Offline, privacy-first grammar checker. Fast, open-source, Rust-powered
feat(chrome-ext): redesign suggestion popup (#4406)
Elijah Potter940bd04799e7
diff --git a/packages/chrome-plugin/tests/google_docs_live.spec.ts b/packages/chrome-plugin/tests/google_docs_live.spec.tsindex 6fdf3aacf..a49842fea 100644--- a/packages/chrome-plugin/tests/google_docs_live.spec.ts+++ b/packages/chrome-plugin/tests/google_docs_live.spec.ts@@ -212,7 +212,7 @@ test.describe('Google Docs live regressions', () => {const opened = await clickHarperHighlight(page);expect(opened).toBe(true);- await page.getByTitle('Replace with "a"').click();+ await page.getByTitle('Click to replace "an" with "a"').click();await expect.poll(() => getGoogleDocsAnnotatedText(page), { timeout: 20000 })@@ -248,7 +248,7 @@ test.describe('Google Docs live regressions', () => {const opened = await clickHarperHighlight(page);expect(opened).toBe(true);- await page.getByTitle('Replace with "a"').click();+ await page.getByTitle('Click to replace "an" with "a"').click();await expect.poll(() => getGoogleDocsAnnotatedText(page), { timeout: 20000 })diff --git a/packages/chrome-plugin/tests/hn.spec.ts b/packages/chrome-plugin/tests/hn.spec.tsindex 7d3043454..eae4ffd87 100644--- a/packages/chrome-plugin/tests/hn.spec.ts+++ b/packages/chrome-plugin/tests/hn.spec.ts@@ -39,6 +39,11 @@ test('Hacker News wraps correctly', async ({ page }) => {{ x: 354.26666259765625, y: 115, width: 64.13333129882812, height: 19 },{ x: 594.7666625976562, y: 98, width: 24.04998779296875, height: 19 },],+ // Current browser-default monospace metrics in the saved page.+ [+ { x: 315.25, y: 115, width: 53.328125, height: 21 },+ { x: 515.171875, y: 96, width: 20.015625, height: 21 },+ ],]);});@@ -60,5 +65,6 @@ test('Hacker News scrolls correctly', async ({ page }) => {await assertHarperHighlightBoxes(page, [[{ x: 216.9375, y: 203, width: 56.171875, height: 17 }],[{ x: 217.98333740234375, y: 221, width: 56.116668701171875, height: 19 }],+ [{ x: 201.96875, y: 231, width: 46.65625, height: 21 }],]);});diff --git a/packages/chrome-plugin/tests/lexical_webcomponent.spec.ts b/packages/chrome-plugin/tests/lexical_webcomponent.spec.tsindex e0b8e7544..a34143885 100644--- a/packages/chrome-plugin/tests/lexical_webcomponent.spec.ts+++ b/packages/chrome-plugin/tests/lexical_webcomponent.spec.ts@@ -26,7 +26,7 @@ test.describe('Lexical webcomponent regression', () => {await expect(mirror).toHaveText(initialText);await clickHarperHighlight(page);- await page.getByTitle('Replace with "a"').click();+ await page.getByTitle('Click to replace "an" with "a"').click();await page.waitForTimeout(3000);const afterFirst = 'This is a test. This is an test again.';@@ -35,7 +35,7 @@ test.describe('Lexical webcomponent regression', () => {await expect(getHarperHighlights(page)).toHaveCount(1);await clickHarperHighlight(page);- await page.getByTitle('Replace with "a"').click();+ await page.getByTitle('Click to replace "an" with "a"').click();await page.waitForTimeout(3000);const finalText = 'This is a test. This is a test again.';diff --git a/packages/chrome-plugin/tests/testUtils.ts b/packages/chrome-plugin/tests/testUtils.tsindex 669f29c87..00cd754ad 100644--- a/packages/chrome-plugin/tests/testUtils.ts+++ b/packages/chrome-plugin/tests/testUtils.ts@@ -85,6 +85,11 @@ export async function replaceEditorContent(editorEl: Locator, text: string, soft}}+/** Locate replacement rows (including explicit empty states) inside Harper's suggestion popup. */+export function getHarperSuggestionRows(page: Page): Locator {+ return page.locator('.harper-container').getByRole('menuitem');+}+/** Locate the Harper highlights on a page. */export function getHarperHighlights(page: Page): Locator {return page.locator('#harper-highlight');@@ -244,7 +249,7 @@ export async function testBasicSuggestion(const opened = await clickHarperHighlight(page);expect(opened).toBe(true);- await page.getByTitle('Replace with "a"').click();+ await page.getByTitle('Click to replace "an" with "a"').click();await page.waitForTimeout(3000);@@ -381,7 +386,7 @@ export async function testMultipleSuggestionsAndUndo(await page.waitForTimeout(4000);await expect(getHarperHighlights(page)).toHaveCount(1);expect(await clickHarperHighlight(page)).toBe(true);- await page.getByTitle('Replace with "test"').click();+ await page.getByTitle('Click to replace "tset" with "test"').click();await page.waitForTimeout(5000);await assertEditorContains(editor, 'test here');@@ -400,7 +405,7 @@ export async function testMultipleSuggestionsAndUndo(await editor.press('ArrowLeft');}- await page.getByTitle('Replace with "test"').click();+ await page.getByTitle('Click to replace "tset" with "test"').click();await page.waitForTimeout(5000);// Verify only second "tset" was correcteddiff --git a/packages/chrome-plugin/tests/typst.spec.ts b/packages/chrome-plugin/tests/typst.spec.tsindex b92295a39..ba164141c 100644--- a/packages/chrome-plugin/tests/typst.spec.ts+++ b/packages/chrome-plugin/tests/typst.spec.ts@@ -19,7 +19,7 @@ test('Typst CodeMirror editor can apply a suggestion', async ({ page }) => {await assertHighlightCount(page, 1);expect(await clickHarperHighlight(page)).toBe(true);- await page.getByTitle('Replace with "a"').click();+ await page.getByTitle('Click to replace "an" with "a"').click();await expect(editor).toContainText('This is a test');});@@ -37,7 +37,7 @@ test('Typst CodeMirror handles multiline suggestions distinctly', async ({ pageawait assertHighlightCount(page, 2);const initialHighlightCount = 2;expect(await clickHarperHighlight(page)).toBe(true);- await page.getByTitle('Replace with "a"').click();+ await page.getByTitle('Click to replace "an" with "a"').click();const editorText = await editor.innerText();expect((editorText.match(/an test/g) ?? []).length).toBe(1);diff --git a/packages/lint-framework/src/lint/PopupHandler.ts b/packages/lint-framework/src/lint/PopupHandler.tsindex 8edf09d71..0d04c7af3 100644--- a/packages/lint-framework/src/lint/PopupHandler.ts+++ b/packages/lint-framework/src/lint/PopupHandler.ts@@ -31,6 +31,7 @@ function monitorActivationKey(export default class PopupHandler {private currentLintBoxes: IgnorableLintBox[];private popupLint: number | undefined;+ private selectedSuggestion = 0;private currentHint: string | null | undefined;private currentHintFor: number | undefined;private renderBox: RenderBox;@@ -82,34 +83,62 @@ export default class PopupHandler {}}- /** Tries to get the current caret position.- * If successful, opens the popup closes to it. */+ /** Open and render the row nearest the editor caret immediately on activation. */private openClosestToCaret() {- const caretPosition = getCaretPosition();+ const host = this.renderBox.getShadowHost();+ const popupFocused = document.activeElement === host;+ const caretPosition = popupFocused ? null : getCaretPosition();+ const closestIdx = caretPosition+ ? closestBox(caretPosition, this.currentLintBoxes)+ : popupFocused+ ? this.popupLint+ : undefined;+ if (closestIdx == null || closestIdx < 0) return;- if (caretPosition != null) {- const closestIdx = closestBox(caretPosition, this.currentLintBoxes);+ this.popupLint = closestIdx;+ this.selectedSuggestion = 0;+ this.render();+ if (popupFocused) this.focusSelectedSuggestion();+ }- if (closestIdx >= 0) {- this.popupLint = closestIdx;- }- }+ /** Focus the active replacement without replacing the renderer's saved editor selection. */+ private focusSelectedSuggestion() {+ const row = this.renderBox+ .getShadowHost()+ .shadowRoot?.querySelector<HTMLElement>('.harper-selected');+ row?.focus({ preventScroll: true });+ row?.scrollIntoView({ block: 'nearest' });}private onPointerDown(e: PointerEvent) {for (let i = 0; i < this.currentLintBoxes.length; i++) {const box = this.currentLintBoxes[i];- if (isPointInBox([e.x, e.y], box)) {+ if (e.composedPath().includes(box.source) && isPointInBox([e.x, e.y], box)) {+ if (this.popupLint != null) this.close();this.popupLint = i;+ this.selectedSuggestion = 0;this.render();return;}}+ this.close();+ }++ private close = () => {this.popupLint = undefined;+ this.selectedSuggestion = 0;this.render();- }+ };++ private onOutsidePointerDown = (event: PointerEvent) => {+ const path = event.composedPath();+ if (path.includes(this.renderBox.getShadowHost())) return;+ // Editor pointer-downs are handled by the existing source listeners.+ if (this.currentLintBoxes.some((box) => path.includes(box.source))) return;+ this.close();+ };private render() {let tree = h('div', {}, []);@@ -120,21 +149,30 @@ export default class PopupHandler {if (this.popupLint != null && this.popupLint < this.currentLintBoxes.length) {const box = this.currentLintBoxes[this.popupLint];- tree = SuggestionBox(box, this.actions, this.currentHint ?? null, () => {- this.popupLint = undefined;- this.updateHint();- this.render();+ tree = SuggestionBox({+ box,+ selectedIndex: this.selectedSuggestion,+ onSelect: (index) => {+ if (index === this.selectedSuggestion) return;+ this.selectedSuggestion = index;+ this.render();+ },+ actions: this.actions,+ hint: this.currentHint ?? null,+ close: this.close,});}this.renderBox.render(tree);if (this.popupLint != null && this.popupLint < this.currentLintBoxes.length) {+ document.addEventListener('pointerdown', this.onOutsidePointerDown, true);host.style.setProperty('visibility', 'visible', 'important');if (host.isConnected && !host.matches(':popover-open')) {host.showPopover();}} else {+ document.removeEventListener('pointerdown', this.onOutsidePointerDown, true);host.style.setProperty('visibility', 'hidden', 'important');if (host.isConnected && host.matches(':popover-open')) {host.hidePopover();@@ -163,14 +201,53 @@ export default class PopupHandler {}}+ /** Preserve logical selection through geometry updates, but never retarget stale row indices. */public updateLintBoxes(boxes: IgnorableLintBox[]) {+ const host = this.renderBox.getShadowHost();+ const popupFocused = document.activeElement === host;this.currentLintBoxes.forEach((b) => {b.source.removeEventListener('pointerdown', this.pointerDownCallback as EventListener);});- if (boxes.length != this.currentLintBoxes.length) {- this.popupLint = undefined;+ const previous = this.popupLint == null ? undefined : this.currentLintBoxes[this.popupLint];+ const previousSelection = previous?.lint.suggestions[this.selectedSuggestion];+ if (previous) {+ // Context hashes are location-agnostic; source and span identify the occurrence.+ // Keep the clicked fragment of a wrapped lint, rather than jumping to its first line.+ const fragment = this.currentLintBoxes+ .slice(0, this.popupLint)+ .filter(+ (box) =>+ box.lint.context_hash === previous.lint.context_hash &&+ box.source === previous.source &&+ box.lint.span.start === previous.lint.span.start &&+ box.lint.span.end === previous.lint.span.end,+ ).length;+ const matches = boxes.flatMap((box, index) =>+ box.lint.context_hash === previous.lint.context_hash &&+ box.source === previous.source &&+ box.lint.span.start === previous.lint.span.start &&+ box.lint.span.end === previous.lint.span.end &&+ box.lint.source === previous.lint.source+ ? [index]+ : [],+ );+ this.popupLint = matches[Math.min(fragment, matches.length - 1)];}+ const next = this.popupLint == null ? undefined : boxes[this.popupLint];+ this.selectedSuggestion =+ next && previousSelection+ ? Math.max(+ 0,+ next.lint.suggestions.findIndex(+ (suggestion) =>+ suggestion.kind === previousSelection.kind &&+ suggestion.replacement_text === previousSelection.replacement_text,+ ),+ )+ : 0;+ // Index changes due to other fields or wrapped rectangles do not start a new hint session.+ if (this.popupLint != null) this.currentHintFor = this.popupLint;this.currentLintBoxes = boxes;this.currentLintBoxes.forEach((b) => {@@ -178,5 +255,8 @@ export default class PopupHandler {});this.render();+ if (popupFocused && this.popupLint != null && !host.shadowRoot?.activeElement) {+ this.focusSelectedSuggestion();+ }}}diff --git a/packages/lint-framework/src/lint/SuggestionBox.ts b/packages/lint-framework/src/lint/SuggestionBox.tsindex 65768040e..a5c6a3834 100644--- a/packages/lint-framework/src/lint/SuggestionBox.ts+++ b/packages/lint-framework/src/lint/SuggestionBox.ts@@ -1,26 +1,21 @@-/** biome-ignore-all lint/complexity/useArrowFunction: It cannot be an arrow function for the logic to work. */-import { type IconDefinition, icon } from '@fortawesome/fontawesome-svg-core';-import { faSliders, faToggleOff } from '@fortawesome/free-solid-svg-icons';+import { icon } from '@fortawesome/fontawesome-svg-core';+import { faSliders } from '@fortawesome/free-solid-svg-icons';import { SuggestionKind } from 'harper.js';-import type { VNode } from 'virtual-dom';-import h from 'virtual-dom/h';+import { h, type VNode } from 'virtual-dom';import bookDownSvg from '../assets/bookDownSvg';-import type { IgnorableLintBox, LintBox } from './Box';-import { type LintKind, lintKindColor, lintKindTextColor } from './lintKindColor';-// Decoupled: actions passed in by framework consumer+import type { Box, IgnorableLintBox } from './Box';+import { type LintKind, lintKindColor } from './lintKindColor';import type { UnpackedLint, UnpackedSuggestion } from './unpackLint';-function iconSvg(definition: IconDefinition): string {- return icon(definition).html.join('');-}--const settingsIconSvg = iconSvg(faSliders);-const disableIconSvg = iconSvg(faToggleOff);+const settingsIconSvg = icon(faSliders).html.join('');+const PANEL_GAP = 6;+const VIEWPORT_MARGIN = 8;-/** Saved cursor restore function, captured when the popup steals focus. */+/** Saved cursor restore function, captured only when the popup first steals focus. */let savedRestore: (() => void) | null = null;function saveCursorState() {+ savedRestore = null;const el = document.activeElement;if (!el || el === document.body || el.tagName.toLowerCase() === 'harper-render-box') return;@@ -51,519 +46,545 @@ function saveCursorState() {}}-/** Deferred so in-flight key events (e.g. Escape) finish before the editor regains focus. */+/** Defer restoration until the closing key event has finished dispatching. */function restoreCursorState() {const restore = savedRestore;- if (!restore) return;savedRestore = null;+ if (!restore) return;setTimeout(() => {try {restore();} catch {- // Range may reference nodes removed by a framework reconciler.+ // A host editor may have replaced the saved selection's DOM nodes.}}, 0);}-var FocusHook: any = function () {};-FocusHook.prototype.hook = function (node: any, _propertyName: any, _previousValue: any) {- if ((node as any).__harperAutofocused) {- return;+function clamp(value: number, min: number, max: number) {+ return Math.max(min, Math.min(value, Math.max(min, max)));+}++/**+ * Position the list at the clicked highlight and anchor the flyout to the list,+ * independently of the selected row or list scroll position.+ * Inputs and outputs are CSS pixels. Panel sizes are measured, not estimated from+ * message length. On narrow viewports, stack the panels instead of clipping them.+ */+function popupPosition(+ anchor: Box,+ viewport: { width: number; height: number },+ list: { width: number; height: number },+ flyout: { width: number; height: number },+) {+ const margin = VIEWPORT_MARGIN;+ const stacked = list.width + PANEL_GAP + flyout.width + margin * 2 > viewport.width;+ const height = stacked ? list.height + PANEL_GAP + flyout.height : list.height;+ const below = anchor.y + anchor.height + 3;+ const flipped = below + height + margin > viewport.height;+ const top = clamp(+ flipped ? anchor.y - height - 3 : below,+ margin,+ viewport.height - height - margin,+ );+ let left = clamp(anchor.x, margin, viewport.width - list.width - margin);+ const opensLeft = left + list.width + PANEL_GAP + flyout.width + margin > viewport.width;+ if (opensLeft && !stacked) {+ left = clamp(left, margin + flyout.width + PANEL_GAP, viewport.width - list.width - margin);}+ const flyoutLeft = stacked ? 0 : opensLeft ? -flyout.width - PANEL_GAP : list.width + PANEL_GAP;+ const flyoutTop = stacked+ ? top + list.height + PANEL_GAP+ : clamp(top, margin, viewport.height - flyout.height - margin);- requestAnimationFrame(() => {- saveCursorState();+ return { top, left, flyoutLeft, flyoutTop: flyoutTop - top, flipped, opensLeft };+}- node.focus();- Object.defineProperty(node, '__harperAutofocused', {- value: true,- enumerable: false,- configurable: false,- });+/**+ * virtual-dom only recognizes hooks inherited from a prototype. This functional+ * adapter pairs each DOM setup with cleanup on replacement or removal; no popup+ * selection state lives in the hook.+ */+function domHook(setup: (node: HTMLElement) => () => void) {+ let cleanup: (() => void) | undefined;+ let frame: number;+ return Object.create({+ hook(node: HTMLElement) {+ if (node.isConnected) {+ cleanup = setup(node);+ } else {+ // Creation hooks run before the node's children have been appended.+ frame = requestAnimationFrame(() => {+ if (node.isConnected) cleanup = setup(node);+ });+ }+ },+ unhook() {+ cancelAnimationFrame(frame);+ cleanup?.();+ },});-};+}-var CloseOnEscapeHook: any = function (this: any, onClose: () => void) {- this.onClose = onClose;-};+/**+ * Measure after attachment and on panel or viewport resize. Autofocus once per+ * popup DOM lifetime, not once per hover render. Clean up observers, listeners,+ * and pending animation frames when virtual-dom replaces the hook.+ */+function popupHook(props: Parameters<typeof SuggestionBox>[0], refocusClose: () => void) {+ return domHook((node) => {+ const list = node.querySelector<HTMLElement>('.harper-container')!;+ const flyout = node.querySelector<HTMLElement>('.harper-flyout')!;+ const measure = () => {+ if (!node.isConnected) return;+ const position = popupPosition(+ props.box,+ { width: window.innerWidth, height: window.innerHeight },+ { width: list.offsetWidth, height: list.offsetHeight },+ { width: flyout.offsetWidth, height: flyout.offsetHeight },+ );+ node.style.top = `${position.top}px`;+ node.style.left = `${position.left}px`;+ flyout.style.left = `${position.flyoutLeft}px`;+ flyout.style.top = `${position.flyoutTop}px`;+ node.style.transformOrigin = `${position.flipped ? 'bottom' : 'top'} ${position.opensLeft ? 'right' : 'left'}`;+ node.style.visibility = 'visible';+ };+ const frame = requestAnimationFrame(() => {+ if (!node.isConnected) return;+ measure();+ if (!node.dataset.autofocused) {+ saveCursorState();+ node.dataset.autofocused = 'true';+ focusRow(node, props.selectedIndex);+ }+ measure();+ });+ const onEscape = (event: KeyboardEvent) => {+ if (event.key !== 'Escape') return;+ event.preventDefault();+ refocusClose();+ };+ const observer = new ResizeObserver(measure);+ observer.observe(list);+ observer.observe(flyout);+ window.addEventListener('resize', measure);+ window.addEventListener('keydown', onEscape);+ return () => {+ cancelAnimationFrame(frame);+ observer.disconnect();+ window.removeEventListener('resize', measure);+ window.removeEventListener('keydown', onEscape);+ };+ });+}-CloseOnEscapeHook.prototype.hook = function (this: { onClose: () => void }, node: HTMLElement) {- const handler = (e: KeyboardEvent) => {- if (e.key === 'Escape') {- this.onClose();- }- };- window.addEventListener('keydown', handler);- (node as any).__harperCloseOnEscapeHandler = handler;-};+function focusRow(root: HTMLElement, index: number) {+ const row = root.querySelector<HTMLElement>(`#harper-suggestion-${index}`);+ row?.focus({ preventScroll: true });+ row?.scrollIntoView({ block: 'nearest', inline: 'nearest' });+}-CloseOnEscapeHook.prototype.unhook = function (this: any, node: HTMLElement) {- const handler = (node as any).__harperCloseOnEscapeHandler;- if (handler) {- window.removeEventListener('keydown', handler);- delete (node as any).__harperCloseOnEscapeHandler;+function suggestionKindToLabel(kind: SuggestionKind): string {+ switch (kind) {+ case SuggestionKind.Replace:+ return 'Replace';+ case SuggestionKind.Remove:+ return 'Remove';+ case SuggestionKind.InsertAfter:+ return 'Insert After';}-};--function header(- title: string,- color: string,- onClose: () => void,- openOptions?: () => Promise<void>,- rule?: string,- setRuleEnabled?: (ruleId: string, enabled: boolean) => Promise<void> | void,-): any {- const closeButton = h(- 'button',- {- className: 'harper-close-btn',- onclick: onClose,- title: 'Close',- 'aria-label': 'Close',- },- '×',- );-- const settingsButton = openOptions- ? h(- 'button',- {- className: 'harper-gear-btn',- onclick: () => {- openOptions();- },- title: 'Settings',- 'aria-label': 'Settings',- innerHTML: settingsIconSvg,- },- [],- )- : undefined;-- const disableRuleButton =- setRuleEnabled && rule- ? h(- 'button',- {- className: 'harper-disable-btn',- onclick: () => {- Promise.resolve(setRuleEnabled(rule, false)).finally(() => {- onClose();- });- },- title: `Disable the ${rule} rule`,- 'aria-label': 'Disable this lint rule',- innerHTML: disableIconSvg,- },- [],- )- : undefined;-- const controlsChildren = [disableRuleButton, settingsButton, closeButton].filter(- (node): node is VNode => node != null,- );- const controls = h('div', { className: 'harper-controls' }, controlsChildren);- const titleEl = h('span', { className: 'harper-title' }, [title]);+}- return h(- 'div',- {- className: 'harper-header',- style: { borderBottom: `2px solid ${color}` },- },- [titleEl, controls],- );+function suggestionLabel(suggestion: UnpackedSuggestion) {+ return suggestion.replacement_text || suggestionKindToLabel(suggestion.kind);}-function body(message_html: string): any {- return h('div', { className: 'harper-body', innerHTML: message_html }, []);+/** Describe the actual edit kind, rather than just repeating the row's visible label. */+function suggestionTitle(suggestion: UnpackedSuggestion, original: string): string {+ switch (suggestion.kind) {+ case SuggestionKind.Replace:+ return `Click to replace "${original}" with "${suggestion.replacement_text}"`;+ case SuggestionKind.Remove:+ return `Click to remove "${original}"`;+ case SuggestionKind.InsertAfter:+ return `Click to insert "${suggestion.replacement_text}" after "${original}"`;+ }}-function button(- label: string,- extraStyle: { [key: string]: string },- onClick: (event: Event) => void,- description?: string,- extraProps: Record<string, unknown> = {},-): any {- const desc = description || label;+function button(label: string, onClick: () => void, props: Record<string, unknown> = {}) {return h('button',{+ type: 'button',className: 'harper-btn',- style: extraStyle,onclick: onClick,- onmousedown: (e: Event) => e.preventDefault(),- title: desc,- type: 'button',- 'aria-label': desc,- ...extraProps,+ onmousedown: (event: MouseEvent) => event.preventDefault(),+ ...props,},label,);}-function footer(leftChildren: any, rightChildren: any) {- const left = h('div', { className: 'harper-child-cont' }, leftChildren);- const right = h('div', { className: 'harper-child-cont' }, rightChildren);- return h('div', { className: 'harper-footer' }, [left, right]);-}--function hintDrawer(hint: string | null): any {+function hintDrawer(hint: string | null): VNode | undefined {if (!hint) return undefined;- return h('div', { className: 'harper-hint-drawer', role: 'note', 'aria-live': 'polite' }, [- h('div', { className: 'harper-hint-content' }, [- h('div', { className: 'harper-hint-icon', 'aria-hidden': 'true' }, '💡'),- h('div', {}, [- h('div', { className: 'harper-hint-title' }, 'Tip'),- h('div', {}, String(hint)),+ return h(+ 'div',+ { className: 'harper-hint-drawer', attributes: { role: 'note', 'aria-live': 'polite' } },+ [+ h('div', { className: 'harper-hint-content' }, [+ h('div', { className: 'harper-hint-icon', attributes: { 'aria-hidden': 'true' } }, '💡'),+ h('div', {}, [h('div', { className: 'harper-hint-title' }, 'Tip'), h('div', {}, hint)]),]),- ]),- ]);+ ],+ );}-function addToDictionary(- box: LintBox,- addToUserDictionary?: (words: string[]) => Promise<void>,-): any {+/** Render one replacement, or a non-applying details row when there are no replacements. */+function suggestionRow(+ suggestion: UnpackedSuggestion | undefined,+ index: number,+ props: Parameters<typeof SuggestionBox>[0],+ apply: () => void,+) {+ const { box } = props;+ const selected = index === props.selectedIndex;+ const label = suggestion ? suggestionLabel(suggestion) : 'No replacements';+ // A stable key preserves keyboard focus when earlier alternatives are removed or reordered.+ const duplicateIndex = suggestion+ ? box.lint.suggestions+ .slice(0, index)+ .filter(+ (candidate) =>+ candidate.kind === suggestion.kind &&+ candidate.replacement_text === suggestion.replacement_text,+ ).length+ : 0;return h('button',{- className: 'harper-btn',- onclick: () => {- addToUserDictionary?.([box.lint.problem_text]);+ key: JSON.stringify([suggestion?.kind, suggestion?.replacement_text, duplicateIndex]),+ id: `harper-suggestion-${index}`,+ type: 'button',+ className: `harper-row${selected ? ' harper-selected' : ''}`,+ tabIndex: selected ? 0 : -1,+ attributes: {+ role: 'menuitem',+ 'aria-controls': 'harper-flyout',+ 'aria-expanded': String(selected),},- title: 'Add word to user dictionary',- 'aria-label': 'Add word to user dictionary',- innerHTML: bookDownSvg,+ title: suggestion+ ? suggestionTitle(suggestion, box.lint.problem_text)+ : `No replacements for "${box.lint.problem_text}"`,+ onmouseenter: () => props.onSelect(index),+ onfocus: () => props.onSelect(index),+ onclick: apply,},- [],+ [+ h(+ 'span',+ {+ className: 'harper-swatch',+ style: { background: lintKindColor(box.lint.lint_kind) },+ attributes: { 'aria-hidden': 'true' },+ },+ [],+ ),+ h('span', { className: 'harper-row-label' }, label),+ h('span', { className: 'harper-chevron', attributes: { 'aria-hidden': 'true' } }, '›'),+ ],);}-function suggestions(- lintKind: LintKind,- suggestions: UnpackedSuggestion[],- apply: (s: UnpackedSuggestion) => void,-): any {- return suggestions.map((s: UnpackedSuggestion, i: number) => {- const label =- s.replacement_text !== '' ? s.replacement_text : String(suggestionKindToLabel(s.kind));- const desc = `Replace with "${label}"`;- const props = i === 0 ? { hook: new FocusHook() } : {};- return button(- label,- { background: lintKindColor(lintKind), color: lintKindTextColor(lintKind) },- () => apply(s),- desc,- props,+/** Show the lint's explanation and secondary actions; applying belongs to the suggestion rows. */+function flyoutPanel(+ box: IgnorableLintBox,+ actions: Parameters<typeof SuggestionBox>[0]['actions'],+ runAndClose: (action: () => void | Promise<void>) => void,+) {+ const lint = box.lint;+ const color = lintKindColor(lint.lint_kind);+ const ignore = box.ignoreLint;+ const children = [+ h(+ 'div',+ { id: 'harper-kind', className: 'harper-kind', style: { borderBottomColor: color } },+ lint.lint_kind_pretty,+ ),+ h('div', { className: 'harper-body', innerHTML: lint.message_html }, []),+ h('div', { className: 'harper-actions' }, [+ ...(ignore+ ? [+ button('Dismiss', () => runAndClose(ignore), {+ className: 'harper-btn harper-dismiss',+ title: 'Ignore this lint',+ }),+ ]+ : []),+ ...(lint.lint_kind === 'Spelling' && actions.addToUserDictionary+ ? [+ button('', () => runAndClose(() => actions.addToUserDictionary!([lint.problem_text])), {+ title: 'Add word to user dictionary',+ attributes: { 'aria-label': 'Add word to user dictionary' },+ innerHTML: bookDownSvg,+ }),+ ]+ : []),+ ]),+ ];+ if (actions.setRuleEnabled && box.rule) {+ children.push(+ button(+ `Disable rule ${box.rule}`,+ () => runAndClose(() => actions.setRuleEnabled!(box.rule, false)),+ {+ className: 'harper-disable',+ title: `Disable the ${box.rule} rule`,+ },+ ),);- });-}--function suggestionKindToLabel(s: SuggestionKind): string {- switch (s) {- case SuggestionKind.Replace:- return 'Replace';- case SuggestionKind.Remove:- return 'Remove';- case SuggestionKind.InsertAfter:- return 'Insert After';}-}--function reportProblemButton(reportError?: () => Promise<void>): any {- if (!reportError) {- return undefined;+ if (actions.reportError) {+ children.push(+ button(+ 'Report',+ () => {+ void actions.reportError!(lint, box.rule);+ },+ {+ className: 'harper-report-link',+ title: 'Report an issue with this lint',+ },+ ),+ );}-return h(- 'button',+ 'div',{- className: 'harper-report-link',- type: 'button',- onclick: () => {- reportError();- },- title: 'Report an issue with this lint',- 'aria-label': 'Report an issue with this lint',+ id: 'harper-flyout',+ className: 'harper-flyout',+ attributes: { role: 'group', 'aria-labelledby': 'harper-kind' },},- 'Report',+ children,);}-function styleTag(lintKind: LintKind) {- return h('style', { id: 'harper-suggestion-style' }, [- `code{- text-decoration: underline solid ${lintKindColor(lintKind)} 2px;- padding:0.125rem;- border-radius:0.25rem- }- .harper-container{- max-width:420px;- max-height:400px;- overflow-y:auto;- background:#ffffff;- border:1px solid #d0d7de;- border-radius:8px;- box-shadow:0 4px 12px rgba(140,149,159,0.3);- padding:8px;- display:flex;- flex-direction:column;- z-index:5000;- font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Helvetica,Arial,sans-serif;- pointer-events:auto- }- .harper-header{- display:flex;- align-items:center;- justify-content:space-between;- font-weight:600;- font-size:14px;- line-height:20px;- color:#1f2328;- padding-bottom:4px;- margin-bottom:4px;- user-select:none- }- .harper-title{- display:flex;- align-items:center;- gap:6px;- }- .harper-body{- font-size:14px;- line-height:20px;- color:#57606a- }- .harper-btn{- display:inline-flex;- align-items:center;- justify-content:center;- gap:4px;- cursor:pointer;- border:none;- border-radius:6px;- padding:3px 6px;- min-height:28px;- font-size:13px;- font-weight:600;- line-height:20px;- transition:background 120ms ease,transform 80ms ease- }- .harper-btn:hover{filter:brightness(0.92)}- .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-disable-btn,- .harper-gear-btn{- background:transparent;- border:none;- cursor:pointer;- font-size:18px;- line-height:1;- color:#57606a;- padding:0 4px;- display:inline-flex;- align-items:center;- justify-content:center;- }- .harper-disable-btn:hover,- .harper-gear-btn:hover{color:#1f2328;}- .harper-disable-btn svg,- .harper-gear-btn svg{- width:18px;- height:18px;- display:block;- }- .harper-disable-btn{- transform: scaleX(-1);- }- .harper-controls{display:flex;align-items:center;gap:3px;}- .harper-child-cont{- display:flex;- flex-wrap:wrap;- justify-content:flex-end;- gap:8px- }- .harper-footer{- display:flex;- flex-wrap:wrap;- justify-content:space-between;- padding:2px;- gap:16px- }-- /* Hint drawer styles */- .harper-hint-drawer{- margin-top:6px;- border-top:1px solid #eaeef2;- background:#f6f8fa;- color:#3e4c59;- border-radius:0 0 6px 6px;- }- .harper-hint-content{- display:flex;- gap:8px;- align-items:flex-start;- padding:8px 10px;- font-size:13px;- line-height:18px;- }- .harper-hint-icon{- flex:0 0 auto;- width:18px;height:18px;- border-radius:50%;- background:#fff3c4;- color:#7c5e10;- display:flex;align-items:center;justify-content:center;- font-weight:700;- }- .harper-hint-title{ font-weight:600; margin-right:6px; color:#1f2328; }-- .fade-in {- animation: fadeIn 100ms ease-in-out forwards;- }-- @keyframes fadeIn {- from {- opacity: 0;- transform: scale(0.95);- }- to {- opacity: 1;- transform: scale(1);- }- }-- @media (prefers-color-scheme:dark){- code{background-color:#1f2d3d;color:#c9d1d9}- .harper-container{- background:#0d1117;- border-color:#30363d;- box-shadow:0 4px 12px rgba(1,4,9,0.85)- }- .harper-header{color:#e6edf3}- .harper-body{color:#8b949e}- .harper-btn{- background:#21262d;- color:#c9d1d9- }- .harper-btn:hover{filter:brightness(1.15)}- .harper-close-btn{color:#8b949e;}- .harper-close-btn:hover{color:#e6edf3;}- .harper-disable-btn,- .harper-gear-btn{color:#8b949e;}- .harper-disable-btn:hover,- .harper-gear-btn:hover{color:#e6edf3;}- .harper-btn[style*="background: #2DA44E"]{background:#238636}- .harper-btn[style*="background: #e5e5e5"]{- background:#4b4b4b;- color:#ffffff- }- .harper-hint-drawer{ border-top-color:#30363d; background:#151b23; color:#9aa4af; }- .harper-hint-icon{ background:#3a2f0b; color:#f2cc60; }- .harper-hint-title{ color:#e6edf3; }- }- .harper-report-link{- margin-top:8px;- align-self:flex-start;- background:none;- border:none;- padding:0;- color:#0969da;- font-size:13px;- font-weight:600;- cursor:pointer;- }- .harper-report-link:hover{text-decoration:underline;}- .harper-report-link:focus{outline:2px solid #0969da; outline-offset:2px;}- @media (prefers-color-scheme:dark){- .harper-report-link{color:#58a6ff;}- }`,- ]);+function listFooter(props: Parameters<typeof SuggestionBox>[0], refocusClose: () => void) {+ const children = [];+ if (props.actions.openOptions) {+ children.push(+ h(+ 'button',+ {+ type: 'button',+ className: 'harper-footer-row',+ title: 'Click to go to Harper settings',+ onclick: () => {+ void props.actions.openOptions!();+ },+ },+ [+ h(+ 'span',+ {+ className: 'harper-settings-icon',+ innerHTML: settingsIconSvg,+ attributes: { 'aria-hidden': 'true' },+ },+ [],+ ),+ 'Go to Harper settings',+ ],+ ),+ );+ }+ children.push(+ button('×', refocusClose, {+ className: 'harper-close-btn',+ title: 'Close',+ attributes: { 'aria-label': 'Close' },+ }),+ );+ return h('div', { className: 'harper-list-footer' }, children);}-function ignoreLint(onIgnore: () => void | Promise<void>): any {- return button(- 'Dismiss',- { background: '#e5e5e5', color: '#000000', fontWeight: 'lighter' },- onIgnore,- 'Ignore this lint',+function styleTag(kind: LintKind) {+ return h(+ 'style',+ { id: 'harper-suggestion-style' },+ `+.harper-popup, .harper-popup * { box-sizing:border-box; }+.harper-popup {+ position:fixed; z-index:5000; visibility:hidden; pointer-events:none;+ font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Helvetica,Arial,sans-serif;+ font-size:13px; line-height:20px; text-align:left; color:#1f2328;+}+.harper-popup button { font-family:inherit; cursor:pointer; }+.harper-container, .harper-flyout {+ background:#ffffff; border:1px solid #d0d7de; border-radius:8px;+ box-shadow:0 4px 12px rgba(140,149,159,0.3); pointer-events:auto;+ max-height:min(400px, calc(100vh - 16px)); overflow-y:auto; overscroll-behavior:contain;+}+.harper-container { position:relative; width:min(210px, calc(100vw - 16px)); padding:4px 0; }+.harper-flyout { position:absolute; width:min(190px, calc(100vw - 16px)); overflow-x:hidden; }+.harper-row {+ display:flex; align-items:center; gap:8px; height:30px; width:100%;+ padding:0 8px 0 10px; border:0; background:transparent; text-align:left;+ transition:background 120ms ease;+}+.harper-selected, .harper-footer-row:hover, .harper-disable:hover { background:rgba(0,0,0,0.045); }+.harper-swatch { width:3px; height:16px; border-radius:2px; flex:0 0 auto; }+.harper-row-label { font-size:13px; font-weight:600; color:#1f2328; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }+.harper-chevron { margin-left:auto; font-size:12px; color:#8b949e; }+.harper-kind { padding:6px 10px; font-size:12px; font-weight:600; border-bottom:2px solid; }+.harper-body { padding:8px 10px; font-size:12px; line-height:17px; color:#57606a; overflow-wrap:anywhere; }+.harper-body p { margin:0; }+.harper-body p + p { margin-top:8px; }+.harper-body code { text-decoration:underline solid ${lintKindColor(kind)} 2px; padding:0.125rem; border-radius:0.25rem; }+.harper-actions { display:flex; flex-wrap:wrap; gap:6px; padding:0 10px 8px; }+.harper-btn {+ display:inline-flex; align-items:center; justify-content:center; gap:4px;+ border:none; border-radius:6px; padding:3px 8px; min-height:24px;+ font-size:12px; font-weight:600; line-height:18px; overflow-wrap:anywhere; max-width:100%;+ transition:background 120ms ease,transform 80ms ease;+}+.harper-btn svg { width:18px; height:18px; }+.harper-btn:hover { filter:brightness(0.92); }+.harper-btn:active { transform:scale(0.97); }+.harper-dismiss { background:#e5e5e5; color:#000000; font-weight:400; }+.harper-disable {+ display:block; width:100%; border:0; border-top:1px solid #eaeef2;+ background:transparent; padding:6px 10px; font-size:11px; color:#8b949e; text-align:left; overflow-wrap:anywhere;+}+.harper-disable:hover { color:#57606a; }+.harper-list-footer { position:relative; border-top:1px solid #eaeef2; margin-top:4px; padding:4px 26px 0 0; min-height:32px; }+.harper-footer-row { display:flex; align-items:center; gap:6px; width:100%; border:0; background:transparent; height:28px; padding:0 10px; font-size:12px; color:#57606a; text-align:left; }+.harper-close-btn { position:absolute; right:4px; top:6px; border:0; background:transparent; color:#57606a; padding:0 4px; font-size:20px; line-height:20px; }+.harper-close-btn:hover { color:#1f2328; }+.harper-settings-icon, .harper-settings-icon svg { display:block; width:14px; height:14px; }+.harper-report-link { display:block; margin:8px 10px; background:none; border:none; padding:0; color:#0969da; font-size:13px; font-weight:600; }+.harper-report-link:hover { text-decoration:underline; }+.harper-popup button:focus-visible { outline:2px solid #0969da; outline-offset:-2px; }+.harper-hint-drawer { margin-top:6px; border-top:1px solid #eaeef2; background:#f6f8fa; color:#3e4c59; border-radius:0 0 6px 6px; }+.harper-hint-content { display:flex; gap:8px; align-items:flex-start; padding:8px 10px; font-size:13px; line-height:18px; }+.harper-hint-icon { flex:0 0 auto; width:18px; height:18px; border-radius:50%; background:#fff3c4; color:#7c5e10; display:flex; align-items:center; justify-content:center; font-weight:700; }+.harper-hint-title { font-weight:600; margin-right:6px; color:#1f2328; }+.fade-in { animation:fadeIn 100ms ease-in-out; }+@keyframes fadeIn { from { opacity:0; transform:scale(0.95); } to { opacity:1; transform:scale(1); } }+@media (max-width:421px) {+ .harper-container, .harper-flyout { max-height:min(400px, calc((100vh - 22px) / 2)); }+}+@media (prefers-reduced-motion:reduce) {+ .fade-in { animation:none; }+ .harper-row, .harper-btn { transition:none; }+ .harper-btn:active { transform:none; }+}+@media (prefers-color-scheme:dark) {+ .harper-popup, .harper-row-label, .harper-hint-title { color:#e6edf3; }+ .harper-container, .harper-flyout { background:#0d1117; border-color:#30363d; box-shadow:0 4px 12px rgba(1,4,9,0.85); }+ .harper-body, .harper-footer-row, .harper-close-btn { color:#8b949e; }+ .harper-body code { background:#1f2d3d; color:#c9d1d9; }+ .harper-selected, .harper-footer-row:hover, .harper-disable:hover { background:rgba(255,255,255,0.06); }+ .harper-disable:hover, .harper-close-btn:hover { color:#e6edf3; }+ .harper-btn { background:#21262d; color:#c9d1d9; }+ .harper-btn:hover { filter:brightness(1.15); }+ .harper-dismiss { background:#4b4b4b; color:#ffffff; }+ .harper-disable, .harper-list-footer, .harper-hint-drawer { border-top-color:#30363d; }+ .harper-hint-drawer { background:#151b23; color:#9aa4af; }+ .harper-hint-icon { background:#3a2f0b; color:#f2cc60; }+ .harper-report-link { color:#58a6ff; }+ .harper-popup button:focus-visible { outline-color:#58a6ff; }+}+`,);}-export default function SuggestionBox(- box: IgnorableLintBox,+/** Render a single lint's replacements and a details flyout; the caller owns selection. */+export default function SuggestionBox(props: {+ box: IgnorableLintBox;+ selectedIndex: number;+ onSelect: (index: number) => void;+ /** Optional consumer capabilities; the popup never persists configuration itself. */actions: {openOptions?: () => Promise<void>;addToUserDictionary?: (words: string[]) => Promise<void>;reportError?: (lint: UnpackedLint, ruleId: string) => Promise<void>;setRuleEnabled?: (ruleId: string, enabled: boolean) => Promise<void> | void;- },- hint: string | null,- close: () => void,-) {- const top = box.y + box.height + 3;- let bottom: number | undefined;- const left = box.x;-- if (top + 400 > window.innerHeight) {- bottom = window.innerHeight - box.y - 3;- }-- const positionStyle: { [key: string]: string } = {- position: 'fixed',- top: bottom ? '' : `${top}px`,- bottom: bottom ? `${bottom}px` : '',- left: `${left}px`,- transformOrigin: `${bottom ? 'bottom' : 'top'} left`,};-- const ignoreLintCallback = box.ignoreLint;-+ hint: string | null;+ close: () => void;+}) {+ const { box, selectedIndex, actions, close } = props;+ const suggestions = box.lint.suggestions.length ? box.lint.suggestions : [undefined];+ const selected = suggestions[selectedIndex];const refocusClose = () => {restoreCursorState();close();};-+ const runAndClose = (action: () => void | Promise<void>) => {+ void Promise.resolve().then(action).catch(console.error).finally(refocusClose);+ };+ const apply = (suggestion: UnpackedSuggestion | undefined) => {+ if (!suggestion) return;+ // Applying owns the new caret position; never restore the pre-edit selection.+ savedRestore = null;+ void Promise.resolve()+ .then(() => box.applySuggestion(suggestion))+ .catch(console.error)+ .finally(close);+ };+ const onKeyDown = (event: KeyboardEvent) => {+ const target = event.target as HTMLElement;+ const root = event.currentTarget as HTMLElement;+ const inList = target.closest('.harper-row') != null;+ if (event.key === 'ArrowLeft' && target.closest('.harper-flyout')) {+ event.preventDefault();+ event.stopPropagation();+ focusRow(root, selectedIndex);+ } else if (inList && ['ArrowDown', 'ArrowUp', 'ArrowRight', 'Enter'].includes(event.key)) {+ event.preventDefault();+ event.stopPropagation();+ if (event.key === 'Enter') apply(selected);+ else if (event.key === 'ArrowRight')+ root.querySelector<HTMLElement>('.harper-flyout button')?.focus({ preventScroll: true });+ else {+ const index =+ (selectedIndex + (event.key === 'ArrowDown' ? 1 : -1) + suggestions.length) %+ suggestions.length;+ props.onSelect(index);+ focusRow(root, index);+ }+ }+ };+ const rowNodes = suggestions.map((suggestion, index) =>+ suggestionRow(suggestion, index, props, () => apply(suggestion)),+ );+ const hint = hintDrawer(props.hint);return h('div',{- className: 'harper-container fade-in',- style: positionStyle,- 'harper-close-on-escape': new CloseOnEscapeHook(refocusClose),+ key: 'harper-suggestion-popup',+ className: 'harper-popup fade-in',+ onkeydown: onKeyDown,+ 'harper-popup-hook': popupHook(props, refocusClose),},[styleTag(box.lint.lint_kind),- header(- box.lint.lint_kind_pretty,- lintKindColor(box.lint.lint_kind),- refocusClose,- actions.openOptions,- box.rule,- actions.setRuleEnabled,- ),- body(box.lint.message_html),- footer(- suggestions(box.lint.lint_kind, box.lint.suggestions, (v) => {- Promise.resolve(box.applySuggestion(v)).finally(() => {- close();- });- }),- [- box.lint.lint_kind === 'Spelling' && actions.addToUserDictionary- ? addToDictionary(box, actions.addToUserDictionary)- : undefined,- ignoreLintCallback- ? ignoreLint(() => ignoreLintCallback().then(refocusClose))- : undefined,- ],- ),- hintDrawer(hint),- actions.reportError- ? reportProblemButton(() => actions.reportError!(box.lint, box.rule))- : undefined,+ h('div', { className: 'harper-container' }, [+ h(+ 'div',+ {+ attributes: {+ role: 'menu',+ 'aria-label': 'Suggestions for this lint',+ 'aria-activedescendant': `harper-suggestion-${selectedIndex}`,+ },+ },+ rowNodes,+ ),+ listFooter(props, refocusClose),+ ...(hint ? [hint] : []),+ ]),+ flyoutPanel(box, actions, runAndClose),],);}