Offline, privacy-first grammar checker. Fast, open-source, Rust-powered
fix(chrome-ext): Lexical tests now wait for linting to complete (#4624)
Elijah Potter1873f751cd5b
diff --git a/Dockerfile b/Dockerfileindex c863520c5..1d4f31523 100644--- a/Dockerfile+++ b/Dockerfile@@ -10,7 +10,7 @@ RUN apt-get update -y && apt-get install clang -yRUN mkdir -p /usr/build/WORKDIR /usr/build/-RUN cargo install wasm-pack+RUN cargo install wasm-pack --lockedCOPY . .diff --git a/packages/chrome-plugin/tests/editor_content.spec.ts b/packages/chrome-plugin/tests/editor_content.spec.tsindex a41e0736a..b0c07b7f8 100644--- a/packages/chrome-plugin/tests/editor_content.spec.ts+++ b/packages/chrome-plugin/tests/editor_content.spec.ts@@ -1,23 +1,53 @@import { expect, test } from '@playwright/test';import { replaceEditorContent } from './testUtils';-for (const tag of ['input', 'textarea']) {- test(`Ensure \`replaceEditorContent\` fills \`${tag}\` without allowing intermediate text to be linted.`, async ({- page,- }) => {- await page.setContent(`<${tag}></${tag}><output></output>`);+for (const kind of ['input', 'textarea', 'div', 'Draft.js']) {+ const tag = kind === 'Draft.js' ? 'div' : kind;+ const rich = tag === 'div';+ const attributes = rich+ ? ` contenteditable="true"${kind === 'Draft.js' ? ' class="public-DraftEditor-content"' : ''}`+ : '';+ const method =+ kind === 'Draft.js'+ ? 'uses character input for Draft.js'+ : rich+ ? 'uses keyboard selection and bulk input for div'+ : `fills ${tag}`;++ test(`replaceEditorContent ${method}`, async ({ page }) => {+ await page.setContent(`<${tag}${attributes}></${tag}><output></output>`);+ await page.locator(tag).fill('Old text');await page.evaluate(() => {const values: string[] = [];document.addEventListener('input', (event) => {- values.push((event.target as HTMLInputElement).value);+ const target = event.target as HTMLElement;+ values.push('value' in target ? String(target.value) : (target.textContent ?? ''));document.querySelector('output')!.textContent = JSON.stringify(values);});});const text = 'This is a mistaek.';await replaceEditorContent(page.locator(tag), text);- await expect(page.locator(tag)).toHaveValue(text);- // The prefix "This is a m" has a different lint from the completed sentence.- await expect(page.locator('output')).toHaveText(JSON.stringify([text]));+ if (rich) {+ await expect(page.locator(tag)).toHaveText(text);+ } else {+ await expect(page.locator(tag)).toHaveValue(text);+ }+ // Native setup must not expose partial words. Draft.js is the legacy exception+ // because its selection model needs individual character key events.+ const values =+ kind === 'Draft.js'+ ? ['', ...Array.from(text, (_, index) => text.slice(0, index + 1))]+ : rich+ ? ['', text]+ : [text];+ await expect(page.locator('output')).toHaveText(JSON.stringify(values));});}++test('replaceEditorContent preserves textarea line breaks', async ({ page }) => {+ await page.setContent('<textarea></textarea>');+ const editor = page.locator('textarea');+ await replaceEditorContent(editor, 'Valid words\ntset here.', true);+ await expect(editor).toHaveValue('Valid words\ntset here.');+});diff --git a/packages/chrome-plugin/tests/fixtures.ts b/packages/chrome-plugin/tests/fixtures.tsindex d8c72f0dd..19fe889dc 100644--- a/packages/chrome-plugin/tests/fixtures.ts+++ b/packages/chrome-plugin/tests/fixtures.ts@@ -4,34 +4,64 @@ import { test as base, expect } from '@playwright/test';import { withExtension } from 'playwright-webextext';const pathToExtension = path.join(import.meta.dirname, '../build');+const welcomeUrl = 'https://writewithharper.com/install-browser-extension';const test = base.extend({- context: async (- { playwright, browserName, contextOptions, launchOptions, headless },- use,- testInfo,- ) => {- if (browserName === 'chromium' && headless) {- throw new Error('Chromium extensions require headed mode');- }-- const profile = testInfo.outputPath('browser-profile');- await mkdir(profile, { recursive: true });-- const browserType = withExtension(playwright[browserName], pathToExtension);- const context = await browserType.launchPersistentContext(profile, {- ...contextOptions,- ...launchOptions,- headless,- });-- try {- await use(context);- } finally {- await context.close();- await rm(profile, { recursive: true, force: true });- }- },+ context: [+ async ({ playwright, browserName, contextOptions, launchOptions, headless }, use, testInfo) => {+ if (browserName === 'chromium' && headless) {+ throw new Error('Chromium extensions require headed mode');+ }++ const profile = testInfo.outputPath('browser-profile');+ await mkdir(profile, { recursive: true });++ const browserType = withExtension(playwright[browserName], pathToExtension);+ const context = await browserType.launchPersistentContext(profile, {+ ...contextOptions,+ ...launchOptions,+ headless,+ });++ try {+ // The install tab can steal focus and pause Firefox's animation frames.+ // Stub its network load, then close it before creating the test page.+ await context.route(`${welcomeUrl}**`, (route) =>+ route.fulfill({ contentType: 'text/html', body: '<title>Installed</title>' }),+ );+ await expect+ .poll(() => context.pages().some((page) => page.url().startsWith(welcomeUrl)), {+ timeout: 90000,+ message: 'The extension install hook should open its welcome tab',+ })+ .toBe(true);+ for (const page of context.pages()) {+ if (page.url().startsWith(welcomeUrl)) await page.close();+ }++ // A completed lint proves that the background linter and content script+ // are ready. Keep cold startup out of each test's UI assertion budget.+ // A normal page works in Firefox too, which does not expose background pages.+ const startupPage = await context.newPage();+ try {+ await startupPage.goto('http://localhost:8081/simple_textarea.html');+ await startupPage.bringToFront();+ await startupPage.locator('textarea').fill('This is an test');+ await expect(startupPage.locator('#harper-highlight').first()).toBeVisible({+ timeout: 90000,+ });+ } finally {+ await startupPage.close();+ }++ await use(context);+ } finally {+ await context.close();+ await rm(profile, { recursive: true, force: true });+ }+ },+ { scope: 'test', timeout: 120000 },+ ],});export { test, expect };diff --git a/packages/chrome-plugin/tests/popup_reconnect.spec.ts b/packages/chrome-plugin/tests/popup_reconnect.spec.tsindex 0b166d3a0..51543fe16 100644--- a/packages/chrome-plugin/tests/popup_reconnect.spec.ts+++ b/packages/chrome-plugin/tests/popup_reconnect.spec.ts@@ -3,12 +3,13 @@ import {getTextarea,openHarperPopupFromEditorPointerDown,replaceEditorContent,- waitForHarperHighlightCenter,+ waitForHighlightsToSettle,} from './testUtils';const TEST_PAGE_URL = 'http://localhost:8081/popup_reconnect.html';test('Reconnects the popup host before opening the popover', async ({ page }) => {+ test.slow();const pageErrors: string[] = [];const consoleErrors: string[] = [];@@ -26,7 +27,9 @@ test('Reconnects the popup host before opening the popover', async ({ page }) =>const editor = getTextarea(page);await replaceEditorContent(editor, 'This is an test');- expect(await waitForHarperHighlightCenter(page, 12000)).not.toBeNull();+ // Finish linting before disconnecting the popup host. Do not wait for a render+ // after replacing the body: the pointer handler must reconnect the host itself.+ await waitForHighlightsToSettle(page);await page.evaluate(() => {(@@ -38,6 +41,7 @@ test('Reconnects the popup host before opening the popover', async ({ page }) =>const opened = await openHarperPopupFromEditorPointerDown(page, editor);expect(opened).toBe(true);+ await expect(page.getByTitle('Click to replace "an" with "a"')).toBeVisible();const errors = [...pageErrors, ...consoleErrors].join('\n');expect(errors).not.toContain("Failed to execute 'showPopover'");diff --git a/packages/chrome-plugin/tests/testUtils.ts b/packages/chrome-plugin/tests/testUtils.tsindex a98f8619b..744e00827 100644--- a/packages/chrome-plugin/tests/testUtils.ts+++ b/packages/chrome-plugin/tests/testUtils.ts@@ -72,7 +72,7 @@ export function getDraftEditor(page: Page): Locator {/** Replace the content of a text editor. */export async function replaceEditorContent(editorEl: Locator, text: string, softBreaks = false) {// Seed form controls in one update so popup tests cannot click lints for partial words.- // Rich editors still need their keyboard-driven editing behavior.+ // Rich editors still need keyboard selection, deletion, and line breaks.if (await isFormElement(editorEl)) {await editorEl.fill(text);return;@@ -85,9 +85,18 @@ export async function replaceEditorContent(editorEl: Locator, text: string, softconst lines = text.split('\n');const breakKey = softBreaks ? 'Shift+Enter' : 'Enter';+ const needsCharacterInput = await editorEl.evaluate((el) =>+ el.classList.contains('public-DraftEditor-content'),+ );for (let i = 0; i < lines.length; i++) {- await editorEl.pressSequentially(lines[i]);+ if (needsCharacterInput) {+ // Draft.js needs character key events at a normal typing cadence for its selection model.+ await editorEl.pressSequentially(lines[i], { delay: 200 });+ } else {+ // Native text input updates the editor model without exposing partial words to linting.+ await editorEl.page().keyboard.insertText(lines[i]);+ }if (i < lines.length - 1) {await editorEl.press(breakKey);}@@ -104,6 +113,44 @@ export function getHarperHighlights(page: Page): Locator {return page.locator('#harper-highlight');}+export async function waitForHighlightsToSettle(+ page: Page,+ quietMs = 250,+ timeoutMs = 30000,+): Promise<void> {+ let previous: string | undefined;+ let changedAt = performance.now();++ await expect+ .poll(+ async () => {+ const snapshot = await getHarperHighlights(page).evaluateAll((highlights) =>+ JSON.stringify(+ highlights.flatMap((highlight) => {+ const { x, y, width, height } = highlight.getBoundingClientRect();+ const style = getComputedStyle(highlight);+ if (width <= 0 || height <= 0 || style.visibility !== 'visible') return [];+ return [[x, y, width, height, style.borderBottomColor, style.backgroundColor]];+ }),+ ),+ );+ const now = performance.now();+ if (snapshot === '[]' || snapshot !== previous) {+ previous = snapshot;+ changedAt = now;+ return false;+ }+ return now - changedAt >= quietMs;+ },+ {+ message: `Visible highlight boxes should stay unchanged for ${quietMs} ms`,+ intervals: [10],+ timeout: timeoutMs,+ },+ )+ .toBe(true);+}+/*** Wait for the first Harper highlight to exist and return its screen-space center.*@@ -148,14 +195,14 @@ export async function assertLocatorsResolveEqually(page: Page, a: Locator, b: Loexpect(areSame).toBe(true);}-/** Locates the first Harper highlight on the page and clicks it.- * It should result in the popup opening.- * Returns whether the highlight was found. */+/** Click the first Harper highlight and check that its popup opens.+ * Returns false if no highlight was found; a missing popup fails the test. */export async function clickHarperHighlight(page: Page): Promise<boolean> {const center = await waitForHarperHighlightCenter(page);if (center == null) return false;await page.mouse.click(center.x, center.y);+ await expect(page.locator('.harper-container')).toBeVisible();return true;}@@ -177,24 +224,20 @@ export async function openHarperPopupFromEditorPointerDown(return false;}- try {- await editor.dispatchEvent('pointerdown', {- bubbles: true,- composed: true,- button: 0,- buttons: 1,- clientX: center.x,- clientY: center.y,- pointerId: 1,- pointerType: 'mouse',- screenX: center.x,- screenY: center.y,- });- await page.locator('.harper-container').waitFor({ state: 'visible', timeout: 2000 });- return true;- } catch {- return false;- }+ await editor.dispatchEvent('pointerdown', {+ bubbles: true,+ composed: true,+ button: 0,+ buttons: 1,+ clientX: center.x,+ clientY: center.y,+ pointerId: 1,+ pointerType: 'mouse',+ screenX: center.x,+ screenY: center.y,+ });+ await expect(page.locator('.harper-container')).toBeVisible();+ return true;}/** Grab the first `<textarea />` on a page. */@@ -254,10 +297,14 @@ export async function testBasicSuggestion(await setup(page, editor);}await replaceEditorContent(editor, 'This is an test');+ await assertEditorText(editor, 'This is an test');+ await waitForHighlightsToSettle(page);const opened = await clickHarperHighlight(page);expect(opened).toBe(true);- await page.getByTitle('Click to replace "an" with "a"').click();+ const suggestion = page.getByTitle('Click to replace "an" with "a"');+ await expect(suggestion).toBeVisible();+ await suggestion.click();await assertEditorText(editor, 'This is a test');await expect(editor).toBeFocused();@@ -298,7 +345,7 @@ export async function testCanIgnoreSuggestion(const testText = 'This is a mistaek.';await replaceEditorContent(editor, testText);- // test.slow() does not extend assertion timeouts during linter startup.+ await waitForHighlightsToSettle(page);await expect(getHarperHighlights(page)).toHaveCount(1, { timeout: 30000 });// Open the popup for the highlight and click Ignore.@@ -338,6 +385,7 @@ export async function testCanBlockRuleSuggestion(await setup(page, editor);}await replaceEditorContent(editor, 'I could of gone.');+ await waitForHighlightsToSettle(page);const opened = await clickHarperHighlight(page);expect(opened).toBe(true);@@ -386,12 +434,14 @@ export async function testMultipleSuggestionsAndUndo(// Soft breaks: no false positives from concatenation + correct span alignment.await replaceEditorContent(editor, 'Valid words\ntset here.', true);await expect(getHarperHighlights(page)).toHaveCount(1, { timeout: 30000 });+ await waitForHighlightsToSettle(page);expect(await clickHarperHighlight(page)).toBe(true);await page.getByTitle('Click to replace "tset" with "test"').click();await assertEditorContains(editor, 'test here');await replaceEditorContent(editor, 'The first tset.\nThe second tset.\nThe third tset.');await expect(getHarperHighlights(page)).toHaveCount(3, { timeout: 30000 });+ await waitForHighlightsToSettle(page);// Get highlights sorted by visual position and click on the middle oneconst sortedBoxes = await getSortedHighlightBoxes(page);