Skip to content

Offline, privacy-first grammar checker. Fast, open-source, Rust-powered

fix(lint-framework): reconnect popup host after DOM replacement (#2998)

Kacper Kuczkowski09d0e1dd8217
diff --git a/packages/chrome-plugin/tests/pages/popup_reconnect.html b/packages/chrome-plugin/tests/pages/popup_reconnect.html
new file mode 100644
index 000000000..e67b65a2e
--- /dev/null
+++ b/packages/chrome-plugin/tests/pages/popup_reconnect.html
@@ -0,0 +1,18 @@
+<!DOCTYPE html>
+<html>
+ <body>
+ <div id="app">
+ <textarea rows="5" cols="33"></textarea>
+ </div>
+ <script>
+ window.rehomeBodyPreservingApp = () => {
+ const app = document.getElementById('app');
+ if (!app) return;
+
+ const newBody = document.createElement('body');
+ newBody.appendChild(app);
+ document.documentElement.replaceChild(newBody, document.body);
+ };
+ </script>
+ </body>
+</html>
diff --git a/packages/chrome-plugin/tests/popup_reconnect.spec.ts b/packages/chrome-plugin/tests/popup_reconnect.spec.ts
new file mode 100644
index 000000000..0b166d3a0
--- /dev/null
+++ b/packages/chrome-plugin/tests/popup_reconnect.spec.ts
@@ -0,0 +1,45 @@
+import { expect, test } from './fixtures';
+import {
+ getTextarea,
+ openHarperPopupFromEditorPointerDown,
+ replaceEditorContent,
+ waitForHarperHighlightCenter,
+} from './testUtils';
+
+const TEST_PAGE_URL = 'http://localhost:8081/popup_reconnect.html';
+
+test('Reconnects the popup host before opening the popover', async ({ page }) => {
+ const pageErrors: string[] = [];
+ const consoleErrors: string[] = [];
+
+ page.on('pageerror', (error) => {
+ pageErrors.push(error.message);
+ });
+ page.on('console', (message) => {
+ if (message.type() === 'error') {
+ consoleErrors.push(message.text());
+ }
+ });
+
+ await page.goto(TEST_PAGE_URL);
+
+ const editor = getTextarea(page);
+ await replaceEditorContent(editor, 'This is an test');
+
+ expect(await waitForHarperHighlightCenter(page, 12000)).not.toBeNull();
+
+ await page.evaluate(() => {
+ (
+ window as typeof window & {
+ rehomeBodyPreservingApp?: () => void;
+ }
+ ).rehomeBodyPreservingApp?.();
+ });
+
+ const opened = await openHarperPopupFromEditorPointerDown(page, editor);
+ expect(opened).toBe(true);
+
+ const errors = [...pageErrors, ...consoleErrors].join('\n');
+ expect(errors).not.toContain("Failed to execute 'showPopover'");
+ expect(errors).not.toContain('Invalid on disconnected popover elements');
+});
diff --git a/packages/chrome-plugin/tests/testUtils.ts b/packages/chrome-plugin/tests/testUtils.ts
index 6d79fee00..2a9397510 100644
--- a/packages/chrome-plugin/tests/testUtils.ts
+++ b/packages/chrome-plugin/tests/testUtils.ts
@@ -2,6 +2,11 @@ import type { Locator, Page } from '@playwright/test';
import type { Box } from 'lint-framework';
import { expect, test } from './fixtures';
+type ScreenPoint = {
+ x: number;
+ y: number;
+};
+
export function randomString(length: number): string {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
let result = '';
@@ -50,6 +55,36 @@ export function getHarperHighlights(page: Page): Locator {
return page.locator('#harper-highlight');
}
+/**
+ * Wait for the first Harper highlight to exist and return its screen-space center.
+ *
+ * We return screen coordinates instead of a DOM node because some editors replace parts of
+ * the DOM during updates. Coordinates are still usable even if the original highlight element
+ * gets disconnected and recreated.
+ */
+export async function waitForHarperHighlightCenter(
+ page: Page,
+ timeoutMs = 12000,
+): Promise<ScreenPoint | null> {
+ const highlight = getHarperHighlights(page).first();
+
+ try {
+ await highlight.waitFor({ state: 'visible', timeout: timeoutMs });
+ } catch {
+ return null;
+ }
+
+ const box = await highlight.boundingBox();
+ if (box == null || box.width <= 0 || box.height <= 0) {
+ return null;
+ }
+
+ return {
+ x: box.x + box.width / 2,
+ y: box.y + box.height / 2,
+ };
+}
+
export async function assertLocatorIsFocused(page: Page, loc: Locator) {
await assertLocatorsResolveEqually(page, loc, page.locator(':focus'));
}
@@ -68,24 +103,49 @@ export async function assertLocatorsResolveEqually(page: Page, a: Locator, b: Lo
* It should result in the popup opening.
* Returns whether the highlight was found. */
export async function clickHarperHighlight(page: Page): Promise<boolean> {
- const highlights = getHarperHighlights(page);
+ const center = await waitForHarperHighlightCenter(page);
+ if (center == null) return false;
+
+ await page.mouse.click(center.x, center.y);
+ return true;
+}
+
+/**
+ * Open the Harper popup by dispatching the same `pointerdown` event Harper receives from
+ * the editor itself.
+ *
+ * This is intentionally different from clicking the floating highlight. Some editors replace
+ * parts of the DOM while the popup is opening, which can briefly disconnect and recreate
+ * Harper's popup host. Tests for that behavior need to follow the same event path as a real
+ * editor interaction.
+ */
+export async function openHarperPopupFromEditorPointerDown(
+ page: Page,
+ editor: Locator,
+): Promise<boolean> {
+ const center = await waitForHarperHighlightCenter(page);
+ if (center == null) {
+ return false;
+ }
- // Wait briefly for at least one highlight to appear.
- // If none appear within a reasonable time, return false.
try {
- await highlights.first().waitFor({ state: 'visible', timeout: 12000 });
+ 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;
}
-
- const box = await highlights.first().boundingBox();
- if (box == null) return false;
-
- // Locate the center of the element and click to open the popup.
- const cx = box.x + box.width / 2;
- const cy = box.y + box.height / 2;
- await page.mouse.click(cx, cy);
- return true;
}
/** Grab the first `<textarea />` on a page. */
diff --git a/packages/lint-framework/src/lint/PopupHandler.ts b/packages/lint-framework/src/lint/PopupHandler.ts
index d7a9b24a8..e5a7960ae 100644
--- a/packages/lint-framework/src/lint/PopupHandler.ts
+++ b/packages/lint-framework/src/lint/PopupHandler.ts
@@ -55,7 +55,7 @@ export default class PopupHandler {
this.currentLintBoxes = [];
this.currentHint = undefined;
this.currentHintFor = undefined;
- this.renderBox = new RenderBox(document.body);
+ this.renderBox = new RenderBox(() => document.body);
this.renderBox.getShadowHost().popover = 'manual';
this.renderBox.getShadowHost().style.pointerEvents = 'none';
this.renderBox.getShadowHost().style.border = 'none';
@@ -113,6 +113,7 @@ export default class PopupHandler {
private render() {
let tree = h('div', {}, []);
+ const host = this.renderBox.getShadowHost();
this.updateHint();
@@ -123,13 +124,21 @@ export default class PopupHandler {
this.popupLint = undefined;
this.updateHint();
});
- this.renderBox.getShadowHost().style.setProperty('visibility', 'visible', 'important');
- this.renderBox.getShadowHost().showPopover();
- } else {
- this.renderBox.getShadowHost().hidePopover();
}
this.renderBox.render(tree);
+
+ if (this.popupLint != null && this.popupLint < this.currentLintBoxes.length) {
+ host.style.setProperty('visibility', 'visible', 'important');
+ if (host.isConnected && !host.matches(':popover-open')) {
+ host.showPopover();
+ }
+ } else {
+ host.style.setProperty('visibility', 'hidden', 'important');
+ if (host.isConnected && host.matches(':popover-open')) {
+ host.hidePopover();
+ }
+ }
}
/** Synchronize the hint with the currently focused lint.
diff --git a/packages/lint-framework/src/lint/RenderBox.ts b/packages/lint-framework/src/lint/RenderBox.ts
index 537440104..f4059c5ca 100644
--- a/packages/lint-framework/src/lint/RenderBox.ts
+++ b/packages/lint-framework/src/lint/RenderBox.ts
@@ -3,10 +3,12 @@ import createElement from 'virtual-dom/create-element';
import diff from 'virtual-dom/diff';
import patch from 'virtual-dom/patch';
+type ParentResolver = () => Node;
+
/** Wraps `virtual-dom` to create a box that is unaffected by the style of the rest of the page. */
export default class RenderBox {
/** The node we reattach into if a host is removed by editor-managed DOM updates. */
- private parent: Node;
+ private parentResolver: ParentResolver;
/** The element our virtual DOM is attached to. */
private virtualRoot: Element | undefined;
/** The current state of the virtual DOM */
@@ -14,16 +16,16 @@ export default class RenderBox {
/** The shadow DOM the `virtualRoot` is attached to. */
private shadowHost: HTMLElement;
- constructor(parent: Node) {
- this.parent = parent;
+ constructor(parent: Node | ParentResolver) {
+ this.parentResolver = typeof parent === 'function' ? parent : () => parent;
this.shadowHost = document.createElement('harper-render-box');
- parent.appendChild(this.shadowHost);
+ this.parentResolver().appendChild(this.shadowHost);
}
/** Render to the box. */
public render(node: VNode) {
if (!this.shadowHost.isConnected) {
- this.parent.appendChild(this.shadowHost);
+ this.parentResolver().appendChild(this.shadowHost);
}
if (!this.virtualRoot || !this.virtualTree) {
diff --git a/packages/lint-framework/src/lint/TextFieldRange.ts b/packages/lint-framework/src/lint/TextFieldRange.ts
index 508de050c..d9b08d0cf 100644
--- a/packages/lint-framework/src/lint/TextFieldRange.ts
+++ b/packages/lint-framework/src/lint/TextFieldRange.ts
@@ -51,7 +51,13 @@ export default class TextFieldRange {
refs: number;
} {
const existing = TextFieldRange.arenas.get(field);
- if (existing) return existing;
+ if (existing?.mirror.isConnected) return existing;
+ if (existing) {
+ try {
+ existing.mirror.remove();
+ } catch {}
+ TextFieldRange.arenas.delete(field);
+ }
const mirror = document.createElement('div');
mirror.className = 'harper-textfield-mirror';