Offline, privacy-first grammar checker. Fast, open-source, Rust-powered
feat(chrome-ext): allow the hotkey to be configured (#1787)
Elijah Potter0106d35d51b0
diff --git a/packages/chrome-plugin/src/PopupHandler.ts b/packages/chrome-plugin/src/PopupHandler.tsindex 5ac7484dd..0b2b4e53c 100644--- a/packages/chrome-plugin/src/PopupHandler.ts+++ b/packages/chrome-plugin/src/PopupHandler.ts@@ -1,18 +1,24 @@import h from 'virtual-dom/h';import { closestBox, isPointInBox, type LintBox } from './Box';import { getCaretPosition } from './editorUtils';+import ProtocolClient from './ProtocolClient';+import { ActivationKey } from './protocol';import RenderBox from './RenderBox';import SuggestionBox from './SuggestionBox';-type DoubleShiftHandler = () => void;+type ActivationHandler = () => void;-function monitorDoubleShift(onDoubleShift: DoubleShiftHandler, interval = 300): () => void {+function monitorActivationKey(+ onActivation: ActivationHandler,+ key: string,+ interval = 300,+): () => void {let lastTime = 0;const handler = (e: KeyboardEvent) => {- if (e.key !== 'Shift') return;+ if (e.key.toLowerCase() !== key.toLowerCase()) return;const now = performance.now();const diff = now - lastTime;- if (diff <= interval && diff > 10) onDoubleShift();+ if (diff <= interval && diff > 10) onActivation();lastTime = now;};window.addEventListener('keydown', handler);@@ -24,6 +30,7 @@ export default class PopupHandler {private popupLint: number | undefined;private renderBox: RenderBox;private pointerDownCallback: (e: PointerEvent) => void;+ private activationKeyListener: (() => void) | undefined;constructor() {this.currentLintBoxes = [];@@ -35,7 +42,25 @@ export default class PopupHandler {this.onPointerDown(e);};- monitorDoubleShift(() => this.openClosestToCaret());+ this.updateActivationKeyListener();++ chrome.storage.onChanged.addListener((changes) => {+ if (changes.activationKey) {+ this.updateActivationKeyListener();+ }+ });+ }++ private updateActivationKeyListener() {+ if (this.activationKeyListener) {+ this.activationKeyListener();+ }++ ProtocolClient.getActivationKey().then((key) => {+ if (key !== ActivationKey.Off) {+ this.activationKeyListener = monitorActivationKey(() => this.openClosestToCaret(), key);+ }+ });}/** Tries to get the current caret position.diff --git a/packages/chrome-plugin/src/ProtocolClient.ts b/packages/chrome-plugin/src/ProtocolClient.tsindex 2d9f89dee..168cf3348 100644--- a/packages/chrome-plugin/src/ProtocolClient.ts+++ b/packages/chrome-plugin/src/ProtocolClient.ts@@ -1,5 +1,6 @@import type { Dialect, LintConfig } from 'harper.js';import { LRUCache } from 'lru-cache';+import type { ActivationKey } from './protocol';import type { UnpackedLint } from './unpackLint';export default class ProtocolClient {@@ -61,6 +62,14 @@ export default class ProtocolClient {await chrome.runtime.sendMessage({ kind: 'setDefaultStatus', enabled });}+ public static async getActivationKey(): Promise<ActivationKey> {+ return (await chrome.runtime.sendMessage({ kind: 'getActivationKey' })).key;+ }++ public static async setActivationKey(key: ActivationKey): Promise<void> {+ await chrome.runtime.sendMessage({ kind: 'setActivationKey', key });+ }+public static async addToUserDictionary(words: string[]): Promise<void> {this.lintCache.clear();await chrome.runtime.sendMessage({ kind: 'addToUserDictionary', words });@@ -79,4 +88,9 @@ export default class ProtocolClient {await chrome.runtime.sendMessage({ kind: 'ignoreLint', contextHash: hash });this.lintCache.clear();}++ public static async openOptions(): Promise<void> {+ // Use background to open options to support content scripts reliably+ await chrome.runtime.sendMessage({ kind: 'openOptions' });+ }}diff --git a/packages/chrome-plugin/src/SuggestionBox.ts b/packages/chrome-plugin/src/SuggestionBox.tsindex f397fe7f7..73e42093e 100644--- a/packages/chrome-plugin/src/SuggestionBox.ts+++ b/packages/chrome-plugin/src/SuggestionBox.ts@@ -57,6 +57,20 @@ function header(title: string, color: string, onClose: () => void): any {'×',);+ const settingsButton = h(+ 'button',+ {+ className: 'harper-gear-btn',+ onclick: () => {+ ProtocolClient.openOptions();+ },+ title: 'Settings',+ 'aria-label': 'Settings',+ },+ '⚙',+ );++ const controls = h('div', { className: 'harper-controls' }, [settingsButton, closeButton]);const titleEl = h('span', {}, title);return h(@@ -65,7 +79,7 @@ function header(title: string, color: string, onClose: () => void): any {className: 'harper-header',style: { borderBottom: `2px solid ${color}` },},- [titleEl, closeButton],+ [titleEl, controls],);}@@ -187,6 +201,9 @@ function styleTag() {.harper-btn:active{transform:scale(0.97)}.harper-close-btn{background:transparent;border:none;cursor:pointer;font-size:20px;line-height:1;color:#57606a;padding:0 4px;}.harper-close-btn:hover{color:#1f2328;}+ .harper-gear-btn{background:transparent;border:none;cursor:pointer;font-size:22px;line-height:1;color:#57606a;padding:0 4px;}+ .harper-gear-btn:hover{color:#1f2328;}+ .harper-controls{display:flex;align-items:center;gap:6px;}.harper-child-cont{display:flex;flex-wrap:wrap;@@ -226,6 +243,8 @@ function styleTag() {.harper-btn:hover{filter:brightness(1.15)}.harper-close-btn{color:#8b949e;}.harper-close-btn:hover{color:#e6edf3;}+ .harper-gear-btn{color:#8b949e;}+ .harper-gear-btn:hover{color:#e6edf3;}.harper-btn[style*="background: #2DA44E"]{background:#238636}.harper-btn[style*="background: #e5e5e5"]{background:#4b4b4b;diff --git a/packages/chrome-plugin/src/background/index.ts b/packages/chrome-plugin/src/background/index.tsindex c480c195b..7245e2029 100644--- a/packages/chrome-plugin/src/background/index.ts+++ b/packages/chrome-plugin/src/background/index.ts@@ -1,7 +1,10 @@import { BinaryModule, Dialect, type LintConfig, LocalLinter } from 'harper.js';import {+ ActivationKey,type AddToUserDictionaryRequest,createUnitResponse,+ type GetActivationKeyRequest,+ type GetActivationKeyResponse,type GetConfigRequest,type GetConfigResponse,type GetDefaultStatusResponse,@@ -17,6 +20,7 @@ import {type LintResponse,type Request,type Response,+ type SetActivationKeyRequest,type SetConfigRequest,type SetDefaultStatusRequest,type SetDialectRequest,@@ -125,6 +129,13 @@ function handleRequest(message: Request): Promise<Response> {return handleGetUserDictionary();case 'setUserDictionary':return handleSetUserDictionary(message);+ case 'getActivationKey':+ return handleGetActivationKey();+ case 'setActivationKey':+ return handleSetActivationKey(message);+ case 'openOptions':+ chrome.runtime.openOptionsPage();+ return createUnitResponse();}}@@ -220,6 +231,21 @@ async function handleGetUserDictionary(): Promise<GetUserDictionaryResponse> {return { kind: 'getUserDictionary', words: dict };}+async function handleGetActivationKey(): Promise<GetActivationKeyResponse> {+ const key = await getActivationKey();++ return { kind: 'getActivationKey', key };+}++async function handleSetActivationKey(req: SetActivationKeyRequest): Promise<UnitResponse> {+ if (!Object.values(ActivationKey).includes(req.key)) {+ throw new Error(`Invalid activation key: ${req.key}`);+ }+ await setActivationKey(req.key);++ return createUnitResponse();+}+/** Set the lint configuration inside the global `linter` and in permanent storage. */async function setLintConfig(lintConfig: LintConfig): Promise<void> {await linter.setLintConfig(lintConfig);@@ -257,6 +283,15 @@ async function getDialect(): Promise<Dialect> {return resp.dialect;}+async function getActivationKey(): Promise<ActivationKey> {+ const resp = await chrome.storage.local.get({ activationKey: ActivationKey.Off });+ return resp.activationKey;+}++async function setActivationKey(key: ActivationKey) {+ await chrome.storage.local.set({ activationKey: key });+}+function initializeLinter(dialect: Dialect) {linter = new LocalLinter({binary: new BinaryModule(chrome.runtime.getURL('./wasm/harper_wasm_bg.wasm')),diff --git a/packages/chrome-plugin/src/options/Options.svelte b/packages/chrome-plugin/src/options/Options.svelteindex 3b7898bd7..ead757470 100644--- a/packages/chrome-plugin/src/options/Options.svelte+++ b/packages/chrome-plugin/src/options/Options.svelte@@ -3,6 +3,7 @@ import { Button, Checkbox, Input, Select, Toggle } from 'flowbite-svelte';import { Dialect, type LintConfig } from 'harper.js';import logo from '/logo.png';import ProtocolClient from '../ProtocolClient';+import { ActivationKey } from '../protocol';let lintConfig: LintConfig = $state({});let lintDescriptions: Record<string, string> = $state({});@@ -10,6 +11,7 @@ let searchQuery = $state('');let searchQueryLower = $derived(searchQuery.toLowerCase());let dialect = $state(Dialect.American);let defaultEnabled = $state(false);+let activationKey: ActivationKey = $state(ActivationKey.Off);let userDict = $state('');$effect(() => {@@ -24,6 +26,10 @@ $effect(() => {ProtocolClient.setDefaultEnabled(defaultEnabled);});+$effect(() => {+ ProtocolClient.setActivationKey(activationKey);+});+$effect(() => {console.log('hit');ProtocolClient.setUserDictionary(stringToDict(userDict));@@ -45,6 +51,10 @@ ProtocolClient.getDefaultEnabled().then((d) => {defaultEnabled = d;});+ProtocolClient.getActivationKey().then((d) => {+ activationKey = d;+});+ProtocolClient.getUserDictionary().then((d) => {userDict = dictToString(d.toSorted());});@@ -122,6 +132,20 @@ export function dictToString(values: string[]): string {</div></div>+ <div class="space-y-5">+ <div class="flex items-center justify-between">+ <div class="flex flex-col">+ <span class="font-medium">Activation Key</span>+ <span class="font-light">If you're finding that you're accidentally triggering Harper.</span>+ </div>+ <Select size="sm" color="primary" class="w-44" bind:value={activationKey}>+ <option value={ActivationKey.Shift}>Double Shift</option>+ <option value={ActivationKey.Control}>Double Control</option>+ <option value={ActivationKey.Off}>Off</option>+ </Select>+ </div>+ </div>+<div class="space-y-5"><div class="flex items-center justify-between"><div class="flex flex-col">diff --git a/packages/chrome-plugin/src/protocol.ts b/packages/chrome-plugin/src/protocol.tsindex 202be09f8..5f5fdce86 100644--- a/packages/chrome-plugin/src/protocol.ts+++ b/packages/chrome-plugin/src/protocol.ts@@ -15,7 +15,10 @@ export type Request =| AddToUserDictionaryRequest| SetUserDictionaryRequest| IgnoreLintRequest- | GetUserDictionaryRequest;+ | GetUserDictionaryRequest+ | GetActivationKeyRequest+ | SetActivationKeyRequest+ | OpenOptionsRequest;export type Response =| LintResponse@@ -25,7 +28,8 @@ export type Response =| GetDialectResponse| GetDomainStatusResponse| GetDefaultStatusResponse- | GetUserDictionaryResponse;+ | GetUserDictionaryResponse+ | GetActivationKeyResponse;export type LintRequest = {kind: 'lint';@@ -138,3 +142,27 @@ export type UnitResponse = {export function createUnitResponse(): UnitResponse {return { kind: 'unit' };}++export enum ActivationKey {+ Off = 'off',+ Shift = 'shift',+ Control = 'control',+}++export type GetActivationKeyRequest = {+ kind: 'getActivationKey';+};++export type GetActivationKeyResponse = {+ kind: 'getActivationKey';+ key: ActivationKey;+};++export type SetActivationKeyRequest = {+ kind: 'setActivationKey';+ key: ActivationKey;+};++export type OpenOptionsRequest = {+ kind: 'openOptions';+};