Offline, privacy-first grammar checker. Fast, open-source, Rust-powered
fix(chrome-ext): shifting highlights after cursor during delay (#3446)
Elijah Potter38fb84aadddc
diff --git a/packages/chrome-plugin/tests/simple_textarea.spec.ts b/packages/chrome-plugin/tests/simple_textarea.spec.tsindex f4405b896..ac2dcd76a 100644--- a/packages/chrome-plugin/tests/simple_textarea.spec.ts+++ b/packages/chrome-plugin/tests/simple_textarea.spec.ts@@ -1,8 +1,10 @@-import { test } from './fixtures';+import { expect, test } from './fixtures';import {assertHarperHighlightBoxes,assertLocatorIsFocused,clickHarperHighlight,+ getBackground,+ getHarperHighlights,getTextarea,replaceEditorContent,testBasicSuggestion,@@ -58,6 +60,69 @@ test('Scrolls correctly', async ({ page }) => {await assertHarperHighlightBoxes(page, [{ height: 19, width: 56, x: 97.953125, y: 63 }]);});+test.describe('textarea lint delay', () => {+ test.skip(+ ({ browserName }) => browserName === 'firefox',+ 'Firefox MV3 background context is not exposed reliably in playwright-webextext.',+ );++ test('Remaps textarea highlights during lint delay when typing before a lint', async ({+ page,+ context,+ }) => {+ const background = await getBackground(context);+ await background.evaluate(async () => {+ await chrome.storage.local.set({ delay: 10000 });+ });++ await page.goto(TEST_PAGE_URL);++ const editor = getTextarea(page);+ await replaceEditorContent(editor, 'This is an test');++ const highlight = getHarperHighlights(page).first();+ await highlight.waitFor({ state: 'visible' });+ const before = await highlight.boundingBox();+ expect(before).not.toBeNull();++ await editor.evaluate((el: HTMLTextAreaElement) => {+ el.setSelectionRange('This is '.length, 'This is '.length);+ el.focus();+ });+ await editor.pressSequentially('really ');++ await expect+ .poll(async () => (await highlight.boundingBox())?.x ?? null, { timeout: 2000 })+ .toBeGreaterThan((before?.x ?? 0) + 35);+ });++ test('Hides stale textarea highlights during lint delay when editing inside a lint', async ({+ page,+ context,+ }) => {+ const background = await getBackground(context);+ await background.evaluate(async () => {+ await chrome.storage.local.set({ delay: 10000 });+ });++ await page.goto(TEST_PAGE_URL);++ const editor = getTextarea(page);+ await replaceEditorContent(editor, 'This is an test');++ const highlights = getHarperHighlights(page);+ await highlights.first().waitFor({ state: 'visible' });++ await editor.evaluate((el: HTMLTextAreaElement) => {+ el.setSelectionRange('This is a'.length, 'This is a'.length);+ el.focus();+ });+ await editor.pressSequentially('x');++ await expect.poll(async () => await highlights.count(), { timeout: 2000 }).toBe(0);+ });+});+test('Can dismiss with escape key', async ({ page }) => {test.slow();await page.goto(TEST_PAGE_URL);diff --git a/packages/lint-framework/src/lint/LintFramework.ts b/packages/lint-framework/src/lint/LintFramework.tsindex d35b4b0ba..a66caf5c9 100644--- a/packages/lint-framework/src/lint/LintFramework.ts+++ b/packages/lint-framework/src/lint/LintFramework.ts@@ -5,6 +5,7 @@ import { isHeading, isVisible } from './domUtils';import { getCaretPosition, getCMRoot } from './editorUtils';import Highlights from './Highlights';import PopupHandler from './PopupHandler';+import { remapLintToCurrentSource } from './spanMapping';import type { UnpackedLint, UnpackedLintGroups } from './unpackLint';type ActivationKey = 'off' | 'shift' | 'control';@@ -133,30 +134,7 @@ export default class LintFramework {return { target: null as HTMLElement | null, lints: {} };}- let text = null;-- // Check if it is a CodeMirror instance, which needs to be handled in a specific way.- const isCM = target instanceof HTMLElement && getCMRoot(target) != null;-- if (isCM) {- const lineElements = target.querySelectorAll<HTMLElement>('.cm-line');- const lines = Array.from(lineElements).map((el) => el.textContent);- text = lines.reduce((acc: string, x: string) => `${acc + x}\n`, '');- } else {- text =- target instanceof HTMLTextAreaElement || target instanceof HTMLInputElement- ? target.value- : (target as HTMLElement).innerText;- }-- const newLineIndices = [];- let i = 0;- for (const c of text ?? '') {- if (c == '\n') {- newLineIndices.push(i);- }- i++;- }+ const { text, isCM, newLineIndices } = this.getTargetText(target);if (!text || text.length > 120000) {return { target: null as HTMLElement | null, lints: {} };@@ -298,6 +276,39 @@ export default class LintFramework {}}+ private getTargetText(target: Node): {+ text: string | null;+ isCM: boolean;+ newLineIndices: number[];+ } {+ let text: string | null = null;++ // Check if it is a CodeMirror instance, which needs to be handled in a specific way.+ const isCM = target instanceof HTMLElement && getCMRoot(target) != null;++ if (isCM) {+ const lineElements = (target as HTMLElement).querySelectorAll<HTMLElement>('.cm-line');+ const lines = Array.from(lineElements).map((el) => el.textContent);+ text = lines.reduce((acc: string, x: string | null) => `${acc}${x ?? ''}\n`, '');+ } else {+ text =+ target instanceof HTMLTextAreaElement || target instanceof HTMLInputElement+ ? target.value+ : (target as HTMLElement).innerText;+ }++ const newLineIndices: number[] = [];+ let i = 0;+ for (const c of text ?? '') {+ if (c == '\n') {+ newLineIndices.push(i);+ }+ i++;+ }++ return { text, isCM, newLineIndices };+ }+private requestRender() {if (this.renderRequested) {return;@@ -306,17 +317,33 @@ export default class LintFramework {this.renderRequested = true;requestAnimationFrame(() => {- const boxes = this.lastLints.flatMap(({ target, lints }) =>- target- ? Object.entries(lints).flatMap(([ruleName, ls]) =>- ls.flatMap((l) =>- computeLintBoxes(target, l as any, ruleName, {- ignoreLint: this.actions.ignoreLint,- }),- ),- )- : [],- );+ const boxes = this.lastLints.flatMap(({ target, lints }) => {+ if (!target) {+ return [];+ }++ const { text, isCM } = this.getTargetText(target);+ if (text == null) {+ return [];+ }++ return Object.entries(lints).flatMap(([ruleName, ls]) =>+ ls.flatMap((lint) => {+ const currentLint = isCM+ ? lint.source === text+ ? lint+ : null+ : remapLintToCurrentSource(lint, text);+ if (currentLint == null) {+ return [];+ }++ return computeLintBoxes(target, currentLint, ruleName, {+ ignoreLint: this.actions.ignoreLint,+ });+ }),+ );+ });this.lastLintBoxes = boxes;this.highlights.renderLintBoxes(boxes);this.popupHandler.updateLintBoxes(boxes);diff --git a/packages/lint-framework/src/lint/spanMapping.ts b/packages/lint-framework/src/lint/spanMapping.tsnew file mode 100644index 000000000..a3244e830--- /dev/null+++ b/packages/lint-framework/src/lint/spanMapping.ts@@ -0,0 +1,108 @@+import type { UnpackedLint, UnpackedSpan } from './unpackLint';++export type SingleTextEdit = {+ oldStart: number;+ oldEnd: number;+ newStart: number;+ newEnd: number;+ delta: number;+};++/**+ * Compute the smallest single changed range between two text snapshots.+ *+ * This is intentionally simple: during typing/debounce we only need to handle the+ * common single-edit case. Complex edits collapse into one wider edit, which makes+ * overlapping lints fail closed and disappear until the next lint pass.+ */+export function computeSingleTextEdit(previous: string, current: string): SingleTextEdit | null {+ if (previous === current) {+ return null;+ }++ let prefixLength = 0;+ const shortestLength = Math.min(previous.length, current.length);+ while (prefixLength < shortestLength && previous[prefixLength] === current[prefixLength]) {+ prefixLength++;+ }++ let suffixLength = 0;+ while (+ suffixLength < previous.length - prefixLength &&+ suffixLength < current.length - prefixLength &&+ previous[previous.length - 1 - suffixLength] === current[current.length - 1 - suffixLength]+ ) {+ suffixLength++;+ }++ const oldStart = prefixLength;+ const oldEnd = previous.length - suffixLength;+ const newStart = prefixLength;+ const newEnd = current.length - suffixLength;++ return {+ oldStart,+ oldEnd,+ newStart,+ newEnd,+ delta: newEnd - newStart - (oldEnd - oldStart),+ };+}++/**+ * Remap a lint span across a single text edit.+ *+ * Spans before the edit are unchanged. Spans after the edit are shifted by the+ * edit delta. Spans touched by the edit are rejected because their lint contents,+ * suggestions, and context may no longer be valid.+ */+export function remapSpanForTextEdit(+ span: UnpackedSpan,+ edit: SingleTextEdit | null,+): UnpackedSpan | null {+ if (edit == null) {+ return { ...span };+ }++ if (span.end <= edit.oldStart) {+ return { ...span };+ }++ if (span.start >= edit.oldEnd) {+ return {+ start: span.start + edit.delta,+ end: span.end + edit.delta,+ };+ }++ return null;+}++/**+ * Return a lint whose span is valid for `currentSource`, or `null` if it should+ * be hidden until the next lint pass.+ */+export function remapLintToCurrentSource(+ lint: UnpackedLint,+ currentSource: string,+): UnpackedLint | null {+ if (lint.source === currentSource) {+ return lint;+ }++ const span = remapSpanForTextEdit(lint.span, computeSingleTextEdit(lint.source, currentSource));++ if (span == null) {+ return null;+ }++ if (currentSource.slice(span.start, span.end) !== lint.problem_text) {+ return null;+ }++ return {+ ...lint,+ span,+ source: currentSource,+ };+}