Offline, privacy-first grammar checker. Fast, open-source, Rust-powered
fix(chrome-ext): fix several Google Docs problems (#4484)
Elijah Potter7b64cdfff644
diff --git a/packages/chrome-plugin/public/google-docs-bridge.js b/packages/chrome-plugin/public/google-docs-bridge.jsindex 6e301c773..fbca76661 100644--- a/packages/chrome-plugin/public/google-docs-bridge.js+++ b/packages/chrome-plugin/public/google-docs-bridge.js@@ -145,7 +145,7 @@ import { GoogleDocsBridgeRequestHandler } from './google-docs-bridge-request-hanfunction getAnnotatedTextApi() {return typeof window._docs_annotate_getAnnotatedText === 'function'- ? window._docs_annotate_getAnnotatedText+ ? () => window._docs_annotate_getAnnotatedText(window._docs_annotate_canvas_by_ext): null;}@@ -672,16 +672,15 @@ import { GoogleDocsBridgeRequestHandler } from './google-docs-bridge-request-hanconst rawStart = normalizedToRawOffset(rawText, resolvedRange.start);const rawEnd = normalizedToRawOffset(rawText, resolvedRange.end);- annotated.setSelection(rawStart, rawEnd);-const iframe = document.querySelector(TEXT_EVENT_IFRAME_SELECTOR);const targetDocument = iframe?.contentDocument;- const target = targetDocument?.activeElement;+ const target = targetDocument?.querySelector('[contenteditable="true"]');if (!target) {return { kind: 'replaceText', applied: false };}target.focus?.();+ annotated.setSelection(rawStart, rawEnd);const expectedNextText =currentText.slice(0, resolvedRange.start) +@@ -693,16 +692,6 @@ import { GoogleDocsBridgeRequestHandler } from './google-docs-bridge-request-hanreturn normalizeGoogleDocsText(nextAnnotated?.getText?.()) === expectedNextText;};- if (targetDocument?.execCommand?.('insertText', false, replacementText)) {- await new Promise((resolve) => setTimeout(resolve, 0));- if (await didApplyReplacement()) {- queueMicrotask(() => {- void syncText();- });- return { kind: 'replaceText', applied: true };- }- }-const dataTransfer = new DataTransfer();dataTransfer.setData('text/plain', replacementText);target.dispatchEvent(diff --git a/packages/chrome-plugin/src/contentScript/googleDocs.ts b/packages/chrome-plugin/src/contentScript/googleDocs.tsindex bb01753d0..7b6a04e94 100644--- a/packages/chrome-plugin/src/contentScript/googleDocs.ts+++ b/packages/chrome-plugin/src/contentScript/googleDocs.ts@@ -55,7 +55,6 @@ export function createGoogleDocsBridgeSync(fw: LintFramework): () => Promise<voilet bridgeAttached = false;let syncInFlight = false;let syncPending = false;- let syncingClearTimer: number | null = null;let lastCloneSignature = '';let injectedMainWorldBridge = false;@@ -193,6 +192,13 @@ export function createGoogleDocsBridgeSync(fw: LintFramework): () => Promise<voiconst fontCss = segment.rectNode.getAttribute('data-font-css');if (fontCss) {span.style.font = fontCss;+ // Docs zooms the SVG, but data-font-css remains in unscaled SVG units.+ // The mirror uses screen-space geometry, so its font must use the same scale.+ const svgWidth = segment.rectNode.width.baseVal.value;+ const fontSize = Number.parseFloat(span.style.fontSize);+ if (svgWidth > 0 && Number.isFinite(fontSize)) {+ span.style.fontSize = `${fontSize * (segment.rect.width / svgWidth)}px`;+ }}return span;@@ -535,10 +541,6 @@ export function createGoogleDocsBridgeSync(fw: LintFramework): () => Promise<voi}const target = ensureTarget(editor);- if (syncingClearTimer != null) {- window.clearTimeout(syncingClearTimer);- syncingClearTimer = null;- }editor.setAttribute(GOOGLE_DOCS_SYNCING_ATTR, 'true');const changed = applySnapshot(target, buildSnapshot(editor));@@ -555,10 +557,9 @@ export function createGoogleDocsBridgeSync(fw: LintFramework): () => Promise<voi} finally {const editor = document.querySelector(GOOGLE_DOCS_EDITOR_SELECTOR);if (editor instanceof HTMLElement) {- syncingClearTimer = window.setTimeout(() => {- editor.removeAttribute(GOOGLE_DOCS_SYNCING_ATTR);- syncingClearTimer = null;- }, 150);+ // Snapshot replacement is complete before the queued animation-frame render.+ // Keeping this flag set delays that render until an unrelated later update.+ editor.removeAttribute(GOOGLE_DOCS_SYNCING_ATTR);}syncInFlight = false;diff --git a/packages/chrome-plugin/tests/google_docs.spec.ts b/packages/chrome-plugin/tests/google_docs.spec.tsindex 567e7b4b9..eababc6d7 100644--- a/packages/chrome-plugin/tests/google_docs.spec.ts+++ b/packages/chrome-plugin/tests/google_docs.spec.ts@@ -1,5 +1,6 @@import type { Page } from '@playwright/test';import { expect, test } from './fixtures';+import { getBackground } from './testUtils';type MockGoogleDocsRect = {label: string;@@ -369,7 +370,6 @@ function buildMockGoogleDocsHtml(rects: MockGoogleDocsRect[]): string {height: 240px;margin: 32px auto;background: white;- border: 1px solid #d1d5db;}svg {@@ -429,16 +429,21 @@ async function installMockGoogleDocsGeometry(getSelection: () => Array<{ start: number; end: number }>;}>;}- )._docs_annotate_getAnnotatedText = async () => ({- getText: () =>- (- window as Window & {- __harperMockGoogleDocsText?: string;- }- ).__harperMockGoogleDocsText ?? '',- setSelection: () => {},- getSelection: () => [{ start: 0, end: 0 }],- });+ )._docs_annotate_getAnnotatedText = async (extensionId?: string) => {+ if (!extensionId) {+ throw new Error('Google Docs requires an extension identifier');+ }+ return {+ getText: () =>+ (+ window as Window & {+ __harperMockGoogleDocsText?: string;+ }+ ).__harperMockGoogleDocsText ?? '',+ setSelection: () => {},+ getSelection: () => [{ start: 0, end: 0 }],+ };+ };},{ pageText: annotatedText },);@@ -477,6 +482,71 @@ async function getBridgeSource(page: Page) {}test.describe('Google Docs support', () => {+ test('scales highlight offsets and widths with Google Docs zoom', async ({ page }) => {+ await openMockGoogleDocsPage(page, [+ {+ label: 'This is an test.',+ left: 48,+ top: 48,+ width: 144,+ height: 18,+ fontCss: '16px Arial',+ },+ ]);+ const highlight = page.locator('#harper-highlight').first();+ await highlight.waitFor({ state: 'visible' });+ const baseline = (await highlight.boundingBox())!;+ const rect = page.locator('rect[aria-label]').first();+ const baselineRect = (await rect.boundingBox())!;++ for (const scale of [1.5, 0.75, 2, 1]) {+ await page.locator('svg').evaluate((svg, scale) => {+ svg.style.transformOrigin = '0 0';+ svg.style.transform = `scale(${scale})`;+ }, scale);+ await expect+ .poll(async () => {+ const box = await highlight.boundingBox();+ const source = await rect.boundingBox();+ if (!box || !source) return Number.POSITIVE_INFINITY;+ return Math.max(+ Math.abs(box.width - baseline.width * scale),+ Math.abs(box.x - source.x - (baseline.x - baselineRect.x) * scale),+ );+ })+ .toBeLessThan(1);+ }+ });++ test('lints the logical text across positioned formatting spans', async ({ page, context }) => {+ const background = await getBackground(context);+ await background.evaluate(() => {+ const state = globalThis as typeof globalThis & { googleDocsLintTexts: string[] };+ state.googleDocsLintTexts = [];+ chrome.runtime.onMessage.addListener((request) => {+ if (request.kind === 'lint' && request.domain === 'docs.google.com') {+ state.googleDocsLintTexts.push(request.text);+ }+ });+ });++ await openMockGoogleDocsPage(+ page,+ ITALIC_SHIFTED_RECTS.map((rect) => ({ ...rect, label: rect.label.trimEnd() })),+ 'This is an test.',+ );+ await expect.poll(() => getBridgeSource(page)).toBe('logical');+ await expect+ .poll(() =>+ background.evaluate(+ () =>+ (globalThis as typeof globalThis & { googleDocsLintTexts: string[] })+ .googleDocsLintTexts,+ ),+ )+ .toContain('This is an test.');+ });+test('Google Docs restores spaces around formatted inline words', async ({ page }) => {await openMockGoogleDocsPage(page, FORMATTED_WORD_GAP_RECTS, 'not smart enough.');diff --git a/packages/lint-framework/src/lint/LintFramework.ts b/packages/lint-framework/src/lint/LintFramework.tsindex 65afd955b..15045d1b5 100644--- a/packages/lint-framework/src/lint/LintFramework.ts+++ b/packages/lint-framework/src/lint/LintFramework.ts@@ -1,5 +1,6 @@import type { LintOptions } from 'harper.js';import { closestBox, type IgnorableLintBox } from './Box';+import { isGoogleDocsTarget } from './computeLintBoxes/googleDocsUtilities';import computeLintBoxes from './computeLintBoxes/index';import { isHeading, isVisible } from './domUtils';import { getCaretPosition, getCMRoot } from './editorUtils';@@ -335,6 +336,10 @@ export default class LintFramework {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 if (target instanceof HTMLElement && isGoogleDocsTarget(target)) {+ // The mirror already contains logical whitespace. innerText inserts line breaks+ // between its positioned spans, splitting sentences at formatting boundaries.+ text = target.textContent;} else {text =target instanceof HTMLTextAreaElement || target instanceof HTMLInputElement