Offline, privacy-first grammar checker. Fast, open-source, Rust-powered
Hotkey (#2149)
LoganBrinsmeada3aa72d79056
diff --git a/packages/chrome-plugin/src/ProtocolClient.ts b/packages/chrome-plugin/src/ProtocolClient.tsindex f97ed57b9..6a07259e3 100644--- a/packages/chrome-plugin/src/ProtocolClient.ts+++ b/packages/chrome-plugin/src/ProtocolClient.ts@@ -1,7 +1,7 @@import type { Dialect, LintConfig, LintOptions } from 'harper.js';import type { UnpackedLintGroups } from 'lint-framework';import { LRUCache } from 'lru-cache';-import type { ActivationKey } from './protocol';+import type { ActivationKey, Hotkey } from './protocol';export default class ProtocolClient {private static readonly lintCache = new LRUCache<string, Promise<UnpackedLintGroups>>({@@ -90,6 +90,19 @@ export default class ProtocolClient {return (await chrome.runtime.sendMessage({ kind: 'getActivationKey' })).key;}+ public static async getHotkey(): Promise<Hotkey> {+ return (await chrome.runtime.sendMessage({ kind: 'getHotkey' })).hotkey;+ }++ public static async setHotkey(hotkey: Hotkey): Promise<void> {+ const modifiers = hotkey.modifiers;+ const hotkeyCopy = {+ modifiers: [...modifiers], // Create a new array+ key: hotkey.key,+ };+ await chrome.runtime.sendMessage({ kind: 'setHotkey', hotkey: hotkeyCopy });+ }+public static async setActivationKey(key: ActivationKey): Promise<void> {await chrome.runtime.sendMessage({ kind: 'setActivationKey', key });}diff --git a/packages/chrome-plugin/src/background/index.ts b/packages/chrome-plugin/src/background/index.tsindex dcc068129..3f8bebc52 100644--- a/packages/chrome-plugin/src/background/index.ts+++ b/packages/chrome-plugin/src/background/index.ts@@ -5,6 +5,7 @@ import {ActivationKey,type AddToUserDictionaryRequest,createUnitResponse,+ type GetActivationKeyRequest,type GetActivationKeyResponse,type GetConfigRequest,type GetConfigResponse,@@ -14,6 +15,7 @@ import {type GetDomainStatusRequest,type GetDomainStatusResponse,type GetEnabledDomainsResponse,+ type GetHotkeyResponse,type GetInstalledOnRequest,type GetInstalledOnResponse,type GetLintDescriptionsRequest,@@ -21,6 +23,7 @@ import {type GetReviewedRequest,type GetReviewedResponse,type GetUserDictionaryResponse,+ type Hotkey,type IgnoreLintRequest,type LintRequest,type LintResponse,@@ -34,6 +37,7 @@ import {type SetDefaultStatusRequest,type SetDialectRequest,type SetDomainStatusRequest,+ type SetHotkeyRequest,type SetReviewedRequest,type SetUserDictionaryRequest,type UnitResponse,@@ -154,6 +158,10 @@ function handleRequest(message: Request): Promise<Response> {return handleGetActivationKey();case 'setActivationKey':return handleSetActivationKey(message);+ case 'getHotkey':+ return handleGetHotkey();+ case 'setHotkey':+ return handleSetHotkey(message);case 'openReportError':return handleOpenReportError(message);case 'openOptions':@@ -294,6 +302,21 @@ async function handleSetActivationKey(req: SetActivationKeyRequest): Promise<Unireturn createUnitResponse();}+async function handleGetHotkey(): Promise<GetHotkeyResponse> {+ const hotkey = await getHotkey();++ return { kind: 'getHotkey', hotkey };+}++async function handleSetHotkey(req: SetHotkeyRequest): Promise<UnitResponse> {+ // Create a plain object to avoid proxy cloning issues+ const hotkey = {+ modifiers: [...req.hotkey.modifiers],+ key: req.hotkey.key,+ };+ await setHotkey(hotkey);+}+async function handleOpenReportError(req: OpenReportErrorRequest): Promise<UnitResponse> {const popupState: PopupState = {page: 'report-error',@@ -389,10 +412,19 @@ async function getActivationKey(): Promise<ActivationKey> {return resp.activationKey;}+async function getHotkey(): Promise<Hotkey> {+ const resp = await chrome.storage.local.get({ hotkey: { modifiers: ['Ctrl'], key: 'e' } });+ return resp.hotkey;+}+async function setActivationKey(key: ActivationKey) {await chrome.storage.local.set({ activationKey: key });}+async function setHotkey(hotkey: Hotkey) {+ await chrome.storage.local.set({ hotkey: hotkey });+}+function initializeLinter(dialect: Dialect) {if (linter != null) {linter.dispose();diff --git a/packages/chrome-plugin/src/contentScript/index.ts b/packages/chrome-plugin/src/contentScript/index.tsindex 60edc959c..1764e1f1d 100644--- a/packages/chrome-plugin/src/contentScript/index.ts+++ b/packages/chrome-plugin/src/contentScript/index.ts@@ -18,6 +18,7 @@ const fw = new LintFramework({ignoreLint: (hash) => ProtocolClient.ignoreHash(hash),getActivationKey: () => ProtocolClient.getActivationKey(),+ getHotkey: () => ProtocolClient.getHotkey(),openOptions: () => ProtocolClient.openOptions(),addToUserDictionary: (words) => ProtocolClient.addToUserDictionary(words),reportError: (lint: UnpackedLint, ruleId: string) =>diff --git a/packages/chrome-plugin/src/options/Options.svelte b/packages/chrome-plugin/src/options/Options.svelteindex 01187389b..80827671f 100644--- a/packages/chrome-plugin/src/options/Options.svelte+++ b/packages/chrome-plugin/src/options/Options.svelte@@ -3,6 +3,7 @@ import { Button, Card, Input, Select, Textarea } from 'components';import { Dialect, type LintConfig } from 'harper.js';import logo from '/logo.png';import ProtocolClient from '../ProtocolClient';+import type { Hotkey, Modifier } from '../protocol';import { ActivationKey } from '../protocol';let lintConfig: LintConfig = $state({});@@ -13,6 +14,8 @@ let dialect = $state(Dialect.American);let defaultEnabled = $state(false);let activationKey: ActivationKey = $state(ActivationKey.Off);let userDict = $state('');+let modifyHotkeyButton: Button;+let hotkey: Hotkey = $state({ modifiers: ['Ctrl'], key: 'e' });let anyRulesEnabled = $derived(Object.values(lintConfig ?? {}).some((value) => value !== false));$effect(() => {@@ -32,7 +35,6 @@ $effect(() => {});$effect(() => {- console.log('hit');ProtocolClient.setUserDictionary(stringToDict(userDict));});@@ -56,6 +58,15 @@ ProtocolClient.getActivationKey().then((d) => {activationKey = d;});+ProtocolClient.getHotkey().then((d) => {+ // Ensure we have a plain object, not a Proxy+ hotkey = {+ modifiers: [...d.modifiers],+ key: d.key,+ };+ buttonText = `Hotkey: ${d.modifiers.join('+')}+${d.key}`;+});+ProtocolClient.getUserDictionary().then((d) => {userDict = dictToString(d.toSorted());});@@ -144,6 +155,51 @@ async function exportEnabledDomainsCSV() {console.error('Failed to export enabled domains JSON:', e);}}++let buttonText = $state('Set Hotkey');+let isBlue = $state(false); // modify color of hotkey button once it is pressed+function startHotkeyCapture(_modifyHotkeyButton: Button) {+ buttonText = 'Press desired hotkey combination now.';++ const handleKeydown = (event: KeyboardEvent) => {+ event.preventDefault();++ const modifiers: Modifier[] = [];+ if (event.ctrlKey) modifiers.push('Ctrl');+ if (event.shiftKey) modifiers.push('Shift');+ if (event.altKey) modifiers.push('Alt');++ let key = event.key;++ if (key !== 'Control' && key !== 'Shift' && key !== 'Alt') {+ if (modifiers.length === 0) {+ return;+ }+ buttonText = `Hotkey: ${modifiers.join('+')}+${key}`;+ // Create a plain object to avoid proxy cloning issues+ const newHotkey = {+ modifiers: [...modifiers],+ key: key,+ };++ hotkey = newHotkey;++ // Call ProtocolClient directly with the plain object to avoid proxy issues+ ProtocolClient.setHotkey(newHotkey);++ // Remove listener+ window.removeEventListener('keydown', handleKeydown);++ // change button color+ isBlue = !isBlue;+ }+ };++ // Add temporary key listener+ window.addEventListener('keydown', handleKeydown);+}++// Import removed</script><!-- centered wrapper with side gutters -->@@ -220,6 +276,18 @@ async function exportEnabledDomainsCSV() {</div></div>+ <div class="space-y-5">+ <div class="flex items-center justify-between">+ <div class="flex flex-col">+ <h3 class="text-sm">Apply Last Suggestion Hotkey</h3>+ <p class="text-xs text-gray-600 dark:text-gray-400">Applies suggestion to last highlighted word.</p>+ </div>+ <Textarea readonly bind:value={buttonText} />+ <Button size="sm" color="light" style="background-color: {isBlue ? 'blue' : ''}" bind:this={modifyHotkeyButton} on:click={() => {startHotkeyCapture(modifyHotkeyButton); isBlue = !isBlue}}>Modify Hotkey</Button>++ </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 56f732ce4..b176de18a 100644--- a/packages/chrome-plugin/src/protocol.ts+++ b/packages/chrome-plugin/src/protocol.ts@@ -19,6 +19,8 @@ export type Request =| GetUserDictionaryRequest| GetActivationKeyRequest| SetActivationKeyRequest+ | GetHotkeyRequest+ | SetHotkeyRequest| OpenOptionsRequest| GetInstalledOnRequest| GetReviewedRequest@@ -36,6 +38,7 @@ export type Response =| GetDefaultStatusResponse| GetEnabledDomainsResponse| GetUserDictionaryResponse+ | GetHotkeyResponse| GetActivationKeyResponse| GetInstalledOnResponse| GetReviewedResponse@@ -198,6 +201,10 @@ export type GetActivationKeyRequest = {kind: 'getActivationKey';};+export type GetHotkeyRequest = {+ kind: 'getHotkey';+};+export type GetActivationKeyResponse = {kind: 'getActivationKey';key: ActivationKey;@@ -217,6 +224,22 @@ export type OpenOptionsRequest = {kind: 'openOptions';};+export type GetHotkeyResponse = {+ kind: 'getHotkey';+ hotkey: Hotkey;+};++export type SetHotkeyRequest = {+ kind: 'setHotkey';+ hotkey: Hotkey;+};++export type Modifier = 'Ctrl' | 'Shift' | 'Alt';++export type Hotkey = {+ modifiers: Modifier[];+ key: string;+};export type OpenReportErrorRequest = {kind: 'openReportError';example: string;diff --git a/packages/lint-framework/package.json b/packages/lint-framework/package.jsonindex 26e7b072c..1e8d4e853 100644--- a/packages/lint-framework/package.json+++ b/packages/lint-framework/package.json@@ -31,6 +31,7 @@"harper.js": "workspace:*"},"devDependencies": {+ "@types/chrome": "0.1.27","@types/virtual-dom": "^2.1.4","type-fest": "^4.37.0","typescript": "catalog:",diff --git a/packages/lint-framework/src/lint/LintFramework.ts b/packages/lint-framework/src/lint/LintFramework.tsindex 315a35266..415be9f84 100644--- a/packages/lint-framework/src/lint/LintFramework.ts+++ b/packages/lint-framework/src/lint/LintFramework.ts@@ -1,13 +1,21 @@import type { LintOptions } from 'harper.js';-import type { IgnorableLintBox } from './Box';+import { closestBox, type IgnorableLintBox } from './Box';import computeLintBoxes from './computeLintBoxes';import { isHeading, isVisible } from './domUtils';+import { getCaretPosition } from './editorUtils';import Highlights from './Highlights';import PopupHandler from './PopupHandler';import type { UnpackedLint, UnpackedLintGroups } from './unpackLint';type ActivationKey = 'off' | 'shift' | 'control';+type Modifier = 'Ctrl' | 'Shift' | 'Alt';++type Hotkey = {+ modifiers: Modifier[];+ key: string;+};+/** Events on an input (any kind) that can trigger a re-render. */const INPUT_EVENTS = ['focus', 'keyup', 'paste', 'change', 'scroll'];/** Events on the window that can trigger a re-render. */@@ -22,6 +30,7 @@ export default class LintFramework {private lintRequested = false;private renderRequested = false;private lastLints: { target: HTMLElement; lints: UnpackedLintGroups }[] = [];+ private lastBoxes: IgnorableLintBox[] = [];private lastLintBoxes: IgnorableLintBox[] = [];/** The function to be called to re-render the highlights. This is a variable because it is used to register/deregister event listeners. */@@ -37,6 +46,7 @@ export default class LintFramework {private actions: {ignoreLint?: (hash: string) => Promise<void>;getActivationKey?: () => Promise<ActivationKey>;+ getHotkey?: () => Promise<Hotkey>;openOptions?: () => Promise<void>;addToUserDictionary?: (words: string[]) => Promise<void>;reportError?: (lint: UnpackedLint, ruleId: string) => Promise<void>;@@ -52,6 +62,7 @@ export default class LintFramework {actions: {ignoreLint?: (hash: string) => Promise<void>;getActivationKey?: () => Promise<ActivationKey>;+ getHotkey?: () => Promise<Hotkey>;openOptions?: () => Promise<void>;addToUserDictionary?: (words: string[]) => Promise<void>;reportError?: (lint: UnpackedLint, ruleId: string) => Promise<void>;@@ -141,6 +152,49 @@ export default class LintFramework {this.requestRender();}+ /**+ * Hotkey to apply the suggestion of the most likely word+ */+ public async lintHotkey() {+ const hotkey = await this.actions.getHotkey?.();++ document.addEventListener(+ 'keydown',+ (event: KeyboardEvent) => {+ if (!hotkey) return;++ const key = event.key.toLowerCase();+ const expectedKey = hotkey.key.toLowerCase();++ const hasCtrl = event.ctrlKey === hotkey.modifiers.includes('Ctrl');+ const hasAlt = event.altKey === hotkey.modifiers.includes('Alt');+ const hasShift = event.shiftKey === hotkey.modifiers.includes('Shift');++ const match = key === expectedKey && hasCtrl && hasAlt && hasShift;++ if (match) {+ event.preventDefault();+ event.stopImmediatePropagation();++ const caretPosition = getCaretPosition();++ if (caretPosition != null) {+ const closestIdx = closestBox(caretPosition, this.lastBoxes);++ const previousBox = this.lastBoxes[closestIdx];+ const suggestions = previousBox.lint.suggestions;+ if (suggestions.length > 0) {+ previousBox.applySuggestion(suggestions[0]);+ } else {+ previousBox.ignoreLint?.();+ }+ }+ }+ },+ { capture: true },+ );+ }+public async addTarget(target: Node) {if (!this.targets.has(target)) {this.targets.add(target);@@ -198,6 +252,7 @@ export default class LintFramework {}private attachWindowListeners() {+ this.lintHotkey();for (const event of PAGE_EVENTS) {window.addEventListener(event, this.updateEventCallback);}@@ -227,6 +282,7 @@ export default class LintFramework {this.popupHandler.updateLintBoxes(boxes);this.renderRequested = false;+ this.lastBoxes = boxes;});}}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex c0c0c5022..0f860e631 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -256,6 +256,9 @@ importers:specifier: ^2.1.1version: 2.1.1devDependencies:+ '@types/chrome':+ specifier: 0.1.27+ version: 0.1.27'@types/virtual-dom':specifier: ^2.1.4version: 2.1.4@@ -3853,6 +3856,9 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-MxGxEomGxsJiL9xe/7ZwVgwdn8XVKWbPvxpVQl3nWOjrS0Ce63JsfzxUc4aU3GvRcUPYsfufHmJ17BFyKxeA4g==}+ '@types/[email protected]':+ resolution: {integrity: sha512-pkkCb0Ft8X+Igi751POzT+YqchSxUCtB6s4Gs6ttgSj8qzJga/qlJMgSW1mKxuQTW4i0sTqQbqVtzXDS5AU+4A==}+'@types/[email protected]':resolution: {integrity: sha512-VjFgDF/eB+Aklcy15TtOTLQeMjTo07k7KAjql8OK5Dirr7a6sJY4T1uVBDuTVG9VEmn1uUsohOpYnVfgC6/jyw==}@@ -16409,6 +16415,11 @@ snapshots:'@types/filesystem': 0.0.36'@types/har-format': 1.2.16+ '@types/[email protected]':+ dependencies:+ '@types/filesystem': 0.0.36+ '@types/har-format': 1.2.16+'@types/[email protected]':dependencies:'@types/tern': 0.23.9