Offline, privacy-first grammar checker. Fast, open-source, Rust-powered
feat(chrome-ext): add delay option (#3166)
Elijah Potterb21e2c17f700
diff --git a/packages/chrome-plugin/src/ProtocolClient.ts b/packages/chrome-plugin/src/ProtocolClient.tsindex 84a89603f..96d668e67 100644--- a/packages/chrome-plugin/src/ProtocolClient.ts+++ b/packages/chrome-plugin/src/ProtocolClient.ts@@ -60,6 +60,14 @@ export default class ProtocolClient {await chrome.runtime.sendMessage({ kind: 'setDialect', dialect });}+ public static async getDelay(): Promise<number> {+ return (await chrome.runtime.sendMessage({ kind: 'getDelay' })).delay;+ }++ public static async setDelay(delay: number): Promise<void> {+ await chrome.runtime.sendMessage({ kind: 'setDelay', delay });+ }+public static async getDomainEnabled(domain: string): Promise<boolean> {this.lintCache.clear();return (await chrome.runtime.sendMessage({ kind: 'getDomainStatus', domain })).enabled;@@ -74,7 +82,12 @@ export default class ProtocolClient {enabled: boolean,overrideValue = true,): Promise<void> {- await chrome.runtime.sendMessage({ kind: 'setDomainStatus', enabled, domain, overrideValue });+ await chrome.runtime.sendMessage({+ kind: 'setDomainStatus',+ enabled,+ domain,+ overrideValue,+ });}public static async getDefaultEnabled(): Promise<boolean> {@@ -173,7 +186,11 @@ export default class ProtocolClient {public static async addWeirpack(filename: string, bytes: Uint8Array): Promise<void> {this.lintCache.clear();- await chrome.runtime.sendMessage({ kind: 'addWeirpack', filename, bytes: Array.from(bytes) });+ await chrome.runtime.sendMessage({+ kind: 'addWeirpack',+ filename,+ bytes: Array.from(bytes),+ });}public static async removeWeirpack(id: string): Promise<void> {diff --git a/packages/chrome-plugin/src/background/index.ts b/packages/chrome-plugin/src/background/index.tsindex 3792011ec..9a939a688 100644--- a/packages/chrome-plugin/src/background/index.ts+++ b/packages/chrome-plugin/src/background/index.ts@@ -16,6 +16,8 @@ import {type GetConfigRequest,type GetConfigResponse,type GetDefaultStatusResponse,+ type GetDelayRequest,+ type GetDelayResponse,type GetDialectRequest,type GetDialectResponse,type GetDomainStatusRequest,@@ -44,6 +46,7 @@ import {type SetActivationKeyRequest,type SetConfigRequest,type SetDefaultStatusRequest,+ type SetDelayRequest,type SetDialectRequest,type SetDomainStatusRequest,type SetHotkeyRequest,@@ -59,7 +62,9 @@ console.log('background is running');chrome.runtime.onInstalled.addListener((details) => {if (details.reason === chrome.runtime.OnInstalledReason.INSTALL) {chrome.runtime.setUninstallURL('https://writewithharper.com/uninstall-browser-extension');- chrome.tabs.create({ url: 'https://writewithharper.com/install-browser-extension' });+ chrome.tabs.create({+ url: 'https://writewithharper.com/install-browser-extension',+ });}});@@ -165,6 +170,10 @@ function handleRequest(message: Request, sender?: chrome.runtime.MessageSender):return handleSetDialect(message);case 'getDialect':return handleGetDialect(message);+ case 'getDelay':+ return handleGetDelay(message);+ case 'setDelay':+ return handleSetDelay(message);case 'getDomainStatus':return handleGetDomainStatus(message);case 'setDomainStatus':@@ -303,6 +312,16 @@ async function handleGetDialect(_req: GetDialectRequest): Promise<GetDialectRespreturn { kind: 'getDialect', dialect: await getDialect() };}+async function handleGetDelay(_req: GetDelayRequest): Promise<GetDelayResponse> {+ return { kind: 'getDelay', delay: await getDelay() };+}++async function handleSetDelay(req: SetDelayRequest): Promise<UnitResponse> {+ await setDelay(req.delay);++ return createUnitResponse();+}+async function handleIgnoreLint(req: IgnoreLintRequest): Promise<UnitResponse> {await ensureLinterReady();await linter.ignoreLintHash(BigInt(req.contextHash));@@ -355,7 +374,10 @@ async function handleGetLintDescriptions(_req: GetLintDescriptionsRequest,): Promise<GetLintDescriptionsResponse> {await ensureLinterReady();- return { kind: 'getLintDescriptions', descriptions: await linter.getLintDescriptionsHTML() };+ return {+ kind: 'getLintDescriptions',+ descriptions: await linter.getLintDescriptionsHTML(),+ };}async function handleSetUserDictionary(req: SetUserDictionaryRequest): Promise<UnitResponse> {@@ -565,12 +587,16 @@ async function getDialect(): Promise<Dialect> {}async function getActivationKey(): Promise<ActivationKey> {- const resp = await chrome.storage.local.get({ activationKey: ActivationKey.Off });+ const resp = await chrome.storage.local.get({+ activationKey: ActivationKey.Off,+ });return resp.activationKey;}async function getHotkey(): Promise<Hotkey> {- const resp = await chrome.storage.local.get({ hotkey: { modifiers: ['Ctrl'], key: 'e' } });+ const resp = await chrome.storage.local.get({+ hotkey: { modifiers: ['Ctrl'], key: 'e' },+ });return resp.hotkey;}@@ -607,6 +633,18 @@ async function setDialect(dialect: Dialect) {await initializeLinter(dialect);}+async function setDelay(delay: number) {+ const normalizedDelay = Number.isFinite(delay) ? Math.max(0, Math.trunc(delay)) : 0;+ await chrome.storage.local.set({ delay: normalizedDelay });+}++async function getDelay(): Promise<number> {+ const resp = await chrome.storage.local.get({ delay: 300 });+ const { delay } = resp;++ return typeof delay === 'number' && Number.isFinite(delay) && delay >= 0 ? delay : 0;+}+/** Format the key to be used in local storage to store domain status. */function formatDomainKey(domain: string): string {return `domainStatus ${domain}`;@@ -758,7 +796,9 @@ async function setStoredWeirpacks(weirpacks: StoredWeirpack[]): Promise<void> {}async function getStoredWeirpacks(): Promise<StoredWeirpack[]> {- const response = await chrome.storage.local.get({ [WEIRPACKS_KEY]: [] as StoredWeirpack[] });+ const response = await chrome.storage.local.get({+ [WEIRPACKS_KEY]: [] as StoredWeirpack[],+ });const value = response[WEIRPACKS_KEY];return Array.isArray(value) ? value : [];}diff --git a/packages/chrome-plugin/src/contentScript/index.ts b/packages/chrome-plugin/src/contentScript/index.tsindex 9f70db295..95c625ec3 100644--- a/packages/chrome-plugin/src/contentScript/index.ts+++ b/packages/chrome-plugin/src/contentScript/index.ts@@ -21,6 +21,7 @@ const fw = new LintFramework(ignoreLint: (hash) => ProtocolClient.ignoreHash(hash),getActivationKey: () => ProtocolClient.getActivationKey(),getHotkey: () => ProtocolClient.getHotkey(),+ getDelay: () => ProtocolClient.getDelay(),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 d3bffb23e..37b5d7268 100644--- a/packages/chrome-plugin/src/options/Options.svelte+++ b/packages/chrome-plugin/src/options/Options.svelte@@ -19,6 +19,8 @@ let searchQuery = $state('');let searchQueryLower = $derived(searchQuery.toLowerCase());let expandedGroups: Record<string, boolean> = $state({});let dialect = $state(Dialect.American);+let delay = $state(0);+let delayLoaded = $state(false);let defaultEnabled = $state(false);let activationKey: ActivationKey = $state(ActivationKey.Off);let userDict = $state('');@@ -37,6 +39,12 @@ $effect(() => {ProtocolClient.setDialect(dialect);});+$effect(() => {+ if (delayLoaded) {+ ProtocolClient.setDelay(delay);+ }+});+$effect(() => {ProtocolClient.setDefaultEnabled(defaultEnabled);});@@ -63,6 +71,11 @@ ProtocolClient.getDialect().then((d) => {dialect = d;});+ProtocolClient.getDelay().then((value) => {+ delay = value;+ delayLoaded = true;+});+ProtocolClient.getDefaultEnabled().then((d) => {defaultEnabled = d;});@@ -329,11 +342,7 @@ async function removeWeirpack(id: string) {<div class="space-y-5"><div class="flex items-center justify-between"><h3 class="text-sm">English Dialect</h3>- <Select- size="sm"- class="w-44"- bind:value={dialect}- >+ <Select size="sm" class="w-44" bind:value={dialect}><option value={Dialect.American}>🇺🇸 American</option><option value={Dialect.British}>🇬🇧 British</option><option value={Dialect.Australian}>🇦🇺 Australian</option>@@ -347,9 +356,34 @@ async function removeWeirpack(id: string) {<div class="flex items-center justify-between"><div class="flex flex-col"><h3 class="text-sm">Enable on New Sites by Default</h3>- <p class="text-xs text-gray-600 dark:text-gray-400">Can make some apps behave abnormally.</p>+ <p class="text-xs text-gray-600 dark:text-gray-400">+ Can make some apps behave abnormally.+ </p>+ </div>+ <input+ type="checkbox"+ bind:checked={defaultEnabled}+ class="h-5 w-5"+ />+ </div>+ </div>++ <div class="space-y-5">+ <div class="flex items-center justify-between gap-4">+ <div class="flex flex-col">+ <h3 class="text-sm">Delay</h3>+ <p class="text-xs text-gray-600 dark:text-gray-400">+ Wait this many milliseconds after typing stops before refreshing+ highlights.+ </p></div>- <input type="checkbox" bind:checked={defaultEnabled} class="h-5 w-5" />+ <input+ type="number"+ min="0"+ step="50"+ bind:value={delay}+ class="w-44 rounded-lg border border-cream-200 bg-white px-3 py-2.5 text-sm text-gray-900 shadow-sm outline-none transition focus:border-cream-300 focus:ring-2 focus:ring-primary-300 dark:border-cream-700 dark:bg-cream-900 dark:text-white dark:focus:border-cream-600 dark:focus:ring-primary-600"+ /></div></div>@@ -357,9 +391,13 @@ async function removeWeirpack(id: string) {<div class="flex items-center justify-between"><div class="flex flex-col"><h3 class="text-sm">Export Enabled Domains</h3>- <p class="text-xs text-gray-600 dark:text-gray-400">Downloads JSON of domains explicitly enabled.</p>+ <p class="text-xs text-gray-600 dark:text-gray-400">+ Downloads JSON of domains explicitly enabled.+ </p></div>- <Button size="sm" on:click={exportEnabledDomainsCSV}>Export JSON</Button>+ <Button size="sm" on:click={exportEnabledDomainsCSV}+ >Export JSON</Button+ ></div></div>@@ -371,11 +409,7 @@ async function removeWeirpack(id: string) {If you're finding that you're accidentally triggering Harper.</p></div>- <Select- size="sm"- class="w-44"- bind:value={activationKey}- >+ <Select size="sm" 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>@@ -387,11 +421,21 @@ async function removeWeirpack(id: string) {<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>+ <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>-+ <Button+ size="sm"+ color="light"+ style="background-color: {isBlue ? 'blue' : ''}"+ bind:this={modifyHotkeyButton}+ on:click={() => {+ startHotkeyCapture(modifyHotkeyButton);+ isBlue = !isBlue;+ }}>Modify Hotkey</Button+ ></div></div>@@ -399,14 +443,13 @@ async function removeWeirpack(id: string) {<div class="flex items-center justify-between"><div class="flex flex-col"><h3 class="text-sm">User Dictionary</h3>- <p class="text-xs text-gray-600 dark:text-gray-400">Each word should be on its own line.</p>+ <p class="text-xs text-gray-600 dark:text-gray-400">+ Each word should be on its own line.+ </p></div>- <Textarea- bind:value={userDict}- ></Textarea>+ <Textarea bind:value={userDict}></Textarea></div></div>-</Card><Card class="space-y-4">@@ -414,8 +457,11 @@ async function removeWeirpack(id: string) {<div class="space-y-2 flex flex-row w-full justify-between"><p class="text-xs text-gray-600 dark:text-gray-400">- Upload one or more <code>.weirpack</code> files to add custom rule packs.- <a href="https://writewithharper.com/docs/weir#Weirpacks">What is a Weirpack?</a>+ Upload one or more <code>.weirpack</code> files to add custom rule+ packs.+ <a href="https://writewithharper.com/docs/weir#Weirpacks"+ >What is a Weirpack?</a+ ></p><inputtype="file"@@ -432,16 +478,24 @@ async function removeWeirpack(id: string) {{/if}{#if weirpacks.length === 0}- <p class="text-sm text-gray-600 dark:text-gray-400">No Weirpacks installed.</p>+ <p class="text-sm text-gray-600 dark:text-gray-400">+ No Weirpacks installed.+ </p>{:else}<div class="space-y-3">{#each weirpacks as weirpack}- <div class="flex items-center justify-between gap-3 rounded-md border border-primary-100 p-3">+ <div+ class="flex items-center justify-between gap-3 rounded-md border border-primary-100 p-3"+ ><div class="min-w-0"><p class="truncate text-sm">- {weirpack.name}{weirpack.version ? ` v${weirpack.version}` : ''}+ {weirpack.name}{weirpack.version+ ? ` v${weirpack.version}`+ : ""}+ </p>+ <p class="truncate text-xs text-gray-600 dark:text-gray-400">+ {weirpack.filename}</p>- <p class="truncate text-xs text-gray-600 dark:text-gray-400">{weirpack.filename}</p></div><Buttonsize="sm"@@ -469,26 +523,27 @@ async function removeWeirpack(id: string) {/></div><div class="flex flex-wrap gap-3">- <Button size="sm" on:click={resetRulesToDefaults}>Reset to Default Rules</Button>+ <Button size="sm" on:click={resetRulesToDefaults}+ >Reset to Default Rules</Button+ ><Button size="sm" on:click={toggleAllRules}>- {anyRulesEnabled ? 'Disable All Rules' : 'Enable All Rules'}+ {anyRulesEnabled ? "Disable All Rules" : "Enable All Rules"}</Button></div>- <div class="rule-scroll space-y-4 max-h-80 overflow-y-auto pr-1">- {#key displayStructuredSettings.length}- <StructuredRuleSettings- settings={displayStructuredSettings}- {lintConfig}- {lintDescriptions}- {searchQueryLower}- {expandedGroups}- handleLintConfigChange={updateLintConfig}- handleToggleGroup={toggleGroup}- />- {/key}- </div>-- </Card>- </div>+ <div class="rule-scroll space-y-4 max-h-80 overflow-y-auto pr-1">+ {#key displayStructuredSettings.length}+ <StructuredRuleSettings+ settings={displayStructuredSettings}+ {lintConfig}+ {lintDescriptions}+ {searchQueryLower}+ {expandedGroups}+ handleLintConfigChange={updateLintConfig}+ handleToggleGroup={toggleGroup}+ />+ {/key}+ </div>+ </Card>+ </div></div>diff --git a/packages/chrome-plugin/src/protocol.ts b/packages/chrome-plugin/src/protocol.tsindex 8c18696e5..092af8ee8 100644--- a/packages/chrome-plugin/src/protocol.ts+++ b/packages/chrome-plugin/src/protocol.ts@@ -9,6 +9,8 @@ export type Request =| GetLintDescriptionsRequest| SetDialectRequest| GetDialectRequest+ | GetDelayRequest+ | SetDelayRequest| SetDomainStatusRequest| SetDefaultStatusRequest| GetDomainStatusRequest@@ -39,6 +41,7 @@ export type Response =| UnitResponse| GetLintDescriptionsResponse| GetDialectResponse+ | GetDelayResponse| GetDomainStatusResponse| GetDefaultStatusResponse| GetEnabledDomainsResponse@@ -90,6 +93,20 @@ export type SetDialectRequest = {dialect: Dialect;};+export type GetDelayRequest = {+ kind: 'getDelay';+};++export type GetDelayResponse = {+ kind: 'getDelay';+ delay: number;+};++export type SetDelayRequest = {+ kind: 'setDelay';+ delay: number;+};+export type GetLintDescriptionsRequest = {kind: 'getLintDescriptions';};diff --git a/packages/chrome-plugin/tests/options_delay.spec.ts b/packages/chrome-plugin/tests/options_delay.spec.tsnew file mode 100644index 000000000..a77141c1e--- /dev/null+++ b/packages/chrome-plugin/tests/options_delay.spec.ts@@ -0,0 +1,20 @@+import { expect, test } from './fixtures';+import { getBackground, getStoredDelay } from './testUtils';++test.describe('options delay setting', () => {+ test.describe.configure({ mode: 'serial' });+ test.setTimeout(90_000);+ test.skip(+ ({ browserName }) => browserName === 'firefox',+ 'Firefox MV3 background context is not exposed reliably in playwright-webextext.',+ );++ test('persists the delay setting in storage', async ({ context }) => {+ const background = await getBackground(context);+ await background.evaluate(async () => {+ await chrome.storage.local.set({ delay: 750 });+ });++ await expect.poll(() => getStoredDelay(context)).toBe(750);+ });+});diff --git a/packages/chrome-plugin/tests/testUtils.ts b/packages/chrome-plugin/tests/testUtils.tsindex 56f590794..165043237 100644--- a/packages/chrome-plugin/tests/testUtils.ts+++ b/packages/chrome-plugin/tests/testUtils.ts@@ -47,6 +47,14 @@ export async function getStoredLintConfig(context: BrowserContext): Promise<Lint});}+export async function getStoredDelay(context: BrowserContext): Promise<number> {+ const background = await getBackground(context);+ return await background.evaluate(async () => {+ const value = await chrome.storage.local.get({ delay: 0 });+ return typeof value.delay === 'number' ? value.delay : 0;+ });+}+/** Locate the [`Slate`](https://www.slatejs.org/examples/richtext) editor on the page. */export function getSlateEditor(page: Page): Locator {return page.locator('[data-slate-editor="true"]');diff --git a/packages/lint-framework/src/lint/LintFramework.ts b/packages/lint-framework/src/lint/LintFramework.tsindex 36523607a..71893151e 100644--- a/packages/lint-framework/src/lint/LintFramework.ts+++ b/packages/lint-framework/src/lint/LintFramework.ts@@ -16,6 +16,17 @@ type Hotkey = {key: string;};+type FrameworkActions = {+ ignoreLint?: (hash: string) => Promise<void>;+ getActivationKey?: () => Promise<ActivationKey>;+ getHotkey?: () => Promise<Hotkey>;+ getDelay?: () => Promise<number>;+ openOptions?: () => Promise<void>;+ addToUserDictionary?: (words: string[]) => Promise<void>;+ reportError?: (lint: UnpackedLint, ruleId: string) => Promise<void>;+ setRuleEnabled?: (ruleId: string, enabled: boolean) => Promise<void> | void;+};+/** 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. */@@ -29,6 +40,7 @@ export default class LintFramework {private scrollableAncestors: Set<HTMLElement>;private lintRequested = false;private renderRequested = false;+ private lastInputAt = 0;private lastLints: { target: HTMLElement; lints: UnpackedLintGroups }[] = [];private lastBoxes: IgnorableLintBox[] = [];private lastLintBoxes: IgnorableLintBox[] = [];@@ -43,15 +55,7 @@ export default class LintFramework {options?: LintOptions,) => Promise<UnpackedLintGroups>;/** Actions wired by host environment (extension/app). */- 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>;- setRuleEnabled?: (ruleId: string, enabled: boolean) => Promise<void> | void;- };+ private actions: FrameworkActions;constructor(lintProvider: (@@ -59,15 +63,7 @@ export default class LintFramework {domain: string,options?: LintOptions,) => Promise<UnpackedLintGroups>,- 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>;- setRuleEnabled?: (ruleId: string, enabled: boolean) => Promise<void> | void;- },+ actions: FrameworkActions,) {this.lintProvider = lintProvider;this.actions = actions;@@ -84,6 +80,7 @@ export default class LintFramework {this.lastLints = [];this.updateEventCallback = () => {+ this.lastInputAt = Date.now();this.update();};@@ -121,6 +118,11 @@ export default class LintFramework {return;}+ const delay = (await this.actions.getDelay?.()) ?? 0;+ if (delay > 0 && Date.now() - this.lastInputAt < delay) {+ return;+ }+// Avoid duplicate requests in the queuethis.lintRequested = true;