Offline, privacy-first grammar checker. Fast, open-source, Rust-powered
fix(chrome-ext): Draft.js multiline suggestion replacement corruption (#2597)
David Raphi41a9a4e44a28
diff --git a/packages/chrome-plugin/tests/draft.spec.ts b/packages/chrome-plugin/tests/draft.spec.tsindex 178268668..546abe791 100644--- a/packages/chrome-plugin/tests/draft.spec.ts+++ b/packages/chrome-plugin/tests/draft.spec.ts@@ -5,6 +5,7 @@ import {getHarperHighlights,randomString,replaceEditorContent,+ testMultipleSuggestionsAndUndo,} from './testUtils';const TEST_PAGE_URL = 'https://draftjs.org/';@@ -24,7 +25,7 @@ test('Can apply basic suggestion.', async ({ page }) => {await page.waitForTimeout(3000);- expect(draft).toContainText('This is a test');+ await expect(draft).toContainText('This is a test');// Verify editor state is preserved: arrow keys and backspace must work.// Position cursor before 's' in 'test', then backspace to delete 'e'.@@ -32,11 +33,16 @@ test('Can apply basic suggestion.', async ({ page }) => {await draft.press('ArrowLeft');await draft.press('ArrowLeft');await draft.press('Backspace');- expect(draft).toContainText('This is a tst');+ await expect(draft).toContainText('This is a tst');// Verify typing still works.await draft.pressSequentially('e');- expect(draft).toContainText('This is a test');+ await expect(draft).toContainText('This is a test');+});++testMultipleSuggestionsAndUndo(TEST_PAGE_URL, getDraftEditor, async (editor) => {+ await editor.scrollIntoViewIfNeeded();+ await editor.click();});test('Can ignore suggestion.', async ({ page }) => {@@ -58,6 +64,6 @@ test('Can ignore suggestion.', async ({ page }) => {await expect(getHarperHighlights(page)).toHaveCount(0);// Nothing should change.- expect(draft).toContainText(cacheSalt);+ await expect(draft).toContainText(cacheSalt);expect(await clickHarperHighlight(page)).toBe(false);});diff --git a/packages/chrome-plugin/tests/lexical.spec.ts b/packages/chrome-plugin/tests/lexical.spec.tsindex f087c5a6a..d7df2c0ea 100644--- a/packages/chrome-plugin/tests/lexical.spec.ts+++ b/packages/chrome-plugin/tests/lexical.spec.ts@@ -5,6 +5,7 @@ import {getLexicalEditor,randomString,replaceEditorContent,+ testMultipleSuggestionsAndUndo,} from './testUtils';const TEST_PAGE_URL = 'https://playground.lexical.dev/';@@ -36,6 +37,8 @@ test('Can apply basic suggestion.', async ({ page }) => {await expect(lexical).toContainText('This is a test');});+testMultipleSuggestionsAndUndo(TEST_PAGE_URL, getLexicalEditor);+test('Can ignore suggestion.', async ({ page }) => {await page.goto(TEST_PAGE_URL);const lexical = getLexicalEditor(page);@@ -52,6 +55,6 @@ test('Can ignore suggestion.', async ({ page }) => {await expect(getHarperHighlights(page)).toHaveCount(0);// Nothing should change.- expect(lexical).toContainText(cacheSalt);+ await expect(lexical).toContainText(cacheSalt);expect(await clickHarperHighlight(page)).toBe(false);});diff --git a/packages/chrome-plugin/tests/prosemirror.spec.ts b/packages/chrome-plugin/tests/prosemirror.spec.tsindex 3769ebc39..2f2338ab7 100644--- a/packages/chrome-plugin/tests/prosemirror.spec.ts+++ b/packages/chrome-plugin/tests/prosemirror.spec.ts@@ -5,6 +5,7 @@ import {getProseMirrorEditor,randomString,replaceEditorContent,+ testMultipleSuggestionsAndUndo,} from './testUtils';const TEST_PAGE_URL = 'https://prosemirror.net/';@@ -29,6 +30,8 @@ test('Can apply basic suggestion.', async ({ page }) => {await expect(pm).toContainText('This is a test of Harper’s grammar checking.');});+testMultipleSuggestionsAndUndo(TEST_PAGE_URL, getProseMirrorEditor);+test('Can ignore suggestion.', async ({ page }) => {await page.goto(TEST_PAGE_URL);const pm = getProseMirrorEditor(page);@@ -45,6 +48,6 @@ test('Can ignore suggestion.', async ({ page }) => {await expect(getHarperHighlights(page)).toHaveCount(0);// Nothing should change.- expect(pm).toContainText(cacheSalt);+ await expect(pm).toContainText(cacheSalt);expect(await clickHarperHighlight(page)).toBe(false);});diff --git a/packages/chrome-plugin/tests/slate.spec.ts b/packages/chrome-plugin/tests/slate.spec.tsindex b06377e4a..283dc1b60 100644--- a/packages/chrome-plugin/tests/slate.spec.ts+++ b/packages/chrome-plugin/tests/slate.spec.ts@@ -5,6 +5,7 @@ import {getSlateEditor,randomString,replaceEditorContent,+ testMultipleSuggestionsAndUndo,} from './testUtils';const TEST_PAGE_URL = 'https://slatejs.org';@@ -22,7 +23,7 @@ test('Can apply basic suggestion.', async ({ page }) => {await page.waitForTimeout(3000);- expect(slate).toContainText('This is a test');+ await expect(slate).toContainText('This is a test');// Verify editor state is preserved: arrow keys and backspace must work.// Position cursor before 's' in 'test', then backspace to delete 'e'.@@ -30,13 +31,15 @@ test('Can apply basic suggestion.', async ({ page }) => {await slate.press('ArrowLeft');await slate.press('ArrowLeft');await slate.press('Backspace');- expect(slate).toContainText('This is a tst');+ await expect(slate).toContainText('This is a tst');// Verify typing still works.await slate.pressSequentially('e');- expect(slate).toContainText('This is a test');+ await expect(slate).toContainText('This is a test');});+testMultipleSuggestionsAndUndo(TEST_PAGE_URL, getSlateEditor);+test('Can ignore suggestion.', async ({ page }) => {await page.goto(TEST_PAGE_URL);const slate = getSlateEditor(page);@@ -53,6 +56,6 @@ test('Can ignore suggestion.', async ({ page }) => {await expect(getHarperHighlights(page)).toHaveCount(0);// Nothing should change.- expect(slate).toContainText(cacheSalt);+ await expect(slate).toContainText(cacheSalt);expect(await clickHarperHighlight(page)).toBe(false);});diff --git a/packages/chrome-plugin/tests/testUtils.ts b/packages/chrome-plugin/tests/testUtils.tsindex 7a240a1f6..2b1afb1a8 100644--- a/packages/chrome-plugin/tests/testUtils.ts+++ b/packages/chrome-plugin/tests/testUtils.ts@@ -31,11 +31,18 @@ export function getDraftEditor(page: Page): Locator {return page.locator('#rich-example .public-DraftEditor-content');}-/** Replace the content of a text editor. */+/** Replace the content of a text editor. Handles newlines by pressing Enter. */export async function replaceEditorContent(editorEl: Locator, text: string) {await editorEl.selectText();await editorEl.press('Backspace');- await editorEl.pressSequentially(text);++ const lines = text.split('\n');+ for (let i = 0; i < lines.length; i++) {+ await editorEl.pressSequentially(lines[i]);+ if (i < lines.length - 1) {+ await editorEl.press('Enter');+ }+ }}/** Locate the Harper highlights on a page. */@@ -89,6 +96,9 @@ export function getTextarea(page: Page): Locator {/** A string or function that resolves to a test page. */export type TestPageUrlProvider = string | ((page: Page) => Promise<string>);+/** A function that returns an editor locator. */+export type EditorLocatorProvider = (page: Page) => Locator;+async function resolveTestPage(prov: TestPageUrlProvider, page: Page): Promise<string> {if (typeof prov === 'string') {return prov;@@ -171,17 +181,81 @@ export async function testCanBlockRuleTextareaSuggestion(testPageUrl: TestPageUr});}+/** Get highlight bounding boxes sorted by visual position (top to bottom, left to right). */+async function getSortedHighlightBoxes(page: Page) {+ const highlights = getHarperHighlights(page);+ const count = await highlights.count();+ const boxes: NonNullable<Awaited<ReturnType<Locator['boundingBox']>>>[] = [];++ for (let i = 0; i < count; i++) {+ const box = await highlights.nth(i).boundingBox();+ if (box) {+ boxes.push(box);+ }+ }++ boxes.sort((a, b) => (Math.abs(a.y - b.y) > 5 ? a.y - b.y : a.x - b.x));++ return boxes;+}++/** Test multiline suggestion replacement and undo. */+export async function testMultipleSuggestionsAndUndo(+ testPageUrl: TestPageUrlProvider,+ getEditor: EditorLocatorProvider,+ setup?: (editor: Locator) => Promise<void>,+) {+ test('Multiple suggestions and undo.', async ({ page }) => {+ const url = await resolveTestPage(testPageUrl, page);+ await page.goto(url);++ const editor = getEditor(page);+ if (setup) {+ await setup(editor);+ }+ await replaceEditorContent(editor, 'The first tset.\nThe second tset.\nThe third tset.');++ await page.waitForTimeout(3000);++ const highlights = getHarperHighlights(page);+ await expect(highlights).toHaveCount(3);++ // Get highlights sorted by visual position and click on the middle one+ const sortedBoxes = await getSortedHighlightBoxes(page);+ expect(sortedBoxes.length).toBe(3);+ const box = sortedBoxes[1];+ await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2);++ // Move cursor away to test whether it handles race condition+ await editor.press('End');++ await page.getByTitle('Replace with "test"').click();+ await page.waitForTimeout(500);++ // Verify only second "tset" was corrected+ await expect(editor).toContainText('first tset');+ await expect(editor).toContainText('second test');+ await expect(editor).toContainText('third tset');++ // Undo+ await editor.press('Control+z');+ await page.waitForTimeout(300);+ await expect(editor).toContainText('The second tset');+ });+}+export async function assertHarperHighlightBoxes(page: Page, boxes: Box[]): Promise<void> {const highlights = getHarperHighlights(page);expect(await highlights.count()).toBe(boxes.length);for (let i = 0; i < (await highlights.count()); i++) {const box = await highlights.nth(i).boundingBox();+ expect(box).not.toBeNull();console.log(`Expected: ${JSON.stringify(boxes[i])}`);console.log(`Got: ${JSON.stringify(box)}`);- assertBoxesClose(box, boxes[i]);+ assertBoxesClose(box!, boxes[i]);}}diff --git a/packages/lint-framework/src/lint/computeLintBoxes.ts b/packages/lint-framework/src/lint/computeLintBoxes.tsindex c159b164e..0b2c50295 100644--- a/packages/lint-framework/src/lint/computeLintBoxes.ts+++ b/packages/lint-framework/src/lint/computeLintBoxes.ts@@ -93,8 +93,10 @@ function replaceValue(replaceFormElementValue(el as HTMLTextAreaElement | HTMLInputElement, value);} else if (getLexicalRoot(el) != null && span && replacementText !== undefined) {replaceLexicalValue(el, span, replacementText);+ } else if (getDraftRoot(el) != null && span && replacementText !== undefined) {+ replaceDraftValue(el, span, replacementText);} else if (- (getSlateRoot(el) != null || getCkEditorRoot(el) != null || getDraftRoot(el) != null) &&+ (getSlateRoot(el) != null || getCkEditorRoot(el) != null) &&span &&replacementText !== undefined) {@@ -129,6 +131,33 @@ function replaceLexicalValue(el.dispatchEvent(new InputEvent('input', { bubbles: true, cancelable: false }));}+function replaceDraftValue(+ el: HTMLElement,+ span: { start: number; end: number },+ replacementText: string,+) {+ const setup = selectSpanInEditor(el, span);+ if (!setup) return;++ const { doc, sel, range } = setup;++ setTimeout(() => {+ const beforeEvt = new InputEvent('beforeinput', {+ bubbles: true,+ cancelable: true,+ inputType: 'insertText',+ data: replacementText,+ });+ el.dispatchEvent(beforeEvt);++ if (!beforeEvt.defaultPrevented) {+ replaceTextInRange(doc, sel, range, replacementText);+ }++ el.dispatchEvent(new InputEvent('input', { bubbles: true, inputType: 'insertText' }));+ }, 0);+}+function selectSpanInEditor(el: HTMLElement, span: { start: number; end: number }) {const doc = el.ownerDocument;const sel = doc.defaultView?.getSelection();diff --git a/packages/vscode-plugin/src/tests/suite/helper.ts b/packages/vscode-plugin/src/tests/suite/helper.tsindex 00ece08ab..92edb2c1e 100644--- a/packages/vscode-plugin/src/tests/suite/helper.ts+++ b/packages/vscode-plugin/src/tests/suite/helper.ts@@ -91,8 +91,8 @@ export function waitForDiagnosticsChange(const before = func ? getActualDiagnostics(uri) : [];(func || (async () => {}))().then(() => {- const delay = 10;- const limit = 10;+ const delay = 50;+ const limit = 20;let counter = 0;const tryCompare = () => {