Skip to content

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

fix(lint-framework): position highlights correctly under zoomed or scaled ancestors (#4506)

Branislav Klocok8670fc3c86db
diff --git a/packages/chrome-plugin/tests/css_zoom.spec.ts b/packages/chrome-plugin/tests/css_zoom.spec.ts
new file mode 100644
index 000000000..f3833ad98
--- /dev/null
+++ b/packages/chrome-plugin/tests/css_zoom.spec.ts
@@ -0,0 +1,69 @@
+import type { Page } from '@playwright/test';
+import { expect, test } from './fixtures';
+import { getHarperHighlights, getTextarea, replaceEditorContent } from './testUtils';
+
+test('Positions highlights inside an ancestor with CSS zoom.', async ({ page }) => {
+ await page.goto('http://localhost:8081/css_zoom.html');
+
+ const editor = getTextarea(page);
+ await replaceEditorContent(editor, 'This is an test of the Harper grammar checker.');
+
+ const highlights = getHarperHighlights(page);
+ await expect(highlights).toHaveCount(1, { timeout: 24000 });
+
+ const editorBox = (await editor.boundingBox())!;
+ const highlightBox = (await highlights.first().boundingBox())!;
+
+ // When the zoom is applied to the highlight a second time, it drifts below and to the
+ // right of the textarea.
+ expect(highlightBox.x).toBeGreaterThanOrEqual(editorBox.x);
+ expect(highlightBox.y).toBeGreaterThanOrEqual(editorBox.y);
+ expect(highlightBox.x + highlightBox.width).toBeLessThanOrEqual(editorBox.x + editorBox.width);
+ expect(highlightBox.y + highlightBox.height).toBeLessThanOrEqual(editorBox.y + editorBox.height);
+});
+
+/** The highlight box inside `textareaId`, relative to that textarea's top-left corner. */
+async function relativeHighlight(page: Page, textareaId: string) {
+ const editor = page.locator(`#${textareaId}`);
+ const editorBox = (await editor.boundingBox())!;
+
+ for (const highlight of await getHarperHighlights(page).all()) {
+ const box = await highlight.boundingBox();
+ if (
+ box != null &&
+ box.x >= editorBox.x &&
+ box.y >= editorBox.y &&
+ box.x < editorBox.x + editorBox.width &&
+ box.y < editorBox.y + editorBox.height
+ ) {
+ return { editorBox, x: box.x - editorBox.x, y: box.y - editorBox.y, width: box.width };
+ }
+ }
+
+ return null;
+}
+
+test('Positions highlights inside a scaled and zoomed ancestor.', async ({ page }) => {
+ await page.goto('http://localhost:8081/css_scale.html');
+
+ // Put the mistake far along the line, so a scale error adds up to a visible offset.
+ const text = 'The quick brown fox jumps over the lazy dog, and then an test.';
+ await replaceEditorContent(page.locator('#reference'), text);
+ await replaceEditorContent(page.locator('#scaled'), text);
+
+ await expect(getHarperHighlights(page)).toHaveCount(2, { timeout: 24000 });
+
+ const reference = (await relativeHighlight(page, 'reference'))!;
+ const scaled = (await relativeHighlight(page, 'scaled'))!;
+ expect(reference).not.toBeNull();
+ expect(scaled).not.toBeNull();
+
+ // Both textareas have the same layout size, so the scaled one should show the same
+ // highlight, just scaled by `scale: 0.9` times `zoom: 1.2` from css_scale.html. The ratio
+ // of the textareas' on-screen widths is not exact, because their borders snap to device
+ // pixels.
+ const ratio = 0.9 * 1.2;
+ expect(Math.abs(scaled.x / ratio - reference.x)).toBeLessThan(2);
+ expect(Math.abs(scaled.y / ratio - reference.y)).toBeLessThan(2);
+ expect(Math.abs(scaled.width / ratio - reference.width)).toBeLessThan(2);
+});
diff --git a/packages/chrome-plugin/tests/pages/css_scale.html b/packages/chrome-plugin/tests/pages/css_scale.html
new file mode 100644
index 000000000..f3b56b218
--- /dev/null
+++ b/packages/chrome-plugin/tests/pages/css_scale.html
@@ -0,0 +1,11 @@
+<!DOCTYPE html>
+<html>
+ <body style="margin: 0">
+ <textarea id="reference" style="position: absolute; top: 400px; left: 20px; font: 16px monospace" rows="3" cols="60"></textarea>
+ <div style="position: absolute; top: 64px; left: 0; scale: 0.9; transform-origin: 0 0">
+ <div style="zoom: 1.2">
+ <textarea id="scaled" style="margin: 20px 0 0 20px; font: 16px monospace" rows="3" cols="60"></textarea>
+ </div>
+ </div>
+ </body>
+</html>
diff --git a/packages/chrome-plugin/tests/pages/css_zoom.html b/packages/chrome-plugin/tests/pages/css_zoom.html
new file mode 100644
index 000000000..69ea40853
--- /dev/null
+++ b/packages/chrome-plugin/tests/pages/css_zoom.html
@@ -0,0 +1,8 @@
+<!DOCTYPE html>
+<html>
+ <body>
+ <div style="zoom: 1.5">
+ <textarea style="margin: 200px 0 0 200px" rows="3" cols="40"></textarea>
+ </div>
+ </body>
+</html>
diff --git a/packages/lint-framework/src/lint/Highlights.ts b/packages/lint-framework/src/lint/Highlights.ts
index 05a07aa27..2418f2fe1 100644
--- a/packages/lint-framework/src/lint/Highlights.ts
+++ b/packages/lint-framework/src/lint/Highlights.ts
@@ -25,7 +25,7 @@ import {
isGoogleDocsSourceSyncing,
} from './googleDocsAdapter';
import { type LintKind, lintKindColor } from './lintKindColor';
-import RenderBox from './RenderBox';
+import RenderBox, { FIXED_FRAME_MARKER_ID, type FixedFrame } from './RenderBox';
import type SourceElement from './SourceElement';
import type { UnpackedLint } from './unpackLint';
@@ -150,7 +150,21 @@ export default class Highlights {
googleDocsRenderOffset ?? (isGoogleDocs || cpa == null ? null : { x: cpa.x, y: cpa.y });
const boxPosition: 'absolute' | 'fixed' = isGoogleDocs ? 'absolute' : 'fixed';
- renderBox.render(this.renderTree(boxes, offset, boxPosition));
+ // Lint boxes are measured in viewport pixels, but the render box lives inside the
+ // source's subtree, where ancestors with `zoom`, `transform` or `scale` can move and
+ // scale fixed-position content. Map the boxes through the frame we actually get.
+ if (isGoogleDocs) {
+ renderBox.render(this.renderTree(boxes, offset, boxPosition));
+ } else {
+ // The frame is measured from a marker in the previous render, so render once more
+ // when it was missing or has moved since.
+ const before = renderBox.measureFixedFrame();
+ renderBox.render(this.renderTree(boxes, before, boxPosition));
+ const after = renderBox.measureFixedFrame();
+ if (after != null && !framesEqual(before, after)) {
+ renderBox.render(this.renderTree(boxes, after, boxPosition));
+ }
+ }
updated.add(source);
}
@@ -178,16 +192,38 @@ export default class Highlights {
private renderTree(
boxes: LintBox[],
- offset: { x: number; y: number } | null,
+ frame: { x: number; y: number; scaleX?: number; scaleY?: number } | null,
boxPosition: 'absolute' | 'fixed',
): VNode {
const elements = [];
- const offsetX = offset?.x ?? 0;
- const offsetY = offset?.y ?? 0;
+ const offsetX = frame?.x ?? 0;
+ const offsetY = frame?.y ?? 0;
+ const scale = { x: frame?.scaleX ?? 1, y: frame?.scaleY ?? 1 };
+
+ if (boxPosition === 'fixed') {
+ elements.push(
+ h(
+ 'div',
+ {
+ id: FIXED_FRAME_MARKER_ID,
+ style: {
+ position: 'fixed',
+ left: '0px',
+ top: '0px',
+ width: '100px',
+ height: '100px',
+ visibility: 'hidden',
+ pointerEvents: 'none',
+ },
+ },
+ [],
+ ),
+ );
+ }
for (const box of boxes) {
- const x = box.x - offsetX;
- const y = box.y - offsetY;
+ const x = (box.x - offsetX) / scale.x;
+ const y = (box.y - offsetY) / scale.y;
const positionStyle =
boxPosition === 'fixed'
? {
@@ -207,8 +243,8 @@ export default class Highlights {
{
style: {
...positionStyle,
- width: `${box.width}px`,
- height: `${box.height}px`,
+ width: `${box.width / scale.x}px`,
+ height: `${box.height / scale.y}px`,
pointerEvents: 'none',
borderBottom: `2px solid ${lintKindColor(box.lint.lint_kind)}`,
backgroundColor: `${lintKindColor(box.lint.lint_kind)}22`,
@@ -266,6 +302,16 @@ export default class Highlights {
}
}
+function framesEqual(a: FixedFrame | null, b: FixedFrame): boolean {
+ return (
+ a != null &&
+ Math.abs(a.x - b.x) < 0.5 &&
+ Math.abs(a.y - b.y) < 0.5 &&
+ Math.abs(a.scaleX - b.scaleX) < 0.001 &&
+ Math.abs(a.scaleY - b.scaleY) < 0.001
+ );
+}
+
function getInitialContainingRect(el: HTMLElement): DOMRect | null {
let node = el.parentElement;
diff --git a/packages/lint-framework/src/lint/RenderBox.ts b/packages/lint-framework/src/lint/RenderBox.ts
index f4059c5ca..ab1ca852b 100644
--- a/packages/lint-framework/src/lint/RenderBox.ts
+++ b/packages/lint-framework/src/lint/RenderBox.ts
@@ -5,6 +5,12 @@ import patch from 'virtual-dom/patch';
type ParentResolver = () => Node;
+/** The id of the invisible `position: fixed` marker used by `RenderBox.measureFixedFrame`. */
+export const FIXED_FRAME_MARKER_ID = 'harper-fixed-frame';
+
+/** The on-screen origin and scale of `position: fixed` content inside a render box. */
+export type FixedFrame = { x: number; y: number; scaleX: number; scaleY: number };
+
/** 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. */
@@ -30,8 +36,7 @@ export default class RenderBox {
if (!this.virtualRoot || !this.virtualTree) {
this.virtualRoot = createElement(node);
- const shadow = this.shadowHost.attachShadow({ mode: 'open' });
- shadow.appendChild(this.virtualRoot);
+ this.getShadowRoot().appendChild(this.virtualRoot);
} else {
const patches = diff(this.virtualTree, node);
this.virtualRoot = patch(this.virtualRoot, patches);
@@ -39,6 +44,33 @@ export default class RenderBox {
this.virtualTree = node;
}
+ /**
+ * Measure where the rendered frame marker (see `FIXED_FRAME_MARKER_ID`), a `position: fixed`
+ * element placed at (0, 0) and 100px wide, actually lands on screen and how much it is
+ * scaled. Ancestors with CSS `zoom`, `transform`, `scale` and similar properties change
+ * both, so highlights have to be mapped through this frame. Returns `null` before the
+ * marker has been rendered.
+ */
+ public measureFixedFrame(): FixedFrame | null {
+ const marker = this.shadowHost.shadowRoot?.getElementById(FIXED_FRAME_MARKER_ID);
+ if (marker == null || !marker.isConnected) {
+ return null;
+ }
+
+ const rect = marker.getBoundingClientRect();
+
+ return {
+ x: rect.x,
+ y: rect.y,
+ scaleX: rect.width > 0 ? rect.width / 100 : 1,
+ scaleY: rect.height > 0 ? rect.height / 100 : 1,
+ };
+ }
+
+ private getShadowRoot(): ShadowRoot {
+ return this.shadowHost.shadowRoot ?? this.shadowHost.attachShadow({ mode: 'open' });
+ }
+
/** Remove the box from the DOM. */
public remove() {
try {
diff --git a/packages/lint-framework/src/lint/TextFieldRange.ts b/packages/lint-framework/src/lint/TextFieldRange.ts
index d9b08d0cf..d685d06de 100644
--- a/packages/lint-framework/src/lint/TextFieldRange.ts
+++ b/packages/lint-framework/src/lint/TextFieldRange.ts
@@ -129,11 +129,23 @@ export default class TextFieldRange {
const fieldRect = field.getBoundingClientRect();
const scrollTop = window.scrollY || document.documentElement.scrollTop;
const scrollLeft = window.scrollX || document.documentElement.scrollLeft;
+
+ // The copied styles are in the field's own CSS pixels, while its bounding rect is on
+ // screen. When an ancestor zooms or scales the field (CSS `zoom`, `transform`, `scale`),
+ // lay the mirror out at the field's own size and scale it to match what is on screen.
+ const width = field.offsetWidth || fieldRect.width;
+ const height = field.offsetHeight || fieldRect.height;
+ const scaleX = width > 0 ? fieldRect.width / width : 1;
+ const scaleY = height > 0 ? fieldRect.height / height : 1;
+ const scaled = Math.abs(scaleX - 1) > 0.001 || Math.abs(scaleY - 1) > 0.001;
+
Object.assign(mirror.style, {
top: `${fieldRect.top + scrollTop}px`,
left: `${fieldRect.left + scrollLeft}px`,
- width: `${fieldRect.width}px`,
- height: `${fieldRect.height}px`,
+ width: `${scaled ? width : fieldRect.width}px`,
+ height: `${scaled ? height : fieldRect.height}px`,
+ transform: scaled ? `scale(${scaleX}, ${scaleY})` : '',
+ transformOrigin: scaled ? '0 0' : '',
});
}