Offline, privacy-first grammar checker. Fast, open-source, Rust-powered
fix(chrome-ext): issues with Google Docs (#3141)
Elijah Potter0f00dec44b53
diff --git a/packages/chrome-plugin/playwright.config.ts b/packages/chrome-plugin/playwright.config.tsindex 9a4470444..9fcbf00ee 100644--- a/packages/chrome-plugin/playwright.config.ts+++ b/packages/chrome-plugin/playwright.config.ts@@ -5,6 +5,7 @@ import { defineConfig, devices } from '@playwright/test';*/export default defineConfig({testDir: './tests',+ testIgnore: ['**/google_docs*.spec.ts', '**/googleDocs*.spec.ts'],fullyParallel: true,/* Fail the build on CI if you accidentally left test.only in the source code. */forbidOnly: !!process.env.CI,diff --git a/packages/chrome-plugin/public/google-docs-bridge.js b/packages/chrome-plugin/public/google-docs-bridge.jsindex e45681f65..6e301c773 100644--- a/packages/chrome-plugin/public/google-docs-bridge.js+++ b/packages/chrome-plugin/public/google-docs-bridge.js@@ -3,23 +3,18 @@ import { GoogleDocsBridgeRequestHandler } from './google-docs-bridge-request-han(() => {/*** @typedef {{ x: number, y: number, width: number, height: number }} Rect- */-- /*** @typedef {{ start: number, end: number }} SelectionEndpoints- */-- /*** @typedef {{* getText: () => string,* setSelection: (start: number, end: number) => void,* getSelection?: () => Array<Record<string, unknown>>* }} AnnotatedText+ * @typedef {{ node: Window | Element, left: number, top: number }} ScrollSnapshot*/const PROTOCOL_VERSION = 'harper-gdocs-bridge/v1';const BRIDGE_ID = 'harper-google-docs-main-world-bridge';- const SYNC_INTERVAL_MS = 100;+ const POLL_INTERVAL_MS = 125;const EDITOR_SELECTOR = '.kix-appview-editor';const EDITOR_CONTAINER_SELECTOR = '.kix-appview-editor-container';const DOCS_EDITOR_SELECTOR = '#docs-editor';@@ -34,21 +29,22 @@ import { GoogleDocsBridgeRequestHandler } from './google-docs-bridge-request-hanconst EVENT_LAYOUT_CHANGED = 'harper:gdocs:layout-changed';const EVENT_GET_RECTS = 'harper:gdocs:get-rects';const EVENT_REPLACE = 'harper:gdocs:replace';-- let isComputingRects = false;- let layoutEpoch = 0;- let layoutBumpPending = false;- let lastCaretChoice = null;const CARET_DIRECTION_THRESHOLD = 20;const CARET_CHOICE_STALE_MS = 1500;- /** @type {HTMLElement | null} */- let bridge = document.getElementById(BRIDGE_ID);+ let bridgeNode = /** @type {HTMLElement | null} */ (document.getElementById(BRIDGE_ID));+ let currentAnnotated = /** @type {AnnotatedText | null} */ (null);+ let observedEditor = /** @type {HTMLElement | null} */ (null);+ let layoutObserver = /** @type {MutationObserver | null} */ (null);+ let resizeObserver = /** @type {ResizeObserver | null} */ (null);+ let layoutEpoch = 0;+ let layoutScheduled = false;+ let lastCaretChoice = /** @type {{ rect: Rect, position: number, at: number } | null} */ (null);+ let textSyncInFlight = false;- /** @returns {HTMLElement} */- function ensureBridgeExists() {- if (bridge) {- return bridge;+ function ensureBridgeNode() {+ if (bridgeNode instanceof HTMLElement) {+ return bridgeNode;}const nextBridge = document.createElement('div');@@ -56,159 +52,356 @@ import { GoogleDocsBridgeRequestHandler } from './google-docs-bridge-request-hannextBridge.setAttribute('aria-hidden', 'true');nextBridge.style.display = 'none';document.documentElement.appendChild(nextBridge);- bridge = nextBridge;-+ bridgeNode = nextBridge;return nextBridge;}- ensureBridgeExists();-- /** @param {string} name- * @param {Record<string, unknown>} detail- * @returns {void}- */- const emitEvent = (name, detail) => {+ function dispatchEvent(name, detail) {try {document.dispatchEvent(new CustomEvent(name, { detail }));} catch {}- };+ }- /**- * @param {'textUpdated' | 'layoutChanged'} name- * @param {Record<string, unknown>} detail- * @returns {void}- */- const emitNotification = (name, detail) => {- try {- document.dispatchEvent(- new CustomEvent(EVENT_NOTIFICATION, {- detail: {- protocol: PROTOCOL_VERSION,- notification: { kind: name, ...detail },- },- }),- );- } catch {}- };+ function dispatchNotification(kind, detail) {+ dispatchEvent(EVENT_NOTIFICATION, {+ protocol: PROTOCOL_VERSION,+ notification: {+ kind,+ ...detail,+ },+ });+ }- /**- * @param {string} reason- * @returns {void}- */- const bumpLayoutEpoch = (reason) => {- if (layoutBumpPending) return;- layoutBumpPending = true;+ function scheduleLayoutUpdate(reason) {+ if (layoutScheduled) {+ return;+ }++ layoutScheduled = true;queueMicrotask(() => {- layoutBumpPending = false;+ layoutScheduled = false;layoutEpoch += 1;- const bridgeNode = ensureBridgeExists();- bridgeNode.setAttribute(LAYOUT_EPOCH_ATTR, String(layoutEpoch));- bridgeNode.setAttribute(LAYOUT_REASON_ATTR, String(reason));- emitEvent(EVENT_LAYOUT_CHANGED, { layoutEpoch, reason });- emitNotification('layoutChanged', { layoutEpoch, reason });+ const bridge = ensureBridgeNode();+ bridge.setAttribute(LAYOUT_EPOCH_ATTR, String(layoutEpoch));+ bridge.setAttribute(LAYOUT_REASON_ATTR, String(reason));+ dispatchEvent(EVENT_LAYOUT_CHANGED, { layoutEpoch, reason });+ dispatchNotification('layoutChanged', { layoutEpoch, reason });});- };+ }++ function normalizeGoogleDocsText(text) {+ const raw = String(text ?? '');+ const withoutSentinel = raw.startsWith('\u0003') ? raw.slice(1) : raw;+ return withoutSentinel.endsWith('\n') ? withoutSentinel.slice(0, -1) : withoutSentinel;+ }++ function normalizedToRawOffset(rawText, normalizedOffset) {+ const raw = String(rawText ?? '');+ const leadingOffset = raw.startsWith('\u0003') ? 1 : 0;+ const trailingOffset = raw.endsWith('\n') ? 1 : 0;+ const rawEnd = Math.max(leadingOffset, raw.length - trailingOffset);+ const safeOffset = Math.max(0, Number.isFinite(normalizedOffset) ? normalizedOffset : 0);++ return Math.max(leadingOffset, Math.min(rawEnd, safeOffset + leadingOffset));+ }++ function rawToNormalizedOffset(rawText, rawOffset) {+ const raw = String(rawText ?? '');+ const leadingOffset = raw.startsWith('\u0003') ? 1 : 0;+ const trailingOffset = raw.endsWith('\n') ? 1 : 0;+ const rawEnd = Math.max(leadingOffset, raw.length - trailingOffset);+ const safeOffset = Math.max(+ leadingOffset,+ Math.min(rawEnd, Number.isFinite(rawOffset) ? rawOffset : leadingOffset),+ );++ return Math.max(0, safeOffset - leadingOffset);+ }++ function asFiniteNumber(value) {+ const number = Number(value);+ return Number.isFinite(number) ? number : null;+ }++ function getSelectionEndpoints(selection) {+ if (!selection || typeof selection !== 'object') {+ return null;+ }++ for (const [startKey, endKey] of [+ ['anchor', 'focus'],+ ['base', 'extent'],+ ['start', 'end'],+ ]) {+ const start = asFiniteNumber(selection[startKey]);+ const end = asFiniteNumber(selection[endKey]);+ if (start != null && end != null) {+ return { start, end };+ }+ }++ return null;+ }++ function getAnnotatedTextApi() {+ return typeof window._docs_annotate_getAnnotatedText === 'function'+ ? window._docs_annotate_getAnnotatedText+ : null;+ }++ async function syncText() {+ if (textSyncInFlight) {+ return;+ }++ textSyncInFlight = true;- /** @returns {Promise<void>} */- const syncText = async () => {try {- const getAnnotatedText = window._docs_annotate_getAnnotatedText;- if (typeof getAnnotatedText !== 'function') return;- /** @type {AnnotatedText | null | undefined} */+ const getAnnotatedText = getAnnotatedTextApi();+ if (!getAnnotatedText) {+ return;+ }+const annotated = await getAnnotatedText();- if (!annotated || typeof annotated.getText !== 'function') return;+ if (!annotated || typeof annotated.getText !== 'function') {+ return;+ }++ currentAnnotated = annotated;window.__harperGoogleDocsAnnotatedText = annotated;- try {- const selection = annotated.getSelection?.()?.[0];- const endpoints = getSelectionEndpoints(selection);- const bridgeNode = ensureBridgeExists();- if (endpoints) {- bridgeNode.setAttribute(SELECTION_START_ATTR, String(endpoints.start));- bridgeNode.setAttribute(SELECTION_END_ATTR, String(endpoints.end));- } else {- bridgeNode.removeAttribute(SELECTION_START_ATTR);- bridgeNode.removeAttribute(SELECTION_END_ATTR);++ const rawText = annotated.getText();+ const normalizedText = normalizeGoogleDocsText(rawText);+ const bridge = ensureBridgeNode();+ const selection = getSelectionEndpoints(annotated.getSelection?.()?.[0]);++ if (selection) {+ bridge.setAttribute(+ SELECTION_START_ATTR,+ String(rawToNormalizedOffset(rawText, selection.start)),+ );+ bridge.setAttribute(+ SELECTION_END_ATTR,+ String(rawToNormalizedOffset(rawText, selection.end)),+ );+ } else {+ bridge.removeAttribute(SELECTION_START_ATTR);+ bridge.removeAttribute(SELECTION_END_ATTR);+ }++ if (bridge.textContent !== normalizedText) {+ bridge.textContent = normalizedText;+ dispatchEvent(EVENT_TEXT_UPDATED, { length: normalizedText.length });+ dispatchNotification('textUpdated', { length: normalizedText.length });+ }+ } catch {+ // Ignore bridge sync failures. The next poll or mutation will retry.+ } finally {+ textSyncInFlight = false;+ }+ }++ function disconnectLayoutObservers() {+ layoutObserver?.disconnect();+ layoutObserver = null;+ resizeObserver?.disconnect();+ resizeObserver = null;+ observedEditor = null;+ }++ function bindLayoutObservers() {+ const editor = document.querySelector(EDITOR_SELECTOR);+ if (!(editor instanceof HTMLElement)) {+ disconnectLayoutObservers();+ return;+ }++ if (editor === observedEditor) {+ return;+ }++ disconnectLayoutObservers();+ observedEditor = editor;+ scheduleLayoutUpdate('init');++ layoutObserver = new MutationObserver((mutations) => {+ for (const mutation of mutations) {+ if (mutation.type === 'childList' || mutation.type === 'attributes') {+ scheduleLayoutUpdate('mutation');+ break;}+ }+ });+ layoutObserver.observe(editor, {+ subtree: true,+ childList: true,+ attributes: true,+ attributeFilter: ['style', 'class'],+ });++ if (typeof ResizeObserver !== 'undefined') {+ resizeObserver = new ResizeObserver(() => {+ scheduleLayoutUpdate('resize');+ });+ resizeObserver.observe(editor);+ }+ }++ function snapshotScroll() {+ /** @type {ScrollSnapshot[]} */+ const snapshots = [{ node: window, left: window.scrollX, top: window.scrollY }];+ const selectors = [EDITOR_SELECTOR, EDITOR_CONTAINER_SELECTOR, DOCS_EDITOR_SELECTOR];++ for (const selector of selectors) {+ const node = document.querySelector(selector);+ if (!(node instanceof Element) || snapshots.some((entry) => entry.node === node)) {+ continue;+ }++ snapshots.push({+ node,+ left: node.scrollLeft,+ top: node.scrollTop,+ });+ }++ return snapshots;+ }++ function restoreScroll(snapshots) {+ for (const snapshot of snapshots) {+ if (snapshot.node === window) {+ if (window.scrollX !== snapshot.left || window.scrollY !== snapshot.top) {+ window.scrollTo(snapshot.left, snapshot.top);+ }+ continue;+ }++ if (!(snapshot.node instanceof Element)) {+ continue;+ }++ if (snapshot.node.scrollLeft !== snapshot.left) {+ snapshot.node.scrollLeft = snapshot.left;+ }++ if (snapshot.node.scrollTop !== snapshot.top) {+ snapshot.node.scrollTop = snapshot.top;+ }+ }+ }++ function withSuppressedScrolling(fn) {+ /** @type {Array<() => void>} */+ const restorers = [];+ const noop = () => {};++ const tryOverride = (target, key) => {+ if (!target || typeof target[key] !== 'function') {+ return;+ }++ const original = target[key];+ try {+ target[key] = noop;+ restorers.push(() => {+ try {+ target[key] = original;+ } catch {}+ });} catch {}- const nextText = annotated.getText();- const bridgeNode = ensureBridgeExists();- if (bridgeNode.textContent !== nextText) {- bridgeNode.textContent = nextText;- emitEvent(EVENT_TEXT_UPDATED, { length: nextText.length });- emitNotification('textUpdated', { length: nextText.length });+ };++ tryOverride(window, 'scrollTo');+ tryOverride(window, 'scrollBy');+ tryOverride(Element.prototype, 'scrollIntoView');+ tryOverride(Element.prototype, 'scrollTo');+ tryOverride(Element.prototype, 'scrollBy');++ try {+ return fn();+ } finally {+ for (let index = restorers.length - 1; index >= 0; index -= 1) {+ restorers[index]();}- } catch {}- };+ }+ }- /**- * @param {AnnotatedText} annotated- * @param {number} position- * @returns {Rect | null}- */- const getCaretRect = (annotated, position) => {+ function getCaretRect(annotated, position) {annotated.setSelection(position, position);+ const epsilon = 0.5;const viewportWidth = window.innerWidth;const viewportHeight = window.innerHeight;- const epsilon = 0.5;/** @type {Rect[]} */const carets = Array.from(document.querySelectorAll(CARET_SELECTOR)).map((caret) => {const rect = caret.getBoundingClientRect();const style = window.getComputedStyle(caret);- const isFullyOnScreen =+ const onScreen =rect.left >= -epsilon &&rect.top >= -epsilon &&rect.right <= viewportWidth + epsilon &&rect.bottom <= viewportHeight + epsilon;+if (- !rect ||rect.width <= 0 ||rect.height <= 0 ||style.display === 'none' ||style.visibility === 'hidden' ||style.opacity === '0' ||- !isFullyOnScreen+ !onScreen) {return null;}- return { x: rect.x, y: rect.y, width: rect.width, height: rect.height };++ return {+ x: rect.x,+ y: rect.y,+ width: rect.width,+ height: rect.height,+ };}).filter((rect) => rect != null);- if (carets.length === 0) return null;- const inPage = carets.filter((rect) => rect.x > 100);- const pool = inPage.length > 0 ? inPage : carets;++ if (carets.length === 0) {+ return null;+ }++ const visiblePageCarets = carets.filter((rect) => rect.x > 100);+ const pool = visiblePageCarets.length > 0 ? visiblePageCarets : carets;const now = Date.now();+if (!lastCaretChoice || now - lastCaretChoice.at > CARET_CHOICE_STALE_MS) {- const seed = pool.reduce((best, rect) => (rect.x < best.x ? rect : best), pool[0]);- lastCaretChoice = { rect: seed, position, at: now };- return seed;+ const choice = pool.reduce((best, rect) => (rect.x < best.x ? rect : best), pool[0]);+ lastCaretChoice = { rect: choice, position, at: now };+ return choice;}- const deltaPos = position - lastCaretChoice.position;- let chosen = null;+ const positionDelta = position - lastCaretChoice.position;+ let choice = null;- if (deltaPos > CARET_DIRECTION_THRESHOLD) {- const downward = pool.filter((rect) => rect.y >= lastCaretChoice.rect.y - 2);- if (downward.length > 0) {- chosen = downward.reduce((best, rect) => {+ if (positionDelta > CARET_DIRECTION_THRESHOLD) {+ const lowerRects = pool.filter((rect) => rect.y >= lastCaretChoice.rect.y - 2);+ if (lowerRects.length > 0) {+ choice = lowerRects.reduce((best, rect) => {if (rect.y > best.y + 1) return rect;if (Math.abs(rect.y - best.y) <= 1 && rect.x < best.x) return rect;return best;- }, downward[0]);+ }, lowerRects[0]);}- } else if (deltaPos < -CARET_DIRECTION_THRESHOLD) {- const upward = pool.filter((rect) => rect.y <= lastCaretChoice.rect.y + 2);- if (upward.length > 0) {- chosen = upward.reduce((best, rect) => {+ } else if (positionDelta < -CARET_DIRECTION_THRESHOLD) {+ const upperRects = pool.filter((rect) => rect.y <= lastCaretChoice.rect.y + 2);+ if (upperRects.length > 0) {+ choice = upperRects.reduce((best, rect) => {if (rect.y < best.y - 1) return rect;if (Math.abs(rect.y - best.y) <= 1 && rect.x < best.x) return rect;return best;- }, upward[0]);+ }, upperRects[0]);}}- if (!chosen) {- chosen = pool.reduce((best, rect) => {+ if (!choice) {+ choice = pool.reduce((best, rect) => {const bestScore =Math.abs(best.y - lastCaretChoice.rect.y) * 4 + Math.abs(best.x - lastCaretChoice.rect.x);const rectScore =@@ -217,196 +410,212 @@ import { GoogleDocsBridgeRequestHandler } from './google-docs-bridge-request-han}, pool[0]);}- lastCaretChoice = { rect: chosen, position, at: now };- return chosen;- };-- /**- * @param {unknown} value- * @returns {number | null}- */- const asFiniteNumber = (value) => {- const num = Number(value);- return Number.isFinite(num) ? num : null;- };-- /**- * @param {unknown} selection- * @returns {SelectionEndpoints | null}- */- const getSelectionEndpoints = (selection) => {- if (!selection || typeof selection !== 'object') {- return null;- }-- const candidates = [- ['anchor', 'focus'],- ['base', 'extent'],- ['start', 'end'],- ];+ lastCaretChoice = { rect: choice, position, at: now };+ return choice;+ }- for (const [a, b] of candidates) {- const start = asFiniteNumber(selection[a]);- const end = asFiniteNumber(selection[b]);- if (start != null && end != null) {- return { start, end };- }+ function restoreSelection(annotated, selection) {+ if (!selection) {+ return;}- return null;- };-- /**- * @param {AnnotatedText} annotated- * @param {SelectionEndpoints | null} selection- * @returns {void}- */- const restoreSelection = (annotated, selection) => {- if (!selection) return;try {annotated.setSelection(selection.start, selection.end);} catch {}- };+ }++ function isSpanNearSelection(start, end, selection) {+ if (!selection) {+ return false;+ }- /**- * @param {number} start- * @param {number} end- * @param {SelectionEndpoints | null} selection- * @returns {boolean}- */- const isSpanNearSelection = (start, end, selection) => {- if (!selection) return false;const spanStart = Math.max(0, Math.min(start, end));const spanEnd = Math.max(spanStart, Math.max(start, end));- const selStart = Math.min(selection.start, selection.end);- const selEnd = Math.max(selection.start, selection.end);+ const selectionStart = Math.min(selection.start, selection.end);+ const selectionEnd = Math.max(selection.start, selection.end);const maxDistance = 2000;- if (spanStart <= selEnd && spanEnd >= selStart) {+ if (spanStart <= selectionEnd && spanEnd >= selectionStart) {return true;}- if (spanEnd < selStart) {- return selStart - spanEnd <= maxDistance;++ if (spanEnd < selectionStart) {+ return selectionStart - spanEnd <= maxDistance;}- return spanStart - selEnd <= maxDistance;- };- /**- * @typedef {{- * node: Window | Element,- * left: number,- * top: number- * }} ScrollSnapshot- */+ return spanStart - selectionEnd <= maxDistance;+ }- /**- * @returns {ScrollSnapshot[]}- */- const snapshotScroll = () => {- /** @type {ScrollSnapshot[]} */- const snapshots = [{ node: window, left: window.scrollX, top: window.scrollY }];- const selectors = [EDITOR_SELECTOR, EDITOR_CONTAINER_SELECTOR, DOCS_EDITOR_SELECTOR];- for (const selector of selectors) {- const node = document.querySelector(selector);- if (!(node instanceof Element)) continue;- if (snapshots.some((entry) => entry.node === node)) continue;- snapshots.push({ node, left: node.scrollLeft, top: node.scrollTop });+ function getCommonPrefixLength(left, right) {+ const maxLength = Math.min(left.length, right.length);+ let index = 0;++ while (index < maxLength && left.charCodeAt(index) === right.charCodeAt(index)) {+ index += 1;}- return snapshots;- };- /**- * @param {ScrollSnapshot[]} snapshots- * @returns {void}- */- const restoreScroll = (snapshots) => {- for (const snap of snapshots) {- if (snap.node === window) {- if (window.scrollX !== snap.left || window.scrollY !== snap.top) {- window.scrollTo(snap.left, snap.top);+ return index;+ }++ function getCommonSuffixLength(left, right) {+ const maxLength = Math.min(left.length, right.length);+ let index = 0;++ while (+ index < maxLength &&+ left.charCodeAt(left.length - 1 - index) === right.charCodeAt(right.length - 1 - index)+ ) {+ index += 1;+ }++ return index;+ }++ function getLongestCommonSubsequenceLength(left, right) {+ if (!left || !right) {+ return 0;+ }++ const previous = new Array(right.length + 1).fill(0);+ const current = new Array(right.length + 1).fill(0);++ for (let i = 1; i <= left.length; i += 1) {+ current[0] = 0;++ for (let j = 1; j <= right.length; j += 1) {+ if (left.charCodeAt(i - 1) === right.charCodeAt(j - 1)) {+ current[j] = previous[j - 1] + 1;+ } else {+ current[j] = Math.max(previous[j], current[j - 1]);}+ }++ for (let j = 0; j <= right.length; j += 1) {+ previous[j] = current[j];+ }+ }++ return previous[right.length];+ }++ function resolveReplacementRange(+ currentText,+ start,+ end,+ expectedText,+ beforeContext,+ afterContext,+ ) {+ const normalizedStart = Math.max(0, Math.min(start, currentText.length));+ const normalizedEnd = Math.max(normalizedStart, Math.min(end, currentText.length));+ const directText = currentText.slice(normalizedStart, normalizedEnd);++ if (!expectedText || directText === expectedText) {+ return {+ start: normalizedStart,+ end: normalizedEnd,+ };+ }++ const spanLength = normalizedEnd - normalizedStart;++ for (let delta = -12; delta <= 12; delta += 1) {+ const candidateStart = normalizedStart + delta;+ if (candidateStart < 0) {continue;}- if (!(snap.node instanceof Element)) continue;- if (snap.node.scrollLeft !== snap.left) {- snap.node.scrollLeft = snap.left;++ const candidateEnd = candidateStart + spanLength;+ if (candidateEnd > currentText.length) {+ continue;}- if (snap.node.scrollTop !== snap.top) {- snap.node.scrollTop = snap.top;++ if (currentText.slice(candidateStart, candidateEnd) === expectedText) {+ return {+ start: candidateStart,+ end: candidateEnd,+ };}}- };-- /**- * @template T- * @param {() => T} fn- * @returns {T}- */- const withSuppressedScrolling = (fn) => {- /** @type {Array<() => void>} */- const restorers = [];- const noop = () => {};- const tryOverride = (obj, key) => {- if (!obj) return;- const original = obj[key];- if (typeof original !== 'function') return;- try {- obj[key] = noop;- restorers.push(() => {- try {- obj[key] = original;- } catch {}- });- } catch {}- };- tryOverride(window, 'scrollTo');- tryOverride(window, 'scrollBy');- tryOverride(Element.prototype, 'scrollIntoView');- tryOverride(Element.prototype, 'scrollTo');- tryOverride(Element.prototype, 'scrollBy');+ const beforeWindowLength = Math.max(beforeContext.length * 2, beforeContext.length + 64);+ const afterWindowLength = Math.max(afterContext.length * 2, afterContext.length + 64);+ const hits = [];+ let cursor = 0;- try {- return fn();- } finally {- for (let i = restorers.length - 1; i >= 0; i -= 1) {- restorers[i]();+ while (cursor <= currentText.length) {+ const index = currentText.indexOf(expectedText, cursor);+ if (index < 0) {+ break;}++ const indexEnd = index + expectedText.length;+ const candidateBefore = currentText.slice(Math.max(0, index - beforeWindowLength), index);+ const candidateAfter = currentText.slice(+ indexEnd,+ Math.min(currentText.length, indexEnd + afterWindowLength),+ );+ let score = 0;++ score += getLongestCommonSubsequenceLength(beforeContext, candidateBefore) * 8;+ score += getLongestCommonSubsequenceLength(afterContext, candidateAfter) * 8;+ score += getCommonPrefixLength(beforeContext, candidateBefore) * 4;+ score += getCommonSuffixLength(beforeContext, candidateBefore) * 4;+ score += getCommonPrefixLength(afterContext, candidateAfter) * 4;+ score += getCommonSuffixLength(afterContext, candidateAfter) * 4;+ score -= Math.abs(index - normalizedStart) / 1000;+ hits.push({ start: index, end: indexEnd, score });+ cursor = index + 1;}- };- /**- * @param {{ start?: number, end?: number }} request- * @returns {Promise<{ kind: 'getRects', rects: Rect[] }>}- */- const handleGetRectsRequest = async (request) => {- const start = Number(request.start);- const end = Number(request.end);- /** @type {AnnotatedText | undefined} */- const annotated = window.__harperGoogleDocsAnnotatedText;+ if (hits.length === 0) {+ return {+ start: normalizedStart,+ end: normalizedEnd,+ };+ }++ hits.sort((left, right) => right.score - left.score);+ return {+ start: hits[0].start,+ end: hits[0].end,+ };+ }++ async function handleGetRectsRequest(request) {+ const annotated = currentAnnotated;if (!annotated || typeof annotated.setSelection !== 'function') {return { kind: 'getRects', rects: [] };}- const currentSelection = annotated.getSelection?.()?.[0];- const previousSelection = getSelectionEndpoints(currentSelection);- if (!isSpanNearSelection(start, end, previousSelection)) {+ const rawText = annotated.getText?.() ?? '';+ const normalizedStart = Number(request.start);+ const normalizedEnd = Number(request.end);+ const rawStart = normalizedToRawOffset(rawText, normalizedStart);+ const rawEnd = normalizedToRawOffset(rawText, normalizedEnd);+ const currentSelection = getSelectionEndpoints(annotated.getSelection?.()?.[0]);+ const previousSelection = currentSelection+ ? {+ start: rawToNormalizedOffset(rawText, currentSelection.start),+ end: rawToNormalizedOffset(rawText, currentSelection.end),+ }+ : null;++ if (!isSpanNearSelection(normalizedStart, normalizedEnd, previousSelection)) {return { kind: 'getRects', rects: [] };}- /** @type {Rect[]} */- const rects = [];- isComputingRects = true;- const scrollSnapshot = snapshotScroll();+ const scrollSnapshots = snapshotScroll();try {- const spanStart = Math.max(0, Math.min(start, end));- const spanEnd = Math.max(spanStart, end);- const { startRect, endRect } = withSuppressedScrolling(() => {- return {- startRect: getCaretRect(annotated, spanStart),- endRect: getCaretRect(annotated, spanEnd),- };- });+ const spanStart = Math.max(0, Math.min(rawStart, rawEnd));+ const spanEnd = Math.max(spanStart, Math.max(rawStart, rawEnd));+ const { startRect, endRect } = withSuppressedScrolling(() => ({+ startRect: getCaretRect(annotated, spanStart),+ endRect: getCaretRect(annotated, spanEnd),+ }));++ /** @type {Rect[]} */+ const rects = [];if (startRect && endRect && Math.abs(startRect.y - endRect.y) < 6) {rects.push({@@ -423,120 +632,102 @@ import { GoogleDocsBridgeRequestHandler } from './google-docs-bridge-request-hanheight: startRect.height,});}++ return {+ kind: 'getRects',+ rects,+ };} finally {- isComputingRects = false;- restoreSelection(annotated, previousSelection);- restoreScroll(scrollSnapshot);- requestAnimationFrame(() => restoreScroll(scrollSnapshot));+ restoreSelection(annotated, currentSelection);+ restoreScroll(scrollSnapshots);+ requestAnimationFrame(() => restoreScroll(scrollSnapshots));}+ }- return { kind: 'getRects', rects };- };-- /**- * @param {{ start?: number, end?: number, replacementText?: string, expectedText?: string, beforeContext?: string, afterContext?: string }} request- * @returns {Promise<{ kind: 'replaceText', applied: boolean }>}- */- const handleReplaceTextRequest = async (request) => {- let start = Number(request.start);- let end = Number(request.end);- const replacementText = String(request.replacementText ?? '');- const expectedText = String(request.expectedText ?? '');- const beforeContext = String(request.beforeContext ?? '');- const afterContext = String(request.afterContext ?? '');- const getAnnotatedText = window._docs_annotate_getAnnotatedText;- if (typeof getAnnotatedText !== 'function') {+ async function handleReplaceTextRequest(request) {+ const getAnnotatedText = getAnnotatedTextApi();+ if (!getAnnotatedText) {return { kind: 'replaceText', applied: false };}- /** @type {AnnotatedText | null | undefined} */+const annotated = await getAnnotatedText();if (!annotated || typeof annotated.setSelection !== 'function') {return { kind: 'replaceText', applied: false };}- if (expectedText) {- const currentText = annotated.getText?.();- if (typeof currentText === 'string') {- const spanLength = Math.max(0, end - start);- const normalizeStart = Math.max(0, Math.min(start, currentText.length));- const normalizeEnd = Math.max(normalizeStart, Math.min(end, currentText.length));- const direct = currentText.slice(normalizeStart, normalizeEnd);- if (direct !== expectedText) {- const resolveByOffsetWindow = () => {- for (let delta = -12; delta <= 12; delta += 1) {- const candidateStart = normalizeStart + delta;- if (candidateStart < 0) continue;- const candidateEnd = candidateStart + spanLength;- if (candidateEnd > currentText.length) continue;- if (currentText.slice(candidateStart, candidateEnd) === expectedText) {- return { start: candidateStart, end: candidateEnd };- }- }- return null;- };-- const resolveByContext = () => {- const hits = [];- let cursor = 0;- while (cursor <= currentText.length) {- const index = currentText.indexOf(expectedText, cursor);- if (index < 0) break;- const indexEnd = index + expectedText.length;- const beforeTail = beforeContext ? beforeContext.slice(-16) : '';- const afterHead = afterContext ? afterContext.slice(0, 16) : '';- let score = 0;- if (- beforeTail &&- currentText.slice(Math.max(0, index - beforeTail.length), index) === beforeTail- ) {- score += 2;- }- if (- afterHead &&- currentText.slice(- indexEnd,- Math.min(currentText.length, indexEnd + afterHead.length),- ) === afterHead- ) {- score += 2;- }- score -= Math.abs(index - normalizeStart) / 1000;- hits.push({ start: index, end: indexEnd, score });- cursor = index + 1;- }-- if (hits.length === 0) return null;- hits.sort((a, b) => b.score - a.score);- return { start: hits[0].start, end: hits[0].end };- };-- const resolved = resolveByOffsetWindow() ?? resolveByContext();- if (resolved) {- start = resolved.start;- end = resolved.end;- }- }- }- }+ currentAnnotated = annotated;+ window.__harperGoogleDocsAnnotatedText = annotated;++ const replacementText = String(request.replacementText ?? '');+ const rawText = annotated.getText?.() ?? '';+ const currentText = normalizeGoogleDocsText(rawText);+ const resolvedRange = resolveReplacementRange(+ currentText,+ Number(request.start),+ Number(request.end),+ String(request.expectedText ?? ''),+ String(request.beforeContext ?? ''),+ String(request.afterContext ?? ''),+ );+ const rawStart = normalizedToRawOffset(rawText, resolvedRange.start);+ const rawEnd = normalizedToRawOffset(rawText, resolvedRange.end);++ annotated.setSelection(rawStart, rawEnd);- annotated.setSelection(start, end);const iframe = document.querySelector(TEXT_EVENT_IFRAME_SELECTOR);- const target = iframe?.contentDocument?.activeElement;+ const targetDocument = iframe?.contentDocument;+ const target = targetDocument?.activeElement;if (!target) {return { kind: 'replaceText', applied: false };}- const dt = new DataTransfer();- dt.setData('text/plain', replacementText);- const pasteEvent = new ClipboardEvent('paste', {- clipboardData: dt,- cancelable: true,- bubbles: true,- });- target.dispatchEvent(pasteEvent);- setTimeout(syncText, 0);- return { kind: 'replaceText', applied: true };- };+ target.focus?.();++ const expectedNextText =+ currentText.slice(0, resolvedRange.start) ++ replacementText ++ currentText.slice(resolvedRange.end);++ const didApplyReplacement = async () => {+ const nextAnnotated = await getAnnotatedText();+ return 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(+ new ClipboardEvent('paste', {+ clipboardData: dataTransfer,+ cancelable: true,+ bubbles: true,+ }),+ );++ await new Promise((resolve) => setTimeout(resolve, 0));+ const applied = await didApplyReplacement();+ if (applied) {+ queueMicrotask(() => {+ void syncText();+ });+ }++ return {+ kind: 'replaceText',+ applied,+ };+ }++ ensureBridgeNode();const requestHandler = new GoogleDocsBridgeRequestHandler({onGetRectsRequest: handleGetRectsRequest,@@ -544,55 +735,52 @@ import { GoogleDocsBridgeRequestHandler } from './google-docs-bridge-request-han});requestHandler.start();- // Legacy compatibility bridge while callers migrate to request/response protocol.document.addEventListener(EVENT_GET_RECTS, (event) => {- try {- const detail = /** @type {CustomEvent} */ (event).detail || {};- const requestId = String(detail.requestId || '');- if (!requestId) return;- void handleGetRectsRequest(detail).then((response) => {- ensureBridgeExists().setAttribute(- `data-harper-rects-${requestId}`,- JSON.stringify(response.rects),- );- });- } catch {}- });-- document.addEventListener(EVENT_REPLACE, (event) => {- try {- const detail = /** @type {CustomEvent} */ (event).detail || {};- void handleReplaceTextRequest(detail);- } catch {}- });-- window.addEventListener('resize', () => bumpLayoutEpoch('resize'));-- const observeLayout = () => {- const editor = document.querySelector(EDITOR_SELECTOR);- if (!(editor instanceof HTMLElement)) {- setTimeout(observeLayout, 250);+ const detail = /** @type {CustomEvent} */ (event).detail ?? {};+ const requestId = String(detail.requestId ?? '');+ if (!requestId) {return;}- bumpLayoutEpoch('init');- const observer = new MutationObserver((mutations) => {- for (const mutation of mutations) {- if (mutation.type === 'childList' || mutation.type === 'attributes') {- bumpLayoutEpoch('mutation');- break;- }- }- });- observer.observe(editor, {- subtree: true,- childList: true,- attributes: true,- attributeFilter: ['style', 'class'],+ void handleGetRectsRequest(detail).then((response) => {+ ensureBridgeNode().setAttribute(+ `data-harper-rects-${requestId}`,+ JSON.stringify(response.rects),+ );});- };+ });++ document.addEventListener(EVENT_REPLACE, (event) => {+ const detail = /** @type {CustomEvent} */ (event).detail ?? {};+ void handleReplaceTextRequest(detail);+ });- observeLayout();- syncText();- setInterval(syncText, SYNC_INTERVAL_MS);+ window.addEventListener(+ 'resize',+ () => {+ scheduleLayoutUpdate('resize');+ },+ { passive: true },+ );+ window.addEventListener(+ 'scroll',+ () => {+ scheduleLayoutUpdate('scroll');+ },+ { passive: true, capture: true },+ );+ document.addEventListener(+ 'wheel',+ () => {+ scheduleLayoutUpdate('wheel');+ },+ { passive: true, capture: true },+ );++ void syncText();+ bindLayoutObservers();+ window.setInterval(() => {+ void syncText();+ bindLayoutObservers();+ }, POLL_INTERVAL_MS);})();diff --git a/packages/chrome-plugin/src/contentScript/GoogleDocsBridgeClient.ts b/packages/chrome-plugin/src/contentScript/GoogleDocsBridgeClient.tsindex 2594317d9..d06e2869a 100644--- a/packages/chrome-plugin/src/contentScript/GoogleDocsBridgeClient.ts+++ b/packages/chrome-plugin/src/contentScript/GoogleDocsBridgeClient.ts@@ -1,72 +1,147 @@-// @ts-nocheck--import type {- GoogleDocsGetRectsResponse,- GoogleDocsNotificationMessage,- GoogleDocsRect,- GoogleDocsRequest,- GoogleDocsRequestMessage,- GoogleDocsResponse,- GoogleDocsResponseMessage,-} from '../../public/google-docs-protocol.js';+const PROTOCOL_VERSION = 'harper-gdocs-bridge/v1';+const EVENT_REQUEST = 'harper:gdocs:request';+const EVENT_RESPONSE = 'harper:gdocs:response';+const EVENT_NOTIFICATION = 'harper:gdocs:notification';++type GoogleDocsRect = {+ x: number;+ y: number;+ width: number;+ height: number;+};++type GoogleDocsRequest =+ | {+ kind: 'getRects';+ start: number;+ end: number;+ }+ | {+ kind: 'replaceText';+ start: number;+ end: number;+ replacementText: string;+ expectedText?: string;+ beforeContext?: string;+ afterContext?: string;+ };++type GoogleDocsGetRectsResponse = {+ kind: 'getRects';+ rects: GoogleDocsRect[];+};++type GoogleDocsResponse =+ | GoogleDocsGetRectsResponse+ | {+ kind: 'replaceText';+ applied: boolean;+ }+ | {+ kind: 'error';+ requestKind: GoogleDocsRequest['kind'];+ code: string;+ message: string;+ };++type GoogleDocsRequestMessage = {+ protocol: string;+ requestId: string;+ request: GoogleDocsRequest;+};++type GoogleDocsResponseMessage = {+ protocol: string;+ requestId: string;+ response: GoogleDocsResponse;+};++type GoogleDocsNotificationMessage = {+ protocol: string;+ notification:+ | {+ kind: 'textUpdated';+ length: number;+ }+ | {+ kind: 'layoutChanged';+ reason: string;+ layoutEpoch: number;+ };+};type PendingRequest = {resolve: (value: GoogleDocsResponse) => void;reject: (reason?: unknown) => void;- timerId: number;+ timeoutId: number;};-const PROTOCOL_VERSION = 'harper-gdocs-bridge/v1';-const EVENT_REQUEST = 'harper:gdocs:request';-const EVENT_RESPONSE = 'harper:gdocs:response';-const EVENT_NOTIFICATION = 'harper:gdocs:notification';+type BridgeNotificationListener = (message: GoogleDocsNotificationMessage['notification']) => void;++function isRecord(value: unknown): value is Record<string, unknown> {+ return value != null && typeof value === 'object';+}++function isResponseMessage(value: unknown): value is GoogleDocsResponseMessage {+ if (!isRecord(value) || value.protocol !== PROTOCOL_VERSION) {+ return false;+ }++ return (+ typeof value.requestId === 'string' &&+ isRecord(value.response) &&+ typeof value.response.kind === 'string'+ );+}++function isNotificationMessage(value: unknown): value is GoogleDocsNotificationMessage {+ if (!isRecord(value) || value.protocol !== PROTOCOL_VERSION) {+ return false;+ }++ return isRecord(value.notification) && typeof value.notification.kind === 'string';+}-/** Content-script client for Google Docs bridge request/response + notifications. */export default class GoogleDocsBridgeClient {private readonly documentRef: Document;- private readonly timeoutMs: number;+ private readonly requestTimeoutMs: number;private readonly pending = new Map<string, PendingRequest>();+ private readonly notificationListeners = new Set<BridgeNotificationListener>();private readonly onResponseBound: EventListener;private readonly onNotificationBound: EventListener;- private readonly textUpdatedListeners = new Set<(length: number) => void>();- private readonly layoutChangedListeners = new Set<- (reason: string, layoutEpoch: number) => void- >();-- public constructor(documentRef: Document = document, timeoutMs = 2000) {+ public constructor(documentRef: Document = document, requestTimeoutMs = 2000) {this.documentRef = documentRef;- this.timeoutMs = timeoutMs;+ this.requestTimeoutMs = requestTimeoutMs;this.onResponseBound = this.onResponse.bind(this);- this.onNotificationBound = this.onNotification.bind(this);+ this.onNotificationBound = this.handleNotificationEvent.bind(this);this.documentRef.addEventListener(EVENT_RESPONSE, this.onResponseBound);this.documentRef.addEventListener(EVENT_NOTIFICATION, this.onNotificationBound);}- /** Remove listeners and reject any pending bridge requests. */public dispose() {this.documentRef.removeEventListener(EVENT_RESPONSE, this.onResponseBound);this.documentRef.removeEventListener(EVENT_NOTIFICATION, this.onNotificationBound);- for (const [requestId, pending] of this.pending.entries()) {- clearTimeout(pending.timerId);- pending.reject(new Error(`Google Docs bridge request "${requestId}" was disposed`));++ for (const [requestId, request] of this.pending) {+ window.clearTimeout(request.timeoutId);+ request.reject(new Error(`Google Docs bridge request "${requestId}" was disposed`));}+this.pending.clear();- this.textUpdatedListeners.clear();- this.layoutChangedListeners.clear();+ this.notificationListeners.clear();}- /** Get on-screen rects for a text span in the Google Doc. */public async getRects(start: number, end: number): Promise<GoogleDocsRect[]> {const response = (await this.request({kind: 'getRects',start,end,})) as GoogleDocsGetRectsResponse;+return response.rects;}- /** Replace a text span in the Google Doc. Returns true if the edit was applied. */public async replaceText(start: number,end: number,@@ -84,110 +159,86 @@ export default class GoogleDocsBridgeClient {beforeContext,afterContext,});+return response.kind === 'replaceText' ? response.applied : false;}- /** Listen for bridge text updates. Returns an unsubscribe function. */- public onTextUpdated(cb: (length: number) => void): () => void {- this.textUpdatedListeners.add(cb);- return () => this.textUpdatedListeners.delete(cb);+ public onTextUpdated(listener: (length: number) => void): () => void {+ return this.addNotificationListener((notification) => {+ if (notification.kind === 'textUpdated') {+ listener(notification.length);+ }+ });+ }++ public onLayoutChanged(listener: (reason: string, layoutEpoch: number) => void): () => void {+ return this.addNotificationListener((notification) => {+ if (notification.kind === 'layoutChanged') {+ listener(notification.reason, notification.layoutEpoch);+ }+ });}- /** Listen for bridge layout changes. Returns an unsubscribe function. */- public onLayoutChanged(cb: (reason: string, layoutEpoch: number) => void): () => void {- this.layoutChangedListeners.add(cb);- return () => this.layoutChangedListeners.delete(cb);+ private addNotificationListener(listener: BridgeNotificationListener): () => void {+ this.notificationListeners.add(listener);+ return () => this.notificationListeners.delete(listener);}- /** Send one bridge request and wait for the response with the same request id. */private async request(request: GoogleDocsRequest): Promise<GoogleDocsResponse> {const requestId = this.createRequestId();- const message: GoogleDocsRequestMessage = {+ const requestMessage: GoogleDocsRequestMessage = {protocol: PROTOCOL_VERSION,requestId,request,};- return new Promise((resolve, reject) => {- const timerId = window.setTimeout(() => {+ return await new Promise<GoogleDocsResponse>((resolve, reject) => {+ const timeoutId = window.setTimeout(() => {this.pending.delete(requestId);reject(new Error(`Google Docs bridge request "${request.kind}" timed out`));- }, this.timeoutMs);+ }, this.requestTimeoutMs);- this.pending.set(requestId, { resolve, reject, timerId });- this.documentRef.dispatchEvent(new CustomEvent(EVENT_REQUEST, { detail: message }));+ this.pending.set(requestId, { resolve, reject, timeoutId });+ this.documentRef.dispatchEvent(new CustomEvent(EVENT_REQUEST, { detail: requestMessage }));});}- /** Route bridge responses to the matching pending request. */private onResponse(event: Event) {const detail = (event as CustomEvent).detail;- if (!this.isResponseMessage(detail)) {+ if (!isResponseMessage(detail)) {return;}- const pending = this.pending.get(detail.requestId);- if (!pending) {+ const pendingRequest = this.pending.get(detail.requestId);+ if (!pendingRequest) {return;}this.pending.delete(detail.requestId);- clearTimeout(pending.timerId);+ window.clearTimeout(pendingRequest.timeoutId);+if (detail.response.kind === 'error') {- pending.reject(new Error(detail.response.message || 'Google Docs bridge request failed'));+ pendingRequest.reject(+ new Error(detail.response.message || 'Google Docs bridge request failed'),+ );return;}- pending.resolve(detail.response);+ pendingRequest.resolve(detail.response);}- /** Route bridge notifications to local subscribers. */- private onNotification(event: Event) {+ private handleNotificationEvent(event: Event) {const detail = (event as CustomEvent).detail;- if (!this.isNotificationMessage(detail)) {+ if (!isNotificationMessage(detail)) {return;}- const { notification } = detail;- if (notification.kind === 'textUpdated') {- for (const listener of this.textUpdatedListeners) {- listener(notification.length);- }- return;- }-- if (notification.kind === 'layoutChanged') {- for (const listener of this.layoutChangedListeners) {- listener(notification.reason, notification.layoutEpoch);- }+ for (const listener of this.notificationListeners) {+ listener(detail.notification);}}- /** Create a request id for request/response matching. */private createRequestId(): string {return `gdocs-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;}-- private isResponseMessage(value: unknown): value is GoogleDocsResponseMessage {- if (!this.isObject(value)) return false;- return (- value.protocol === PROTOCOL_VERSION &&- typeof value.requestId === 'string' &&- this.isObject(value.response) &&- typeof value.response.kind === 'string'- );- }-- private isNotificationMessage(value: unknown): value is GoogleDocsNotificationMessage {- if (!this.isObject(value)) return false;- return (- value.protocol === PROTOCOL_VERSION &&- this.isObject(value.notification) &&- typeof value.notification.kind === 'string'- );- }-- private isObject(value: unknown): value is Record<string, any> {- return value != null && typeof value === 'object';- }}diff --git a/packages/chrome-plugin/src/contentScript/googleDocs.ts b/packages/chrome-plugin/src/contentScript/googleDocs.tsindex 9abc3868f..bb01753d0 100644--- a/packages/chrome-plugin/src/contentScript/googleDocs.ts+++ b/packages/chrome-plugin/src/contentScript/googleDocs.ts@@ -5,6 +5,7 @@ import {extendGoogleDocsLineBand,type GoogleDocsLineBand,type GoogleDocsRectLayout,+ getGoogleDocsParagraphBreakThreshold,rectSharesGoogleDocsLineBand,shouldInsertGoogleDocsSpace,} from './googleDocsLayout';@@ -15,19 +16,33 @@ declare global {}}-const GOOGLE_DOCS_BRIDGE_ID = 'harper-google-docs-target';+const GOOGLE_DOCS_TARGET_ID = 'harper-google-docs-target';const GOOGLE_DOCS_MAIN_WORLD_BRIDGE_ID = 'harper-google-docs-main-world-bridge';-const GOOGLE_DOCS_SCROLL_LAYOUT_REASONS = new Set(['scroll', 'wheel', 'key-scroll']);const GOOGLE_DOCS_EDITOR_SELECTOR = '.kix-appview-editor';-const GOOGLE_DOCS_SVG_RECT_SELECTOR = 'rect[aria-label]';-const GOOGLE_DOCS_TABLE_CELL_GAP_THRESHOLD_PX = 60;-const GOOGLE_DOCS_PARAGRAPH_BREAK_GAP_RATIO = 0.5;+const GOOGLE_DOCS_RECT_SELECTOR = 'rect[aria-label]';+const GOOGLE_DOCS_SYNCING_ATTR = 'data-harper-gdocs-syncing';+const GOOGLE_DOCS_IGNORED_LAYOUT_REASONS = new Set(['scroll', 'wheel', 'key-scroll']);const GOOGLE_DOCS_MIN_PARAGRAPH_BREAK_GAP_PX = 6;+const GOOGLE_DOCS_PARAGRAPH_BREAK_RATIO = 0.5;type LayoutRefreshFramework = LintFramework & {refreshLayout?: () => void;};+type GoogleDocsRectSegment = {+ rectNode: SVGRectElement;+ text: string;+ rect: GoogleDocsRectLayout;+};++type GoogleDocsCloneSnapshot = {+ fragment: DocumentFragment;+ text: string;+ source: 'logical' | 'rects';+ segmentCount: number;+ signature: string;+};+export function isGoogleDocsPage(): boolean {return (window.location.hostname === 'docs.google.com' &&@@ -35,320 +50,520 @@ export function isGoogleDocsPage(): boolean {);}-/**- * Creates a serialized sync function that keeps Harper's hidden lint target in step with- * Google Docs' rendered text layer.- *- * Why: Google Docs does not expose a stable, contenteditable DOM surface we can lint directly.- * We instead mirror its visual text rects into our own hidden bridge node, then point- * `LintFramework` at that node.- */export function createGoogleDocsBridgeSync(fw: LintFramework): () => Promise<void> {- let googleDocsSyncInFlight = false;- let googleDocsSyncPending = false;- let googleDocsBridgeAttached = false;- let googleDocsEventsBound = false;- let googleDocsCloneSignature = '';- let googleDocsBridgeClient: GoogleDocsBridgeClient | null = null;-- /**- * Ensures the hidden bridge element exists under the live editor container.- *- * Why: attaching to the editor keeps coordinate systems aligned so lint overlays map- * correctly to what the user sees.- */- function getGoogleDocsBridge(editor: HTMLElement): HTMLElement {- let bridge = document.getElementById(GOOGLE_DOCS_BRIDGE_ID);-- if (!bridge) {- bridge = document.createElement('div');- bridge.id = GOOGLE_DOCS_BRIDGE_ID;- bridge.setAttribute('data-harper-google-docs-target', 'true');- bridge.setAttribute('aria-hidden', 'true');- bridge.style.position = 'absolute';- bridge.style.top = '0';- bridge.style.left = '0';- bridge.style.width = '0';- bridge.style.height = '0';- bridge.style.overflow = 'visible';- bridge.style.pointerEvents = 'none';- bridge.style.opacity = '0';- bridge.style.zIndex = '-2147483648';- bridge.setAttribute('contenteditable', 'false');- bridge.setAttribute('data-language', 'plaintext');- editor.appendChild(bridge);+ let bridgeClient: GoogleDocsBridgeClient | null = null;+ let bridgeAttached = false;+ let syncInFlight = false;+ let syncPending = false;+ let syncingClearTimer: number | null = null;+ let lastCloneSignature = '';+ let injectedMainWorldBridge = false;++ function ensureTarget(editor: HTMLElement): HTMLElement {+ let target = document.getElementById(GOOGLE_DOCS_TARGET_ID);++ if (!(target instanceof HTMLElement)) {+ target = document.createElement('div');+ target.id = GOOGLE_DOCS_TARGET_ID;+ target.setAttribute('data-harper-google-docs-target', 'true');+ target.setAttribute('aria-hidden', 'true');+ target.setAttribute('contenteditable', 'false');+ target.setAttribute('data-language', 'plaintext');+ target.style.position = 'absolute';+ target.style.top = '0';+ target.style.left = '0';+ target.style.width = '0';+ target.style.height = '0';+ target.style.overflow = 'visible';+ target.style.pointerEvents = 'none';+ target.style.opacity = '0';+ target.style.zIndex = '-2147483648';+ editor.appendChild(target);}- if (bridge.parentElement !== editor) {- editor.appendChild(bridge);+ if (target.parentElement !== editor) {+ editor.appendChild(target);}- return bridge;+ return target;}- /**- * Injects the page-world bridge script once.- *- * Why: content scripts run in an isolated world and cannot directly access some- * Google Docs internals. The injected main-world bridge can, then communicates via DOM events.- */- function ensureGoogleDocsMainWorldBridge() {- if (document.getElementById(GOOGLE_DOCS_MAIN_WORLD_BRIDGE_ID)) {+ function ensureMainWorldBridge() {+ if (+ injectedMainWorldBridge ||+ document.getElementById(GOOGLE_DOCS_MAIN_WORLD_BRIDGE_ID) != null+ ) {+ injectedMainWorldBridge = true;return;}const script = document.createElement('script');script.type = 'module';script.src = chrome.runtime.getURL('google-docs-bridge.js');- (document.head || document.documentElement).appendChild(script);script.onload = () => script.remove();+ (document.head || document.documentElement).appendChild(script);+ injectedMainWorldBridge = true;}- /**- * Wires bridge events into framework refresh paths.- *- * Why: we react to push-style updates from Docs instead of polling heavily.- * Layout refreshes intentionally ignore pure scroll reasons to avoid expensive- * recalculations on high-frequency movement.- */- function bindGoogleDocsBridgeEvents(syncGoogleDocsBridge: () => Promise<void>) {- if (!isGoogleDocsPage() || googleDocsEventsBound) {+ function bindBridgeClient() {+ if (bridgeClient != null) {return;}- googleDocsEventsBound = true;- googleDocsBridgeClient = new GoogleDocsBridgeClient(document);- window.__harperGoogleDocsBridgeClient = googleDocsBridgeClient;- googleDocsBridgeClient.onTextUpdated(() => {+ bridgeClient = new GoogleDocsBridgeClient(document);+ window.__harperGoogleDocsBridgeClient = bridgeClient;++ bridgeClient.onTextUpdated(() => {void syncGoogleDocsBridge();});- googleDocsBridgeClient.onLayoutChanged((reason) => {- if (!GOOGLE_DOCS_SCROLL_LAYOUT_REASONS.has(String(reason))) {++ bridgeClient.onLayoutChanged((reason) => {+ if (!GOOGLE_DOCS_IGNORED_LAYOUT_REASONS.has(reason)) {(fw as LayoutRefreshFramework).refreshLayout?.();}});}- /**- * Normalizes Google Docs aria-label text into a whitespace shape closer to user-visible text.- *- * Why: Docs tokenization can collapse or split spaces around punctuation in ways that- * produce false positives/offset drift for lint spans.- */- function normalizeGoogleDocsLabel(label: string): string {- const tokens = label.split(' ');-- for (let i = 0; i < tokens.length; i += 1) {- const token = tokens[i];- if (token === '') {- tokens[i] = '\xa0';+ function disposeBridgeClient() {+ bridgeClient?.dispose();+ bridgeClient = null;+ delete window.__harperGoogleDocsBridgeClient;+ }++ function addSignatureToken(hash: number, token: string): number {+ let nextHash = hash;+ for (let index = 0; index < token.length; index += 1) {+ nextHash = (nextHash * 33 + token.charCodeAt(index)) >>> 0;+ }+ return nextHash;+ }++ function normalizeGoogleDocsRectLabel(label: string): string {+ const parts = label.split(' ');+ let normalized = '';++ for (let index = 0; index < parts.length; index += 1) {+ const part = parts[index];+ if (part === '') {+ normalized += '\u00a0';continue;}- const isLast = i === tokens.length - 1;- const lastChar = token.charAt(token.length - 1);- const nextFirstChar = tokens[i + 1]?.charAt(0) ?? '';- const keepTightTrailing = /[(["'“\-_`]/.test(lastChar);- const keepTightLeadingNext = /[)\]"'”\-_`]/.test(nextFirstChar);+ normalized += part;+ if (index === parts.length - 1) {+ continue;+ }++ const keepTightRight = /[(["'“‘/_`-]$/u.test(part);+ const keepTightLeft = /^[)\]"'”’/_`—–-]/u.test(parts[index + 1] ?? '');++ if (!keepTightRight && !keepTightLeft) {+ normalized += ' ';+ }+ }++ return normalized;+ }- tokens[i] = !isLast && !keepTightTrailing && !keepTightLeadingNext ? `${token} ` : token;+ function isStandaloneListMarker(text: string): boolean {+ return /^((\d+|[a-zA-Z]|[ivxlcdmIVXLCDM]+)[.)]|[-+*•◦▪‣●☐☑☒])$/u.test(text.trim());+ }++ function appendText(fragment: DocumentFragment, parts: string[], text: string) {+ if (text.length === 0) {+ return;}- return tokens.join('');+ parts.push(text);+ fragment.appendChild(document.createTextNode(text));}- /**- * Adds a token to a small rolling hash (djb2 variant).- *- * Why: fast change detection lets us skip expensive DOM replacement and framework updates- * when reconstructed clone output is effectively unchanged.- */- function addHashToken(hash: number, token: string): number {- let next = hash;- for (let i = 0; i < token.length; i += 1) {- next = (next * 33 + token.charCodeAt(i)) >>> 0;+ function createCloneSpan(segment: GoogleDocsRectSegment, text: string): HTMLSpanElement {+ const span = document.createElement('span');+ span.textContent = text;+ span.style.position = 'absolute';+ span.style.whiteSpace = 'pre';+ span.style.overflow = 'hidden';+ span.style.left = `${segment.rect.left}px`;+ span.style.top = `${segment.rect.top}px`;+ span.style.width = `${Math.max(1, segment.rect.width)}px`;+ span.style.height = `${Math.max(1, segment.rect.height)}px`;+ span.style.lineHeight = `${Math.max(1, segment.rect.height)}px`;++ const fontCss = segment.rectNode.getAttribute('data-font-css');+ if (fontCss) {+ span.style.font = fontCss;}- return next;++ return span;}- function isGoogleDocsStandaloneListMarker(label: string): boolean {- return /^(\d+\.|[-+*•◦▪‣])$/.test(label.trim());+ function canIgnoreLogicalGap(text: string): boolean {+ return /^\s*$/u.test(text);+ }++ function segmentsShareVisualLine(+ left: GoogleDocsRectSegment,+ right: GoogleDocsRectSegment,+ ): boolean {+ return (+ rectSharesGoogleDocsLineBand(left.rect, createGoogleDocsLineBand(right.rect)) ||+ rectSharesGoogleDocsLineBand(right.rect, createGoogleDocsLineBand(left.rect))+ );}- /**- * Rebuilds the hidden clone from Docs SVG text rects.- *- * How: each labeled rect becomes an absolutely-positioned span in the bridge.- * Why: this preserves enough geometry for highlight placement while giving Harper a- * stable text surface. The signature short-circuits no-op updates.- */- function rebuildGoogleDocsClone(editor: HTMLElement, clone: HTMLElement): { changed: boolean } {- const rectNodes = editor.querySelectorAll<SVGRectElement>(GOOGLE_DOCS_SVG_RECT_SELECTOR);+ function compareSegments(left: GoogleDocsRectSegment, right: GoogleDocsRectSegment): number {+ if (segmentsShareVisualLine(left, right)) {+ const horizontalDelta = left.rect.left - right.rect.left;+ if (Math.abs(horizontalDelta) > 1) {+ return horizontalDelta;+ }+ }++ const verticalDelta = left.rect.top - right.rect.top;+ if (Math.abs(verticalDelta) > 1) {+ return verticalDelta;+ }++ const horizontalDelta = left.rect.left - right.rect.left;+ if (Math.abs(horizontalDelta) > 1) {+ return horizontalDelta;+ }++ return 0;+ }++ function collectRectSegments(editor: HTMLElement): GoogleDocsRectSegment[] {const editorRect = editor.getBoundingClientRect();- const scrollTop = editor.scrollTop;- const scrollLeft = editor.scrollLeft;+ const segments: GoogleDocsRectSegment[] = [];++ for (const rectNode of Array.from(+ editor.querySelectorAll<SVGRectElement>(GOOGLE_DOCS_RECT_SELECTOR),+ )) {+ const rawLabel = rectNode.getAttribute('aria-label');+ if (!rawLabel) {+ continue;+ }++ const text = normalizeGoogleDocsRectLabel(rawLabel);+ if (text.length === 0) {+ continue;+ }++ const rect = rectNode.getBoundingClientRect();+ if (!Number.isFinite(rect.top) || rect.width <= 0 || rect.height <= 0) {+ continue;+ }++ const top = rect.top - editorRect.top + editor.scrollTop;+ const left = rect.left - editorRect.left + editor.scrollLeft;+ if (!Number.isFinite(top) || !Number.isFinite(left)) {+ continue;+ }++ segments.push({+ rectNode,+ text,+ rect: {+ top,+ left,+ width: rect.width,+ height: rect.height,+ },+ });+ }++ segments.sort(compareSegments);+ return segments;+ }++ function shouldRepairCollapsedGap(+ skippedText: string,+ previousText: string,+ nextText: string,+ sharesVisualLine: boolean,+ ): boolean {+ return (+ skippedText.length === 0 &&+ !sharesVisualLine &&+ /[\p{L}\p{N}]$/u.test(previousText) &&+ /^[\p{L}\p{N}]/u.test(nextText)+ );+ }++ function normalizeLogicalGap(+ skippedText: string,+ previousText: string,+ nextText: string,+ sharesVisualLine: boolean,+ currentRect: GoogleDocsRectLayout,+ nextRect: GoogleDocsRectLayout | null,+ ): string {+ if (shouldRepairCollapsedGap(skippedText, previousText, nextText, sharesVisualLine)) {+ return ' ';+ }++ if (!skippedText.includes('\n')) {+ return skippedText;+ }++ const startsNewTableColumn =+ nextRect != null &&+ rectSharesGoogleDocsLineBand(currentRect, createGoogleDocsLineBand(nextRect)) &&+ nextRect.left - currentRect.left > currentRect.width + 120;++ if (sharesVisualLine || startsNewTableColumn) {+ return skippedText.replace(/\n+/gu, '\n');+ }++ const shouldKeepParagraphBreak =+ !isStandaloneListMarker(previousText) && !isStandaloneListMarker(nextText);++ return skippedText.replace(/\n+/gu, shouldKeepParagraphBreak ? '\n\n' : '\n');+ }++ function shouldInsertSoftWrapSpace(+ previousText: string,+ nextText: string,+ lineGap: number,+ paragraphBreakThreshold: number,+ ): boolean {+ return (+ lineGap < paragraphBreakThreshold &&+ /[\p{L}\p{N}]$/u.test(previousText) &&+ /^[\p{Ll}\p{N}]/u.test(nextText)+ );+ }++ function computeSignature(+ source: GoogleDocsCloneSnapshot['source'],+ text: string,+ segments: GoogleDocsRectSegment[],+ editor: HTMLElement,+ ): string {+ let hash = 5381;+ hash = addSignatureToken(hash, source);+ hash = addSignatureToken(hash, text);+ hash = addSignatureToken(hash, `${editor.scrollTop}:${editor.scrollLeft}:${segments.length}`);++ for (const segment of segments) {+ hash = addSignatureToken(+ hash,+ `${Math.round(segment.rect.top)}:${Math.round(segment.rect.left)}:${Math.round(segment.rect.width)}:${Math.round(segment.rect.height)}:${segment.text}`,+ );+ }++ return String(hash);+ }++ function buildLogicalSnapshot(+ editor: HTMLElement,+ segments: GoogleDocsRectSegment[],+ logicalText: string,+ ): GoogleDocsCloneSnapshot | null {+ if (logicalText.length === 0 || segments.length === 0) {+ return null;+ }+const fragment = document.createDocumentFragment();const parts: string[] = [];- let nextHash = 5381;+ let cursor = 0;+ let previousText = '';let currentLineBand: GoogleDocsLineBand | null = null;- let lastLayoutRect: GoogleDocsRectLayout | null = null;- let lastLabel = '';- let lastRight: number | null = null;- let segmentCount = 0;- for (const rectNode of Array.from(rectNodes)) {- const areaLabel = rectNode.getAttribute('aria-label');- if (!areaLabel) continue;+ for (let index = 0; index < segments.length; index += 1) {+ const segment = segments[index];+ const startAtCursor = logicalText.startsWith(segment.text, cursor)+ ? cursor+ : logicalText.indexOf(segment.text, cursor);- const normalizedLabel = normalizeGoogleDocsLabel(areaLabel);- if (!normalizedLabel) continue;+ if (startAtCursor < 0) {+ return null;+ }- const rect = rectNode.getBoundingClientRect();- if (!Number.isFinite(rect.top) || rect.width <= 0 || rect.height <= 0) continue;-- const top = rect.top - editorRect.top + scrollTop;- const left = rect.left - editorRect.left + scrollLeft;- const right = left + rect.width;- if (!Number.isFinite(top)) continue;- if (!Number.isFinite(left)) continue;- if (!Number.isFinite(right)) continue;-- const layoutRect: GoogleDocsRectLayout = {- top,- left,- width: rect.width,- height: rect.height,- };- const sharesVisualLine =- currentLineBand != null && rectSharesGoogleDocsLineBand(layoutRect, currentLineBand);- const shouldInsertLineBreak =- (currentLineBand != null && !sharesVisualLine) ||- (sharesVisualLine &&- !isGoogleDocsStandaloneListMarker(lastLabel) &&- lastRight != null &&- left - lastRight >= GOOGLE_DOCS_TABLE_CELL_GAP_THRESHOLD_PX);-- if (shouldInsertLineBreak && parts.length > 0 && !parts[parts.length - 1].endsWith('\n')) {- const lineGap =- currentLineBand == null ? 0 : Math.max(0, layoutRect.top - currentLineBand.bottom);+ const skippedText = logicalText.slice(cursor, startAtCursor);+ if (!canIgnoreLogicalGap(skippedText)) {+ return null;+ }++ const sharesVisualLine: boolean =+ currentLineBand != null && rectSharesGoogleDocsLineBand(segment.rect, currentLineBand);+ const normalizedGap = normalizeLogicalGap(+ skippedText,+ previousText,+ segment.text,+ sharesVisualLine,+ segment.rect,+ segments[index + 1]?.rect ?? null,+ );+ appendText(fragment, parts, normalizedGap);++ fragment.appendChild(createCloneSpan(segment, segment.text));+ parts.push(segment.text);+ cursor = startAtCursor + segment.text.length;+ previousText = segment.text;+ currentLineBand =+ currentLineBand == null || !sharesVisualLine+ ? createGoogleDocsLineBand(segment.rect)+ : extendGoogleDocsLineBand(currentLineBand, segment.rect);+ }++ const trailingText = logicalText.slice(cursor);+ if (!canIgnoreLogicalGap(trailingText)) {+ return null;+ }++ appendText(fragment, parts, trailingText);+ const text = parts.join('');++ return {+ fragment,+ text,+ source: 'logical',+ segmentCount: segments.length,+ signature: computeSignature('logical', text, segments, editor),+ };+ }++ function buildRectSnapshot(+ editor: HTMLElement,+ segments: GoogleDocsRectSegment[],+ ): GoogleDocsCloneSnapshot {+ const fragment = document.createDocumentFragment();+ const parts: string[] = [];+ let previousText = '';+ let previousRect: GoogleDocsRectLayout | null = null;+ let currentLineBand: GoogleDocsLineBand | null = null;++ for (const segment of segments) {+ const sharesVisualLine: boolean =+ currentLineBand != null && rectSharesGoogleDocsLineBand(segment.rect, currentLineBand);+ const startsNewLine: boolean = currentLineBand != null && !sharesVisualLine;++ if (startsNewLine && currentLineBand != null) {+ const lineGap = Math.max(0, segment.rect.top - currentLineBand.bottom);const paragraphBreakThreshold = Math.max(GOOGLE_DOCS_MIN_PARAGRAPH_BREAK_GAP_PX,- Math.min(currentLineBand?.bottom - currentLineBand?.top || 0, layoutRect.height) *- GOOGLE_DOCS_PARAGRAPH_BREAK_GAP_RATIO,+ getGoogleDocsParagraphBreakThreshold(currentLineBand, segment.rect),+ Math.min(currentLineBand.height, segment.rect.height) * GOOGLE_DOCS_PARAGRAPH_BREAK_RATIO,);- const breakText = !sharesVisualLine && lineGap >= paragraphBreakThreshold ? '\n\n' : '\n';- parts.push(breakText);- fragment.appendChild(document.createTextNode(breakText));- }- if (- !shouldInsertLineBreak &&- lastLayoutRect != null &&- (isGoogleDocsStandaloneListMarker(lastLabel) ||- shouldInsertGoogleDocsSpace(lastLayoutRect, layoutRect, lastLabel, normalizedLabel))+ const breakText = shouldInsertSoftWrapSpace(+ previousText,+ segment.text,+ lineGap,+ paragraphBreakThreshold,+ )+ ? ' '+ : lineGap >= paragraphBreakThreshold+ ? '\n\n'+ : '\n';+ appendText(fragment, parts, breakText);+ } else if (+ previousRect != null &&+ (isStandaloneListMarker(previousText) ||+ shouldInsertGoogleDocsSpace(previousRect, segment.rect, previousText, segment.text))) {- parts.push(' ');- fragment.appendChild(document.createTextNode(' '));+ appendText(fragment, parts, ' ');}- const span = document.createElement('span');- span.textContent = normalizedLabel;- span.style.position = 'absolute';- span.style.whiteSpace = 'pre';- span.style.overflow = 'hidden';- span.style.left = `${left}px`;- span.style.top = `${top}px`;- span.style.width = `${Math.max(rect.width, 1)}px`;- span.style.height = `${Math.max(rect.height, 1)}px`;- span.style.lineHeight = `${Math.max(rect.height, 1)}px`;- const fontCss = rectNode.getAttribute('data-font-css');- if (fontCss) {- span.style.font = fontCss;- }- fragment.appendChild(span);-- parts.push(normalizedLabel);+ fragment.appendChild(createCloneSpan(segment, segment.text));+ parts.push(segment.text);+ previousText = segment.text;+ previousRect = segment.rect;currentLineBand =- currentLineBand == null || shouldInsertLineBreak- ? createGoogleDocsLineBand(layoutRect)- : extendGoogleDocsLineBand(currentLineBand, layoutRect);- lastLayoutRect = layoutRect;- lastLabel = normalizedLabel;- lastRight = right;- segmentCount += 1;-- nextHash = addHashToken(nextHash, normalizedLabel);- nextHash = addHashToken(- nextHash,- `${Math.round(top)}:${Math.round(left)}:${Math.round(rect.width)}`,- );+ currentLineBand == null || startsNewLine+ ? createGoogleDocsLineBand(segment.rect)+ : extendGoogleDocsLineBand(currentLineBand, segment.rect);}- const nextText = parts.join('');- nextHash = addHashToken(- nextHash,- `${nextText.length}:${segmentCount}:${Math.round(scrollTop)}`,+ const text = parts.join('');++ return {+ fragment,+ text,+ source: 'rects',+ segmentCount: segments.length,+ signature: computeSignature('rects', text, segments, editor),+ };+ }++ function buildSnapshot(editor: HTMLElement): GoogleDocsCloneSnapshot {+ const segments = collectRectSegments(editor);+ const logicalText =+ document+ .getElementById(GOOGLE_DOCS_MAIN_WORLD_BRIDGE_ID)+ ?.textContent?.replace(/\r\n?/gu, '\n') ?? '';++ return (+ buildLogicalSnapshot(editor, segments, logicalText) ?? buildRectSnapshot(editor, segments));- const nextSignature = String(nextHash);- if (nextSignature === googleDocsCloneSignature && clone.textContent === nextText) {- return { changed: false };+ }++ function applySnapshot(target: HTMLElement, snapshot: GoogleDocsCloneSnapshot): boolean {+ if (snapshot.signature === lastCloneSignature && target.textContent === snapshot.text) {+ return false;}- clone.replaceChildren(fragment);- clone.setAttribute('data-harper-gdocs-segments', String(segmentCount));- googleDocsCloneSignature = nextSignature;- return { changed: true };+ target.replaceChildren(snapshot.fragment);+ target.setAttribute('data-harper-gdocs-source', snapshot.source);+ target.setAttribute('data-harper-gdocs-segments', String(snapshot.segmentCount));+ lastCloneSignature = snapshot.signature;+ return true;}- /**- * Performs one sync pass, with in-flight serialization and a pending replay.- *- * Why: Docs can fire bursts of changes; serialization prevents overlapping `fw.update()`- * work and ensures we process at least one follow-up pass after a busy interval.- */async function syncGoogleDocsBridge() {if (!isGoogleDocsPage()) {- if (googleDocsBridgeClient) {- googleDocsBridgeClient.dispose();- googleDocsBridgeClient = null;- }- delete window.__harperGoogleDocsBridgeClient;- googleDocsEventsBound = false;+ disposeBridgeClient();+ bridgeAttached = false;return;}- if (googleDocsSyncInFlight) {- googleDocsSyncPending = true;+ if (syncInFlight) {+ syncPending = true;return;}- googleDocsSyncInFlight = true;+ syncInFlight = true;try {- ensureGoogleDocsMainWorldBridge();- bindGoogleDocsBridgeEvents(syncGoogleDocsBridge);+ ensureMainWorldBridge();+ bindBridgeClient();const editor = document.querySelector(GOOGLE_DOCS_EDITOR_SELECTOR);if (!(editor instanceof HTMLElement)) {return;}- const target = getGoogleDocsBridge(editor);- const { changed } = rebuildGoogleDocsClone(editor, target);- if (!googleDocsBridgeAttached) {+ 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));+ if (!bridgeAttached) {await fw.addTarget(target);- googleDocsBridgeAttached = true;+ bridgeAttached = true;}if (changed) {await fw.update();}- } catch (err) {- console.error('Failed to sync Google Docs bridge text', err);+ } catch (error) {+ console.error('Failed to sync Google Docs bridge text', error);} finally {- googleDocsSyncInFlight = false;+ const editor = document.querySelector(GOOGLE_DOCS_EDITOR_SELECTOR);+ if (editor instanceof HTMLElement) {+ syncingClearTimer = window.setTimeout(() => {+ editor.removeAttribute(GOOGLE_DOCS_SYNCING_ATTR);+ syncingClearTimer = null;+ }, 150);+ }- if (googleDocsSyncPending) {- googleDocsSyncPending = false;+ syncInFlight = false;+ if (syncPending) {+ syncPending = false;void syncGoogleDocsBridge();}}diff --git a/packages/chrome-plugin/src/contentScript/googleDocsLayout.ts b/packages/chrome-plugin/src/contentScript/googleDocsLayout.tsindex c30a1464f..97afa21e3 100644--- a/packages/chrome-plugin/src/contentScript/googleDocsLayout.ts+++ b/packages/chrome-plugin/src/contentScript/googleDocsLayout.ts@@ -8,16 +8,22 @@ export type GoogleDocsRectLayout = {export type GoogleDocsLineBand = {top: number;bottom: number;+ height: number;};-const GOOGLE_DOCS_LINE_OVERLAP_TOLERANCE_PX = 1;-const GOOGLE_DOCS_SPACE_GAP_RATIO = 0.2;-const GOOGLE_DOCS_MIN_SPACE_GAP_PX = 3;+const LINE_OVERLAP_RATIO = 0.45;+const MIN_LINE_OVERLAP_PX = 1;+const LINE_CENTER_DISTANCE_RATIO = 0.75;+const SPACE_GAP_RATIO = 0.2;+const MIN_SPACE_GAP_PX = 3;+const TIGHT_LEFT_PUNCTUATION = /^[,./:;!?%)\]}"'”’—–-]/u;+const TIGHT_RIGHT_PUNCTUATION = /[([{"'“‘/_—–-]$/u;export function createGoogleDocsLineBand(rect: GoogleDocsRectLayout): GoogleDocsLineBand {return {top: rect.top,bottom: rect.top + rect.height,+ height: rect.height,};}@@ -25,9 +31,13 @@ export function extendGoogleDocsLineBand(lineBand: GoogleDocsLineBand,rect: GoogleDocsRectLayout,): GoogleDocsLineBand {+ const top = Math.min(lineBand.top, rect.top);+ const bottom = Math.max(lineBand.bottom, rect.top + rect.height);+return {- top: Math.min(lineBand.top, rect.top),- bottom: Math.max(lineBand.bottom, rect.top + rect.height),+ top,+ bottom,+ height: bottom - top,};}@@ -36,11 +46,23 @@ export function rectSharesGoogleDocsLineBand(lineBand: GoogleDocsLineBand,): boolean {const rectBottom = rect.top + rect.height;-- return (- rect.top <= lineBand.bottom + GOOGLE_DOCS_LINE_OVERLAP_TOLERANCE_PX &&- rectBottom >= lineBand.top - GOOGLE_DOCS_LINE_OVERLAP_TOLERANCE_PX+ const overlap = Math.min(rectBottom, lineBand.bottom) - Math.max(rect.top, lineBand.top);+ const overlapThreshold = Math.max(+ MIN_LINE_OVERLAP_PX,+ Math.min(rect.height, lineBand.height) * LINE_OVERLAP_RATIO,);+ const rectCenter = rect.top + rect.height / 2;+ const lineCenter = lineBand.top + lineBand.height / 2;+ const lineCenterThreshold = Math.max(rect.height, lineBand.height) * LINE_CENTER_DISTANCE_RATIO;++ return overlap >= overlapThreshold || Math.abs(rectCenter - lineCenter) <= lineCenterThreshold;+}++export function getGoogleDocsParagraphBreakThreshold(+ lineBand: GoogleDocsLineBand,+ nextRect: GoogleDocsRectLayout,+): number {+ return Math.max(MIN_SPACE_GAP_PX * 2, Math.min(lineBand.height, nextRect.height) * 0.5);}export function shouldInsertGoogleDocsSpace(@@ -49,23 +71,23 @@ export function shouldInsertGoogleDocsSpace(previousText: string,currentText: string,): boolean {- if (previousText.length === 0 || currentText.length === 0) {+ if (!previousText || !currentText) {return false;}- if (/\s$/.test(previousText) || /^\s/.test(currentText)) {+ if (/\s$/u.test(previousText) || /^\s/u.test(currentText)) {return false;}- if (/[([{"'“‘-]$/.test(previousText) || /^[,.;:!?)\]}"'”’]/.test(currentText)) {+ if (TIGHT_RIGHT_PUNCTUATION.test(previousText) || TIGHT_LEFT_PUNCTUATION.test(currentText)) {return false;}- const gap = currentRect.left - (previousRect.left + previousRect.width);- const threshold = Math.max(- GOOGLE_DOCS_MIN_SPACE_GAP_PX,- Math.min(previousRect.height, currentRect.height) * GOOGLE_DOCS_SPACE_GAP_RATIO,+ const horizontalGap = currentRect.left - (previousRect.left + previousRect.width);+ const gapThreshold = Math.max(+ MIN_SPACE_GAP_PX,+ Math.min(previousRect.height, currentRect.height) * SPACE_GAP_RATIO,);- return gap >= threshold;+ return horizontalGap >= gapThreshold;}diff --git a/packages/chrome-plugin/tests/googleDocsTestUtils.ts b/packages/chrome-plugin/tests/googleDocsTestUtils.tsnew file mode 100644index 000000000..83e3c6b90--- /dev/null+++ b/packages/chrome-plugin/tests/googleDocsTestUtils.ts@@ -0,0 +1,417 @@+import type { Page } from '@playwright/test';+import { expect } from './fixtures';++export const LIVE_GOOGLE_DOCS_URL = 'CHANGE_ME';++const GOOGLE_DOCS_RESET_SENTINEL = 'Harper reset sentinel';++type GoogleDocsRenderedState = {+ annotatedText: string;+ bridgeText: string;+ rectFonts: string[];+ rectLabels: string[];+ highlightCount: number;+ lineCount: number;+};++function normalizeWhitespace(text: string): string {+ return text.replaceAll('\u00a0', ' ').replace(/\s+/g, ' ').trim();+}++function normalizeAnnotatedText(text: string): string {+ return (text.startsWith('\u0003') ? text.slice(1) : text).replace(/\n$/, '');+}++export function normalizeGoogleDocsBridgeText(text: string): string {+ return text.replaceAll('\u00a0', ' ').trimEnd();+}++export async function openLiveGoogleDoc(page: Page) {+ await page.goto(LIVE_GOOGLE_DOCS_URL, {+ waitUntil: 'domcontentloaded',+ timeout: 120000,+ });++ await page.locator('#docs-editor').waitFor({ state: 'visible', timeout: 60000 });++ await expect+ .poll(+ async () => {+ return await page.evaluate(async () => {+ if (typeof window._docs_annotate_getAnnotatedText !== 'function') {+ return false;+ }++ try {+ const annotated = await window._docs_annotate_getAnnotatedText();+ return Boolean(+ annotated?.getText &&+ document.querySelector('#harper-google-docs-target') &&+ document.querySelector('#harper-google-docs-main-world-bridge'),+ );+ } catch {+ return false;+ }+ });+ },+ { timeout: 60000 },+ )+ .toBe(true);+}++export async function focusGoogleDocsEditor(page: Page) {+ await page.locator('#docs-editor').click({+ position: { x: 260, y: 180 },+ timeout: 30000,+ });+ await page.waitForTimeout(750);+}++export async function setGoogleDocsFontSize(page: Page, fontSizePoints: number) {+ await page.keyboard.press('Escape');+ await page.waitForTimeout(200);++ const fontSizeInput = page.locator('input[aria-label="Font size"]').first();+ await expect(fontSizeInput).toBeVisible({ timeout: 10000 });+ await fontSizeInput.click({ clickCount: 3 });+ await page.waitForTimeout(150);+ await fontSizeInput.fill(String(fontSizePoints));+ await fontSizeInput.press('Enter');+ await page.waitForTimeout(750);++ await focusGoogleDocsEditor(page);+}++export async function moveGoogleDocsCursorToEnd(page: Page) {+ await page.evaluate(async () => {+ const annotated = await window._docs_annotate_getAnnotatedText?.();+ const source = annotated?.getText?.() ?? '';+ annotated?.setSelection?.(source.length, source.length);+ });+ await page.waitForTimeout(500);+}++async function getGoogleDocsRenderedState(page: Page): Promise<GoogleDocsRenderedState> {+ return await page.evaluate(async () => {+ const annotated = await window._docs_annotate_getAnnotatedText();+ const rects = Array.from(+ document.querySelectorAll<SVGRectElement>('.kix-appview-editor rect[aria-label]'),+ );+ const lineTops = new Set(+ rects+ .map((rect) => Math.round(rect.getBoundingClientRect().top))+ .filter((top) => Number.isFinite(top)),+ );++ return {+ annotatedText: annotated.getText(),+ bridgeText: document.querySelector('#harper-google-docs-target')?.textContent ?? '',+ rectFonts: rects.map((rect) => rect.getAttribute('data-font-css') ?? ''),+ rectLabels: rects.map((rect) => rect.getAttribute('aria-label') ?? ''),+ highlightCount: document.querySelectorAll('#harper-highlight').length,+ lineCount: lineTops.size,+ };+ });+}++export async function getGoogleDocsAnnotatedText(page: Page): Promise<string> {+ const state = await getGoogleDocsRenderedState(page);+ return normalizeAnnotatedText(state.annotatedText);+}++export async function getGoogleDocsBridgeText(page: Page): Promise<string> {+ const state = await getGoogleDocsRenderedState(page);+ return normalizeGoogleDocsBridgeText(state.bridgeText);+}++export async function getGoogleDocsNormalizedBridgeText(page: Page): Promise<string> {+ return normalizeWhitespace(await getGoogleDocsBridgeText(page));+}++export async function getGoogleDocsHighlightCount(page: Page): Promise<number> {+ const state = await getGoogleDocsRenderedState(page);+ return state.highlightCount;+}++export async function getGoogleDocsVisualLineCount(page: Page): Promise<number> {+ const state = await getGoogleDocsRenderedState(page);+ return state.lineCount;+}++async function clearGoogleDocsDocument(page: Page) {+ await focusGoogleDocsEditor(page);+ await page.keyboard.press('Escape');+ await page.waitForTimeout(200);+ await page.evaluate(async () => {+ const annotated = await window._docs_annotate_getAnnotatedText?.();+ const source = annotated?.getText?.() ?? '';+ annotated?.setSelection?.(0, source.length);+ });+ await page.waitForTimeout(300);+ await page.keyboard.press('Control+A');+ await page.waitForTimeout(200);+ await page.keyboard.press('Control+A');+ await page.waitForTimeout(300);+ await page.keyboard.press('Backspace');+ await page.waitForTimeout(1000);+}++async function clearGoogleDocsDocumentCompletely(page: Page) {+ for (let attempt = 0; attempt < 3; attempt += 1) {+ await clearGoogleDocsDocument(page);++ try {+ await expect.poll(() => getGoogleDocsAnnotatedText(page), { timeout: 10000 }).toBe('');+ return;+ } catch {+ await focusGoogleDocsEditor(page);+ await page.keyboard.press('Escape');+ await page.waitForTimeout(200);+ await page.evaluate(async () => {+ const annotated = await window._docs_annotate_getAnnotatedText?.();+ const source = annotated?.getText?.() ?? '';+ annotated?.setSelection?.(0, source.length);+ });+ await page.waitForTimeout(300);+ await page.keyboard.press('Control+A');+ await page.waitForTimeout(200);+ await page.keyboard.press('Control+A');+ await page.waitForTimeout(300);+ await page.keyboard.press('Delete');+ await page.waitForTimeout(1000);+ }+ }++ throw new Error('Failed to clear the Google Docs document');+}++async function typeGoogleDocsText(page: Page, text: string) {+ const lines = text.split('\n');++ for (let i = 0; i < lines.length; i += 1) {+ if (lines[i].length > 0) {+ await page.keyboard.type(lines[i], { delay: 20 });+ }++ if (i < lines.length - 1) {+ await page.keyboard.press('Enter');+ await page.waitForTimeout(150);+ }+ }++ await page.waitForTimeout(1500);+}++async function openGoogleDocsInsertTablePicker(page: Page) {+ await page.getByRole('menuitem', { name: 'Insert' }).click();+ await page.waitForTimeout(300);+ await page.locator('.goog-menuitem').filter({ hasText: 'Table' }).first().hover();+ await page.waitForTimeout(500);+}++export async function insertGoogleDocsTable(page: Page, rows: number, columns: number) {+ if (rows < 1 || columns < 1) {+ throw new Error('Google Docs tables must have at least one row and one column');+ }++ await focusGoogleDocsEditor(page);+ await openGoogleDocsInsertTablePicker(page);++ const grid = page.locator('.goog-dimension-picker-unhighlighted');+ await expect(grid).toBeVisible({ timeout: 10000 });+ const gridBox = await grid.boundingBox();+ if (!gridBox) {+ throw new Error('Could not find the Google Docs table picker grid');+ }++ const cellSize = gridBox.width / 11;+ const targetX = gridBox.x + (columns - 0.5) * cellSize;+ const targetY = gridBox.y + (rows - 0.5) * cellSize;++ await page.mouse.move(targetX, targetY);+ await page.waitForTimeout(300);+ await page.mouse.click(targetX, targetY);+ await page.waitForTimeout(1000);+}++export async function typeGoogleDocsTableCells(page: Page, rows: string[][]) {+ const columnCount = rows[0]?.length ?? 0;+ if (columnCount === 0 || rows.some((row) => row.length !== columnCount)) {+ throw new Error('Google Docs table rows must all have the same number of cells');+ }++ const cells = rows.flat();+ for (let cellIndex = 0; cellIndex < cells.length; cellIndex += 1) {+ if (cells[cellIndex].length > 0) {+ await page.keyboard.type(cells[cellIndex], { delay: 20 });+ }++ if (cellIndex < cells.length - 1) {+ await page.keyboard.press('Tab');+ await page.waitForTimeout(250);+ }+ }++ await page.waitForTimeout(1500);+}++export async function appendGoogleDocsTable(page: Page, rows: string[][]) {+ if (rows.length === 0) {+ throw new Error('Google Docs tables must include at least one row');+ }++ await moveGoogleDocsCursorToEnd(page);+ await focusGoogleDocsEditor(page);+ await page.keyboard.press('Enter');+ await page.waitForTimeout(500);+ await insertGoogleDocsTable(page, rows.length, rows[0].length);+ await typeGoogleDocsTableCells(page, rows);+}++async function ensurePlainGoogleDocsInsertionMode(page: Page) {+ for (let attempt = 0; attempt < 3; attempt += 1) {+ await clearGoogleDocsDocument(page);+ await typeGoogleDocsText(page, GOOGLE_DOCS_RESET_SENTINEL);++ try {+ await expect+ .poll(() => getGoogleDocsNormalizedBridgeText(page), { timeout: 15000 })+ .toContain(GOOGLE_DOCS_RESET_SENTINEL);+ } catch {+ continue;+ }++ const state = await getGoogleDocsRenderedState(page);+ const bridgeText = normalizeGoogleDocsBridgeText(state.bridgeText);+ const hasListMarker = /^([●•◦▪‣]|\d+\.)\s/.test(bridgeText);+ const hasUnexpectedFont = state.rectFonts.some((font) => /italic|bold/.test(font));++ if (!hasListMarker && !hasUnexpectedFont) {+ return;+ }++ await focusGoogleDocsEditor(page);+ await page.keyboard.press('Control+A');+ await page.waitForTimeout(300);++ if (hasListMarker) {+ await page.keyboard.press('Control+Shift+8');+ await page.waitForTimeout(1000);+ }++ if (hasUnexpectedFont) {+ await page.keyboard.press('Control+\\\\');+ await page.waitForTimeout(1000);+ }+ }++ throw new Error('Failed to reset Google Docs formatting state');+}++export async function replaceGoogleDocsDocumentText(page: Page, text: string) {+ await ensurePlainGoogleDocsInsertionMode(page);+ await clearGoogleDocsDocumentCompletely(page);++ if (text.length > 0) {+ await typeGoogleDocsText(page, text);+ }++ await expect.poll(() => getGoogleDocsAnnotatedText(page), { timeout: 20000 }).toBe(text);+}++async function selectGoogleDocsRange(page: Page, start: number, end: number) {+ await page.evaluate(+ async ({ selectionStart, selectionEnd }) => {+ const annotated = await window._docs_annotate_getAnnotatedText();+ annotated.setSelection(selectionStart, selectionEnd);+ },+ {+ selectionStart: start,+ selectionEnd: end,+ },+ );+ await page.waitForTimeout(500);+}++export async function selectGoogleDocsText(page: Page, text: string, occurrence = 0) {+ const selection = await page.evaluate(+ async ({ needle, targetOccurrence }) => {+ const annotated = await window._docs_annotate_getAnnotatedText();+ const source = annotated.getText();+ let start = -1;+ let fromIndex = 0;++ for (let i = 0; i <= targetOccurrence; i += 1) {+ start = source.indexOf(needle, fromIndex);+ if (start < 0) {+ return null;+ }+ fromIndex = start + needle.length;+ }++ return { start, end: start + needle.length };+ },+ {+ needle: text,+ targetOccurrence: occurrence,+ },+ );++ if (selection == null) {+ throw new Error(`Could not find "${text}" in Google Docs text`);+ }++ await selectGoogleDocsRange(page, selection.start, selection.end);+}++export async function selectGoogleDocsFromTextToEnd(page: Page, text: string) {+ const selection = await page.evaluate(async (needle) => {+ const annotated = await window._docs_annotate_getAnnotatedText();+ const source = annotated.getText();+ const start = source.indexOf(needle);+ if (start < 0) {+ return null;+ }++ return { start, end: source.length };+ }, text);++ if (selection == null) {+ throw new Error(`Could not find "${text}" in Google Docs text`);+ }++ await selectGoogleDocsRange(page, selection.start, selection.end);+}++export async function hasGoogleDocsRectWithFontContainingText(+ page: Page,+ text: string,+ fontPattern: RegExp,+): Promise<boolean> {+ const state = await getGoogleDocsRenderedState(page);+ const normalizedNeedle = normalizeWhitespace(text);++ return state.rectLabels.some((label, index) => {+ const normalizedLabel = normalizeWhitespace(label);+ const fontCss = state.rectFonts[index] ?? '';+ return normalizedLabel.includes(normalizedNeedle) && fontPattern.test(fontCss);+ });+}++export async function applyItalicToGoogleDocsText(page: Page, text: string, occurrence = 0) {+ await selectGoogleDocsText(page, text, occurrence);+ await page.keyboard.press('Control+I');++ await expect+ .poll(() => hasGoogleDocsRectWithFontContainingText(page, text, /italic/i), {+ timeout: 15000,+ })+ .toBe(true);+}++export async function applyBulletedListToGoogleDocsText(page: Page, text: string) {+ await selectGoogleDocsFromTextToEnd(page, text);+ await page.keyboard.press('Control+Shift+8');++ await expect.poll(() => getGoogleDocsBridgeText(page), { timeout: 15000 }).toContain(`● ${text}`);+}diff --git a/packages/chrome-plugin/tests/google_docs.spec.ts b/packages/chrome-plugin/tests/google_docs.spec.tsindex f72db2892..567e7b4b9 100644--- a/packages/chrome-plugin/tests/google_docs.spec.ts+++ b/packages/chrome-plugin/tests/google_docs.spec.ts@@ -10,7 +10,7 @@ type MockGoogleDocsRect = {fontCss?: string;};-const TEST_PAGE_URL = 'https://docs.google.com/document/d/harper-formatting-regression/edit';+const TEST_PAGE_URL = 'CHANGE_ME';const FORMATTED_WORD_GAP_RECTS: MockGoogleDocsRect[] = [{label: 'not',@@ -123,7 +123,216 @@ const SUPERSCRIPT_LIKE_RECTS: MockGoogleDocsRect[] = [fontCss: '16px Arial',},];-+const WRAPPED_LINE_RECTS: MockGoogleDocsRect[] = [+ {+ label: 'This sentence wraps',+ left: 48,+ top: 48,+ width: 128,+ height: 18,+ fontCss: '16px Arial',+ },+ {+ label: 'because the viewport is narrow.',+ left: 48,+ top: 72,+ width: 182,+ height: 18,+ fontCss: '16px Arial',+ },+];+const PARAGRAPH_BREAK_RECTS: MockGoogleDocsRect[] = [+ {+ label: 'First paragraph.',+ left: 48,+ top: 48,+ width: 110,+ height: 18,+ fontCss: '16px Arial',+ },+ {+ label: 'Second paragraph.',+ left: 48,+ top: 96,+ width: 126,+ height: 18,+ fontCss: '16px Arial',+ },+];+const NUMBERED_PAREN_LIST_RECTS: MockGoogleDocsRect[] = [+ {+ label: 'This paragraph stays sentence case.',+ left: 48,+ top: 48,+ width: 220,+ height: 18,+ fontCss: '16px Arial',+ },+ {+ label: '1)',+ left: 48,+ top: 96,+ width: 18,+ height: 18,+ fontCss: '16px Arial',+ },+ {+ label: 'This list item should stay sentence case',+ left: 74,+ top: 96,+ width: 240,+ height: 18,+ fontCss: '16px Arial',+ },+ {+ label: '2)',+ left: 48,+ top: 120,+ width: 18,+ height: 18,+ fontCss: '16px Arial',+ },+ {+ label: 'Another list item should stay sentence case',+ left: 74,+ top: 120,+ width: 258,+ height: 18,+ fontCss: '16px Arial',+ },+];+const NBSP_FORMATTED_GAP_RECTS: MockGoogleDocsRect[] = [+ {+ label: 'not',+ left: 48,+ top: 48,+ width: 24,+ height: 18,+ fontCss: '16px Arial',+ },+ {+ label: 'smart',+ left: 74,+ top: 56,+ width: 42,+ height: 18,+ fontCss: 'italic 16px Arial',+ },+ {+ label: 'enough.',+ left: 122,+ top: 48,+ width: 60,+ height: 18,+ fontCss: '16px Arial',+ },+];+const EM_DASH_SPLIT_RECTS: MockGoogleDocsRect[] = [+ {+ label: 'word',+ left: 48,+ top: 48,+ width: 34,+ height: 18,+ fontCss: '16px Arial',+ },+ {+ label: '—',+ left: 86,+ top: 48,+ width: 10,+ height: 18,+ fontCss: '16px Arial',+ },+ {+ label: 'word',+ left: 100,+ top: 48,+ width: 34,+ height: 18,+ fontCss: '16px Arial',+ },+];+const WIDE_SAME_ROW_GAP_RECTS: MockGoogleDocsRect[] = [+ {+ label: 'Name',+ left: 48,+ top: 48,+ width: 38,+ height: 18,+ fontCss: '16px Arial',+ },+ {+ label: 'Value',+ left: 176,+ top: 48,+ width: 40,+ height: 18,+ fontCss: '16px Arial',+ },+];+const COLUMN_MAJOR_TABLE_RECTS: MockGoogleDocsRect[] = [+ {+ label: 'Leah Pring',+ left: 48,+ top: 48,+ width: 92,+ height: 18,+ fontCss: '16px Arial',+ },+ {+ label: 'Emily Puetz',+ left: 48,+ top: 120,+ width: 96,+ height: 18,+ fontCss: '16px Arial',+ },+ {+ label: 'shares planning notes with the team every',+ left: 296,+ top: 48,+ width: 300,+ height: 18,+ fontCss: '16px Arial',+ },+ {+ label: 'morning.',+ left: 296,+ top: 72,+ width: 64,+ height: 18,+ fontCss: '16px Arial',+ },+ {+ label: 'is available in the early',+ left: 296,+ top: 120,+ width: 176,+ height: 18,+ fontCss: '16px Arial',+ },+ {+ label: 'morning before 9 and after 3:30.',+ left: 296,+ top: 144,+ width: 236,+ height: 18,+ fontCss: '16px Arial',+ },+];+const COLUMN_MAJOR_TABLE_TEXT = [+ 'Leah Pring',+ 'shares planning notes with the team every morning.',+ 'Emily Puetz',+ 'is available in the early morning before 9 and after 3:30.',+].join('\n');+const COLUMN_MAJOR_TABLE_COLLAPSED_WORD_TEXT = [+ 'Leah Pring',+ 'shares planning notes with the team every morning.',+ 'Emily Puetz',+ 'is available in the earlymorning before 9 and after 3:30.',+].join('\n');function buildMockGoogleDocsHtml(rects: MockGoogleDocsRect[]): string {const rectMarkup = rects.map(@@ -185,8 +394,8 @@ function escapeHtml(text: string): string {.replaceAll('>', '>');}-async function mockGoogleDocsPage(page: Page, rects: MockGoogleDocsRect[]) {- await page.route(TEST_PAGE_URL, async (route) => {+async function mockGoogleDocsPage(page: Page, rects: MockGoogleDocsRect[], url = TEST_PAGE_URL) {+ await page.route(url, async (route) => {await route.fulfill({contentType: 'text/html',body: buildMockGoogleDocsHtml(rects),@@ -194,28 +403,56 @@ async function mockGoogleDocsPage(page: Page, rects: MockGoogleDocsRect[]) {});}-async function installMockGoogleDocsGeometry(page: Page, rects: MockGoogleDocsRect[]) {- await page.evaluate((pageRects) => {- (- window as Window & {- _docs_annotate_getAnnotatedText?: () => Promise<{- getText: () => string;- setSelection: () => void;- getSelection: () => Array<{ start: number; end: number }>;- }>;- }- )._docs_annotate_getAnnotatedText = async () => ({- getText: () => pageRects.map((rect) => rect.label).join(''),- setSelection: () => {},- getSelection: () => [{ start: 0, end: 0 }],- });- }, rects);+async function installMockGoogleDocsGeometry(+ page: Page,+ rects: MockGoogleDocsRect[],+ annotatedText = rects.map((rect) => rect.label).join(''),+) {+ await page.evaluate(+ ({ pageText }) => {+ (+ window as Window & {+ __harperMockGoogleDocsText?: string;+ _docs_annotate_getAnnotatedText?: () => Promise<{+ getText: () => string;+ setSelection: () => void;+ getSelection: () => Array<{ start: number; end: number }>;+ }>;+ }+ ).__harperMockGoogleDocsText = pageText;+ (+ window as Window & {+ __harperMockGoogleDocsText?: string;+ _docs_annotate_getAnnotatedText?: () => Promise<{+ getText: () => string;+ setSelection: () => void;+ getSelection: () => Array<{ start: number; end: number }>;+ }>;+ }+ )._docs_annotate_getAnnotatedText = async () => ({+ getText: () =>+ (+ window as Window & {+ __harperMockGoogleDocsText?: string;+ }+ ).__harperMockGoogleDocsText ?? '',+ setSelection: () => {},+ getSelection: () => [{ start: 0, end: 0 }],+ });+ },+ { pageText: annotatedText },+ );}-async function openMockGoogleDocsPage(page: Page, rects: MockGoogleDocsRect[]) {- await mockGoogleDocsPage(page, rects);- await page.goto(TEST_PAGE_URL);- await installMockGoogleDocsGeometry(page, rects);+async function openMockGoogleDocsPage(+ page: Page,+ rects: MockGoogleDocsRect[],+ annotatedText?: string,+ url = TEST_PAGE_URL,+) {+ await mockGoogleDocsPage(page, rects, url);+ await page.goto(url);+ await installMockGoogleDocsGeometry(page, rects, annotatedText);await page.locator('#harper-google-docs-target').waitFor({ state: 'attached' });}@@ -233,38 +470,143 @@ async function getNormalizedBridgeText(page: Page) {);}-test('Google Docs restores spaces around formatted inline words', async ({ page }) => {- await openMockGoogleDocsPage(page, FORMATTED_WORD_GAP_RECTS);+async function getBridgeSource(page: Page) {+ return await page+ .locator('#harper-google-docs-target')+ .evaluate((node) => node.getAttribute('data-harper-gdocs-source'));+}- await expect- .poll(() => getNormalizedBridgeText(page), { timeout: 10000 })- .toBe('not smart enough.');- await expect.poll(() => getRawBridgeText(page), { timeout: 10000 }).not.toContain('\n');-});+test.describe('Google Docs support', () => {+ test('Google Docs restores spaces around formatted inline words', async ({ page }) => {+ await openMockGoogleDocsPage(page, FORMATTED_WORD_GAP_RECTS, 'not smart enough.');-test('Google Docs formatted rects stay in the same sentence', async ({ page }) => {- await openMockGoogleDocsPage(page, ITALIC_SHIFTED_RECTS);+ await expect+ .poll(() => getNormalizedBridgeText(page), { timeout: 10000 })+ .toBe('not smart enough.');+ await expect.poll(() => getRawBridgeText(page), { timeout: 10000 }).not.toContain('\n');+ });- await expect- .poll(() => getNormalizedBridgeText(page), { timeout: 10000 })- .toBe('This is an test.');- await expect.poll(() => getRawBridgeText(page), { timeout: 10000 }).not.toContain('\n');-});+ test('Google Docs formatted rects stay in the same sentence', async ({ page }) => {+ await openMockGoogleDocsPage(page, ITALIC_SHIFTED_RECTS);-test('Google Docs does not invent spaces around standalone punctuation rects', async ({ page }) => {- await openMockGoogleDocsPage(page, PUNCTUATION_BOUNDARY_RECTS);+ await expect+ .poll(() => getNormalizedBridgeText(page), { timeout: 10000 })+ .toBe('This is an test.');+ await expect.poll(() => getRawBridgeText(page), { timeout: 10000 }).not.toContain('\n');+ });- await expect- .poll(() => getNormalizedBridgeText(page), { timeout: 10000 })- .toBe('not smart enough. But');- await expect.poll(() => getRawBridgeText(page), { timeout: 10000 }).not.toContain(' .');-});+ test('Google Docs does not invent spaces around standalone punctuation rects', async ({+ page,+ }) => {+ await openMockGoogleDocsPage(page, PUNCTUATION_BOUNDARY_RECTS, 'not smart enough. But');++ await expect+ .poll(() => getNormalizedBridgeText(page), { timeout: 10000 })+ .toBe('not smart enough. But');+ await expect.poll(() => getRawBridgeText(page), { timeout: 10000 }).not.toContain(' .');+ });++ test('Google Docs superscript-like rects do not create a fake line break', async ({ page }) => {+ await openMockGoogleDocsPage(page, SUPERSCRIPT_LIKE_RECTS);++ await expect+ .poll(() => getNormalizedBridgeText(page), { timeout: 10000 })+ .toBe('Testing formatting matters.');+ await expect.poll(() => getRawBridgeText(page), { timeout: 10000 }).not.toContain('\n');+ });++ test('Google Docs keeps soft wraps out of the logical bridge text', async ({ page }) => {+ await openMockGoogleDocsPage(+ page,+ WRAPPED_LINE_RECTS,+ 'This sentence wraps because the viewport is narrow.',+ );++ await expect+ .poll(() => getRawBridgeText(page), { timeout: 10000 })+ .toBe('This sentence wraps because the viewport is narrow.');+ });-test('Google Docs superscript-like rects do not create a fake line break', async ({ page }) => {- await openMockGoogleDocsPage(page, SUPERSCRIPT_LIKE_RECTS);+ test('Google Docs preserves paragraph breaks from annotated text', async ({ page }) => {+ await openMockGoogleDocsPage(+ page,+ PARAGRAPH_BREAK_RECTS,+ 'First paragraph.\n\nSecond paragraph.',+ );++ await expect+ .poll(() => getRawBridgeText(page), { timeout: 10000 })+ .toBe('First paragraph.\n\nSecond paragraph.');+ });++ test('Google Docs keeps numbered list markers with closing parentheses on single list lines', async ({+ page,+ }) => {+ await openMockGoogleDocsPage(+ page,+ NUMBERED_PAREN_LIST_RECTS,+ 'This paragraph stays sentence case.\n1) This list item should stay sentence case\n2) Another list item should stay sentence case',+ );++ await expect+ .poll(() => getRawBridgeText(page), { timeout: 10000 })+ .toBe(+ 'This paragraph stays sentence case.\n1) This list item should stay sentence case\n2) Another list item should stay sentence case',+ );+ });++ test('Google Docs keeps NBSP-separated formatted inline words in the same sentence', async ({+ page,+ }) => {+ await openMockGoogleDocsPage(page, NBSP_FORMATTED_GAP_RECTS, 'not\u00a0smart enough.');++ await expect+ .poll(() => getNormalizedBridgeText(page), { timeout: 10000 })+ .toBe('not smart enough.');+ });++ test('Google Docs does not invent spaces around em dash rects in fallback mode', async ({+ page,+ }) => {+ await openMockGoogleDocsPage(page, EM_DASH_SPLIT_RECTS, '');- await expect- .poll(() => getNormalizedBridgeText(page), { timeout: 10000 })- .toBe('Testing formatting matters.');- await expect.poll(() => getRawBridgeText(page), { timeout: 10000 }).not.toContain('\n');+ await expect.poll(() => getRawBridgeText(page), { timeout: 10000 }).toBe('word—word');+ });++ test('Google Docs keeps wide same-row fallback gaps in a single logical line', async ({+ page,+ }) => {+ await openMockGoogleDocsPage(page, WIDE_SAME_ROW_GAP_RECTS, '');++ await expect.poll(() => getRawBridgeText(page), { timeout: 10000 }).toBe('Name Value');+ });++ test('Google Docs keeps column-major table rects in logical row order', async ({ page }) => {+ await openMockGoogleDocsPage(page, COLUMN_MAJOR_TABLE_RECTS, COLUMN_MAJOR_TABLE_TEXT);++ await expect.poll(() => getBridgeSource(page), { timeout: 10000 }).toBe('logical');+ await expect+ .poll(() => getRawBridgeText(page), { timeout: 10000 })+ .toBe(COLUMN_MAJOR_TABLE_TEXT);+ });++ test('Google Docs repairs collapsed wrapped words from malformed logical text', async ({+ page,+ }) => {+ await openMockGoogleDocsPage(+ page,+ COLUMN_MAJOR_TABLE_RECTS,+ COLUMN_MAJOR_TABLE_COLLAPSED_WORD_TEXT,+ );++ await expect+ .poll(() => getNormalizedBridgeText(page), { timeout: 10000 })+ .toContain('is available in the early morning before 9 and after 3:30.');+ await expect+ .poll(() => getRawBridgeText(page), { timeout: 10000 })+ .not.toContain('earlymorning');+ await expect+ .poll(async () => await page.locator('#harper-highlight').count(), { timeout: 10000 })+ .toBe(0);+ });});diff --git a/packages/chrome-plugin/tests/google_docs_flicker.spec.ts b/packages/chrome-plugin/tests/google_docs_flicker.spec.tsnew file mode 100644index 000000000..96d00943a--- /dev/null+++ b/packages/chrome-plugin/tests/google_docs_flicker.spec.ts@@ -0,0 +1,274 @@+import type { Page } from '@playwright/test';+import { expect, test } from './fixtures';++type MockGoogleDocsRect = {+ label: string;+ left: number;+ top: number;+ width: number;+ height: number;+ fontCss?: string;+};++const GOOGLE_DOCS_HIGHLIGHT_TIMEOUT_MS = 20000;++function buildMockGoogleDocsHtml(rects: MockGoogleDocsRect[]): string {+ const rectMarkup = rects+ .map(+ (rect, index) => `+ <rect+ data-rect-index="${index}"+ x="${rect.left}"+ y="${rect.top}"+ width="${rect.width}"+ height="${rect.height}"+ fill="rgba(15, 23, 42, 0.001)"+ aria-label="${escapeHtml(rect.label)}"+ data-font-css="${escapeHtml(rect.fontCss ?? '')}"+ />+ `,+ )+ .join('');++ return `<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <title>Mock Google Docs</title>+ <style>+ body {+ margin: 0;+ font: 16px/1.4 sans-serif;+ background: #f3f4f6;+ }++ #docs-editor {+ position: relative;+ width: 900px;+ height: 240px;+ margin: 32px auto;+ background: white;+ border: 1px solid #d1d5db;+ }++ svg {+ width: 100%;+ height: 100%;+ }+ </style>+ </head>+ <body>+ <div id="docs-editor" class="kix-appview-editor">+ <svg>${rectMarkup}</svg>+ </div>+ </body>+</html>`;+}++function escapeHtml(text: string): string {+ return text+ .replaceAll('&', '&')+ .replaceAll('"', '"')+ .replaceAll('<', '<')+ .replaceAll('>', '>');+}++async function installMockGoogleDocsGeometry(page: Page, annotatedText: string) {+ await page.evaluate(+ ({ pageText }) => {+ (+ window as Window & {+ __harperMockGoogleDocsText?: string;+ _docs_annotate_getAnnotatedText?: () => Promise<{+ getText: () => string;+ setSelection: () => void;+ getSelection: () => Array<{ start: number; end: number }>;+ }>;+ }+ ).__harperMockGoogleDocsText = pageText;+ (+ window as Window & {+ __harperMockGoogleDocsText?: string;+ _docs_annotate_getAnnotatedText?: () => Promise<{+ getText: () => string;+ setSelection: () => void;+ getSelection: () => Array<{ start: number; end: number }>;+ }>;+ }+ )._docs_annotate_getAnnotatedText = async () => ({+ getText: () =>+ (+ window as Window & {+ __harperMockGoogleDocsText?: string;+ }+ ).__harperMockGoogleDocsText ?? '',+ setSelection: () => {},+ getSelection: () => [{ start: 0, end: 0 }],+ });+ },+ { pageText: annotatedText },+ );+}++async function openMockGoogleDocsPage(+ page: Page,+ url: string,+ rects: MockGoogleDocsRect[],+ annotatedText: string,+) {+ await page.route(url, async (route) => {+ await route.fulfill({+ contentType: 'text/html',+ body: buildMockGoogleDocsHtml(rects),+ });+ });+ await page.goto(url);+ await installMockGoogleDocsGeometry(page, annotatedText);+ await page.locator('#harper-google-docs-target').waitFor({ state: 'attached' });+}++async function updateMockGoogleDocsGeometry(+ page: Page,+ rects: MockGoogleDocsRect[],+ annotatedText: string,+) {+ await page.evaluate(+ ({ nextRects, pageText }) => {+ const svg = document.querySelector('svg');+ if (!(svg instanceof SVGElement)) {+ throw new Error('Missing mock Google Docs SVG');+ }++ svg.replaceChildren();++ for (const [index, rect] of nextRects.entries()) {+ const node = document.createElementNS('http://www.w3.org/2000/svg', 'rect');+ node.setAttribute('data-rect-index', String(index));+ node.setAttribute('x', String(rect.left));+ node.setAttribute('y', String(rect.top));+ node.setAttribute('width', String(rect.width));+ node.setAttribute('height', String(rect.height));+ node.setAttribute('fill', 'rgba(15, 23, 42, 0.001)');+ node.setAttribute('aria-label', rect.label);+ node.setAttribute('data-font-css', rect.fontCss ?? '');+ svg.appendChild(node);+ }++ (+ window as Window & {+ __harperMockGoogleDocsText?: string;+ }+ ).__harperMockGoogleDocsText = pageText;+ },+ { nextRects: rects, pageText: annotatedText },+ );+}++async function getNormalizedBridgeText(page: Page) {+ return await page+ .locator('#harper-google-docs-target')+ .evaluate((node) =>+ (node.textContent ?? '').replaceAll('\u00a0', ' ').replace(/\s+/g, ' ').trim(),+ );+}++async function startHighlightCountSampling(page: Page) {+ await page.evaluate(() => {+ const win = window as Window & {+ __harperHighlightSamples?: number[];+ __harperHighlightSamplerId?: number;+ };+ win.__harperHighlightSamples = [];++ const sample = () => {+ const count = Array.from(document.querySelectorAll<HTMLElement>('harper-render-box')).reduce(+ (total, host) =>+ total + (host.shadowRoot?.querySelectorAll('#harper-highlight').length ?? 0),+ 0,+ );+ win.__harperHighlightSamples?.push(count);+ };++ sample();+ win.__harperHighlightSamplerId = window.setInterval(sample, 40);+ });+}++async function stopHighlightCountSampling(page: Page): Promise<number[]> {+ return await page.evaluate(() => {+ const win = window as Window & {+ __harperHighlightSamples?: number[];+ __harperHighlightSamplerId?: number;+ };++ if (win.__harperHighlightSamplerId != null) {+ window.clearInterval(win.__harperHighlightSamplerId);+ delete win.__harperHighlightSamplerId;+ }++ return [...(win.__harperHighlightSamples ?? [])];+ });+}++test.describe('Google Docs support', () => {+ test('Google Docs keeps existing typo highlights stable while unrelated text is appended (#3122)', async ({+ page,+ }) => {+ const initialText = 'Stable context. This is teh plan.';+ const updatedText = `${initialText} More text.`;+ const testPageUrl = 'CHANGE_ME';+ const initialRects: MockGoogleDocsRect[] = [+ {+ label: 'Stable context. This is ',+ left: 48,+ top: 48,+ width: 168,+ height: 18,+ fontCss: '16px Arial',+ },+ {+ label: 'teh plan.',+ left: 220,+ top: 48,+ width: 64,+ height: 18,+ fontCss: '16px Arial',+ },+ ];+ const updatedRects: MockGoogleDocsRect[] = [+ ...initialRects,+ {+ label: ' More text.',+ left: 292,+ top: 48,+ width: 72,+ height: 18,+ fontCss: '16px Arial',+ },+ ];++ await openMockGoogleDocsPage(page, testPageUrl, initialRects, initialText);++ await expect+ .poll(async () => await page.locator('#harper-highlight').count(), {+ timeout: GOOGLE_DOCS_HIGHLIGHT_TIMEOUT_MS,+ })+ .toBeGreaterThan(0);++ await startHighlightCountSampling(page);+ await updateMockGoogleDocsGeometry(page, updatedRects, updatedText);++ await expect.poll(() => getNormalizedBridgeText(page), { timeout: 10000 }).toBe(updatedText);+ await expect+ .poll(async () => await page.locator('#harper-highlight').count(), {+ timeout: GOOGLE_DOCS_HIGHLIGHT_TIMEOUT_MS,+ })+ .toBeGreaterThan(0);++ await page.waitForTimeout(400);+ const highlightSamples = await stopHighlightCountSampling(page);++ expect(highlightSamples.some((count) => count > 0)).toBe(true);+ expect(highlightSamples).not.toContain(0);+ });+});diff --git a/packages/chrome-plugin/tests/google_docs_live.spec.ts b/packages/chrome-plugin/tests/google_docs_live.spec.tsnew file mode 100644index 000000000..6fdf3aacf--- /dev/null+++ b/packages/chrome-plugin/tests/google_docs_live.spec.ts@@ -0,0 +1,513 @@+import type { Page } from '@playwright/test';+import { expect, test } from './fixtures';+import {+ appendGoogleDocsTable,+ applyBulletedListToGoogleDocsText,+ applyItalicToGoogleDocsText,+ getGoogleDocsAnnotatedText,+ getGoogleDocsBridgeText,+ getGoogleDocsHighlightCount,+ getGoogleDocsNormalizedBridgeText,+ getGoogleDocsVisualLineCount,+ hasGoogleDocsRectWithFontContainingText,+ openLiveGoogleDoc,+ replaceGoogleDocsDocumentText,+ setGoogleDocsFontSize,+} from './googleDocsTestUtils';+import { clickHarperHighlight, waitForHarperHighlightCenter } from './testUtils';++const WRAPPED_SENTENCE =+ 'This intentionally long sentence wraps across the page so Harper must treat it as one continuous sentence even when Google Docs renders it over multiple visual lines for the reader.';+const WRAPPED_LINKED_SENTENCE =+ 'We will be clear with one another about exactly what work we expect to finish and by when. For this, we will be tracking project work using the Basecamp tool (https://basecamp.com/; our team page is https://3.basecamp.com/4507520). When timelines can not be met as originally promised, the owner of the task agrees to communicate that change as quickly as possible to impacted stakeholders. Leah Pring will coordinate usage of the Basecamp tool across all workstreams. Invitations will be sent to everyone on the team.';+const GOOGLE_DOCS_BRIDGE_PROTOCOL = 'harper-gdocs-bridge/v1';+const GOOGLE_DOCS_FONT_SIZES = [11, 14, 18];+const LIVE_GOOGLE_DOCS_HIGHLIGHT_TIMEOUT_MS = 20000;++type ScreenRect = {+ x: number;+ y: number;+ width: number;+ height: number;+};++function getOccurrenceRange(source: string, needle: string, occurrence = 0) {+ let start = -1;+ let fromIndex = 0;++ for (let i = 0; i <= occurrence; i += 1) {+ start = source.indexOf(needle, fromIndex);+ if (start < 0) {+ throw new Error(`Could not find occurrence ${occurrence} of "${needle}"`);+ }+ fromIndex = start + needle.length;+ }++ return {+ start,+ end: start + needle.length,+ };+}++async function dispatchGoogleDocsBridgeReplacement(+ page: Page,+ request: {+ start: number;+ end: number;+ replacementText: string;+ expectedText: string;+ beforeContext: string;+ afterContext: string;+ },+): Promise<boolean> {+ return await page.evaluate(+ async ({ protocol, request }) => {+ const requestId = `playwright-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;++ const response = await new Promise<{ kind: string; applied?: boolean; message?: string }>(+ (resolve, reject) => {+ const timeoutId = window.setTimeout(() => {+ document.removeEventListener('harper:gdocs:response', onResponse as EventListener);+ reject(new Error('Timed out waiting for Google Docs bridge response'));+ }, 5000);++ const onResponse = (event: Event) => {+ const detail = (event as CustomEvent).detail;+ if (detail?.protocol !== protocol || detail?.requestId !== requestId) {+ return;+ }++ window.clearTimeout(timeoutId);+ document.removeEventListener('harper:gdocs:response', onResponse as EventListener);+ resolve(detail.response);+ };++ document.addEventListener('harper:gdocs:response', onResponse as EventListener);+ document.dispatchEvent(+ new CustomEvent('harper:gdocs:request', {+ detail: {+ protocol,+ requestId,+ request: {+ kind: 'replaceText',+ ...request,+ },+ },+ }),+ );+ },+ );++ if (response.kind !== 'replaceText') {+ throw new Error(response.message ?? 'Unexpected Google Docs bridge response');+ }++ return response.applied === true;+ },+ {+ protocol: GOOGLE_DOCS_BRIDGE_PROTOCOL,+ request,+ },+ );+}++async function getHarperHighlightBoxes(page: Page): Promise<ScreenRect[]> {+ return await page.locator('#harper-highlight').evaluateAll((nodes) =>+ nodes.map((node) => {+ const rect = node.getBoundingClientRect();+ return {+ x: rect.x,+ y: rect.y,+ width: rect.width,+ height: rect.height,+ };+ }),+ );+}++test.describe('Google Docs live regressions', () => {+ test.describe.configure({ mode: 'serial' });+ test.setTimeout(180000);++ test.beforeEach(async ({ page }) => {+ await openLiveGoogleDoc(page);+ });++ test.afterEach(async ({ page }) => {+ try {+ await replaceGoogleDocsDocumentText(page, '');+ } catch {+ // Best effort cleanup for the shared document.+ }+ });++ test('detects basic lints in a live Google Doc (#1966)', async ({ page }) => {+ test.slow();++ await replaceGoogleDocsDocumentText(page, 'This is an test');++ await expect+ .poll(() => getGoogleDocsAnnotatedText(page), { timeout: 20000 })+ .toBe('This is an test');+ await expect+ .poll(() => getGoogleDocsNormalizedBridgeText(page), { timeout: 20000 })+ .toBe('This is an test');+ expect(await waitForHarperHighlightCenter(page, 20000)).not.toBeNull();+ });++ test('highlights only the incorrect portion in a live Google Doc', async ({ page }) => {+ test.slow();++ const source = 'This is an test';+ const typoText = 'an';+ await replaceGoogleDocsDocumentText(page, source);++ await expect.poll(() => getGoogleDocsAnnotatedText(page), { timeout: 20000 }).toBe(source);+ await expect+ .poll(() => getGoogleDocsNormalizedBridgeText(page), { timeout: 20000 })+ .toBe(source);+ expect(+ await waitForHarperHighlightCenter(page, LIVE_GOOGLE_DOCS_HIGHLIGHT_TIMEOUT_MS),+ ).not.toBeNull();++ const highlightBoxes = await getHarperHighlightBoxes(page);+ expect(highlightBoxes.length).toBeGreaterThan(0);+ const sourceRects = await page.evaluate((lineText) => {+ return Array.from(+ document.querySelectorAll<SVGRectElement>('.kix-appview-editor rect[aria-label]'),+ )+ .map((rect) => {+ const label = rect.getAttribute('aria-label') ?? '';+ const box = rect.getBoundingClientRect();+ return {+ label,+ x: box.x,+ y: box.y,+ width: box.width,+ height: box.height,+ };+ })+ .filter((rect) => rect.label.includes(lineText));+ }, source);+ expect(sourceRects.length).toBeGreaterThan(0);++ const sourceRect = sourceRects[0];+ const matchingHighlight = highlightBoxes.find((box) => {+ const centerY = box.y + box.height / 2;+ return centerY >= sourceRect.y - 8 && centerY <= sourceRect.y + sourceRect.height + 8;+ });++ expect(matchingHighlight).toBeDefined();+ expect(matchingHighlight!.width).toBeLessThan(sourceRect.width / 2);+ expect(matchingHighlight!.x).toBeGreaterThan(sourceRect.x + sourceRect.width * 0.2);+ expect(matchingHighlight!.x + matchingHighlight!.width).toBeLessThan(+ sourceRect.x + sourceRect.width * 0.8,+ );+ });++ test('applies suggestion replacements in a live Google Doc (#2995)', async ({ page }) => {+ test.slow();++ await replaceGoogleDocsDocumentText(page, 'This is an test');++ const opened = await clickHarperHighlight(page);+ expect(opened).toBe(true);+ await page.getByTitle('Replace with "a"').click();++ await expect+ .poll(() => getGoogleDocsAnnotatedText(page), { timeout: 20000 })+ .toBe('This is a test');+ await expect+ .poll(() => getGoogleDocsNormalizedBridgeText(page), { timeout: 20000 })+ .toBe('This is a test');+ });++ test('keeps inline formatting in the same sentence (#2882)', async ({ page }) => {+ test.slow();++ await replaceGoogleDocsDocumentText(page, 'This is not smart enough.');+ await applyItalicToGoogleDocsText(page, 'smart');++ await expect+ .poll(() => getGoogleDocsBridgeText(page), { timeout: 20000 })+ .toBe('This is not smart enough.');+ await expect.poll(() => getGoogleDocsHighlightCount(page), { timeout: 15000 }).toBe(0);+ });++ test('preserves inline formatting after applying a nearby suggestion', async ({ page }) => {+ test.slow();++ await replaceGoogleDocsDocumentText(page, 'This is an test.');+ await applyItalicToGoogleDocsText(page, 'test');++ await expect+ .poll(() => hasGoogleDocsRectWithFontContainingText(page, 'test', /italic/i), {+ timeout: 15000,+ })+ .toBe(true);++ const opened = await clickHarperHighlight(page);+ expect(opened).toBe(true);+ await page.getByTitle('Replace with "a"').click();++ await expect+ .poll(() => getGoogleDocsAnnotatedText(page), { timeout: 20000 })+ .toBe('This is a test.');+ await expect+ .poll(() => getGoogleDocsBridgeText(page), { timeout: 20000 })+ .toBe('This is a test.');+ await expect+ .poll(() => hasGoogleDocsRectWithFontContainingText(page, 'test', /italic/i), {+ timeout: 15000,+ })+ .toBe(true);+ });++ test('does not misread bullet lists as headings (#2923)', async ({ page }) => {+ test.slow();++ await replaceGoogleDocsDocumentText(+ page,+ 'This paragraph stays sentence case.\nThis list item should stay sentence case\nAnother list item should stay sentence case',+ );+ await applyBulletedListToGoogleDocsText(page, 'This list item should stay sentence case');++ await expect+ .poll(() => getGoogleDocsBridgeText(page), { timeout: 20000 })+ .toBe(+ 'This paragraph stays sentence case.\n● This list item should stay sentence case\n● Another list item should stay sentence case',+ );+ await expect.poll(() => getGoogleDocsHighlightCount(page), { timeout: 15000 }).toBe(0);+ });++ test('preserves paragraph boundaries in the bridge text (#2959)', async ({ page }) => {+ test.slow();++ await replaceGoogleDocsDocumentText(+ page,+ 'First short paragraph\nSecond short paragraph\nThird short paragraph',+ );++ await expect+ .poll(() => getGoogleDocsBridgeText(page), { timeout: 20000 })+ .toBe('First short paragraph\n\nSecond short paragraph\n\nThird short paragraph');+ });++ test('realigns stale replacement offsets to the intended duplicate phrase', async ({ page }) => {+ test.slow();++ const originalText = 'Context alpha: This is an test. Context beta: This is an test.';+ const insertedPrefix = 'Long inserted prefix here. ';+ await replaceGoogleDocsDocumentText(page, originalText);+ await expect.poll(() => getGoogleDocsBridgeText(page), { timeout: 20000 }).toBe(originalText);++ const originalBridgeText = await getGoogleDocsBridgeText(page);+ const targetSpan = getOccurrenceRange(originalBridgeText, 'an', 1);+ const beforeContext = originalBridgeText.slice(+ Math.max(0, targetSpan.start - 64),+ targetSpan.start,+ );+ const afterContext = originalBridgeText.slice(+ targetSpan.end,+ Math.min(originalBridgeText.length, targetSpan.end + 64),+ );++ const shiftedText = `Context alpha: This is an test. Context beta: ${insertedPrefix}This is an test.`;+ await replaceGoogleDocsDocumentText(page, shiftedText);++ const applied = await dispatchGoogleDocsBridgeReplacement(page, {+ start: targetSpan.start,+ end: targetSpan.end,+ replacementText: 'a',+ expectedText: originalBridgeText.slice(targetSpan.start, targetSpan.end),+ beforeContext,+ afterContext,+ });++ expect(applied).toBe(true);+ await expect+ .poll(() => getGoogleDocsAnnotatedText(page), { timeout: 20000 })+ .toBe(+ 'Context alpha: This is an test. Context beta: Long inserted prefix here. This is a test.',+ );+ await expect+ .poll(() => getGoogleDocsBridgeText(page), { timeout: 20000 })+ .toBe(+ 'Context alpha: This is an test. Context beta: Long inserted prefix here. This is a test.',+ );+ });++ test('realigns stale replacement offsets when duplicate local contexts are ambiguous', async ({+ page,+ }) => {+ test.slow();++ const repeatedSentence = 'Lorem ipsum an dolor sit amet.';+ const originalText = `${repeatedSentence} ${repeatedSentence}`;+ const insertedPrefix =+ 'Long inserted prefix that shifts the target far away from its original offsets. ';++ await replaceGoogleDocsDocumentText(page, originalText);+ await expect.poll(() => getGoogleDocsBridgeText(page), { timeout: 20000 }).toBe(originalText);++ const originalBridgeText = await getGoogleDocsBridgeText(page);+ const targetSpan = getOccurrenceRange(originalBridgeText, 'an', 1);+ const beforeContext = originalBridgeText.slice(+ Math.max(0, targetSpan.start - 64),+ targetSpan.start,+ );+ const afterContext = originalBridgeText.slice(+ targetSpan.end,+ Math.min(originalBridgeText.length, targetSpan.end + 64),+ );++ const shiftedText = `${repeatedSentence} ${insertedPrefix}${repeatedSentence}`;+ await replaceGoogleDocsDocumentText(page, shiftedText);++ const applied = await dispatchGoogleDocsBridgeReplacement(page, {+ start: targetSpan.start,+ end: targetSpan.end,+ replacementText: 'a',+ expectedText: originalBridgeText.slice(targetSpan.start, targetSpan.end),+ beforeContext,+ afterContext,+ });++ expect(applied).toBe(true);+ await expect+ .poll(() => getGoogleDocsAnnotatedText(page), { timeout: 20000 })+ .toBe(`Lorem ipsum an dolor sit amet. ${insertedPrefix}Lorem ipsum a dolor sit amet.`);+ await expect+ .poll(() => getGoogleDocsBridgeText(page), { timeout: 20000 })+ .toBe(`Lorem ipsum an dolor sit amet. ${insertedPrefix}Lorem ipsum a dolor sit amet.`);+ });++ for (const fontSize of GOOGLE_DOCS_FONT_SIZES) {+ test(`does not invent a sentence break at a soft wrap (#2992, ${fontSize}pt)`, async ({+ page,+ }) => {+ test.slow();++ await setGoogleDocsFontSize(page, fontSize);+ await replaceGoogleDocsDocumentText(page, WRAPPED_SENTENCE);++ await expect+ .poll(() => getGoogleDocsVisualLineCount(page), { timeout: 20000 })+ .toBeGreaterThan(1);+ await expect+ .poll(() => getGoogleDocsNormalizedBridgeText(page), { timeout: 20000 })+ .toBe(WRAPPED_SENTENCE);+ await expect+ .poll(() => getGoogleDocsBridgeText(page), { timeout: 20000 })+ .toBe(WRAPPED_SENTENCE);+ });++ test(`keeps wrapped url-heavy prose intact on a real Google Doc page (${fontSize}pt)`, async ({+ page,+ }) => {+ test.slow();++ await setGoogleDocsFontSize(page, fontSize);+ await replaceGoogleDocsDocumentText(page, WRAPPED_LINKED_SENTENCE);++ await expect+ .poll(() => getGoogleDocsVisualLineCount(page), { timeout: 20000 })+ .toBeGreaterThan(3);+ await expect+ .poll(() => getGoogleDocsBridgeText(page), { timeout: 20000 })+ .toBe(WRAPPED_LINKED_SENTENCE);+ await expect.poll(() => getGoogleDocsHighlightCount(page), { timeout: 15000 }).toBe(0);+ });++ test(`does not collapse early morning inside a real Google Docs table cell (${fontSize}pt)`, async ({+ page,+ }) => {+ test.slow();++ const suffix = `${fontSize}-${Date.now().toString(36)}`;+ const leftCell = `Emily Puetz ${suffix}`;+ const rightCell =+ 'Is available in the early morning before 9 and after 3:30, then reviews drafts again after lunch on most weekdays.';++ await setGoogleDocsFontSize(page, fontSize);+ await appendGoogleDocsTable(page, [+ [`Name ${suffix}`, `Availability notes ${suffix}`],+ [leftCell, rightCell],+ ]);++ await expect+ .poll(() => getGoogleDocsAnnotatedText(page), { timeout: 20000 })+ .toContain(rightCell);+ await expect+ .poll(() => getGoogleDocsBridgeText(page), { timeout: 20000 })+ .toContain('early morning before 9 and after 3:30,');+ await expect+ .poll(() => getGoogleDocsBridgeText(page), { timeout: 20000 })+ .toContain('then reviews drafts again after lunch on most weekdays.');+ await expect+ .poll(() => getGoogleDocsBridgeText(page), { timeout: 20000 })+ .not.toContain('earlymorning');+ const getTableRects = async () =>+ await page.evaluate(+ ({ leftCell }) => {+ const rects = Array.from(+ document.querySelectorAll<SVGRectElement>('.kix-appview-editor rect[aria-label]'),+ ).map((rect) => {+ const box = rect.getBoundingClientRect();+ return {+ label: rect.getAttribute('aria-label') ?? '',+ top: Math.round(box.top),+ left: Math.round(box.left),+ };+ });++ const leftRect = rects.find((rect) => rect.label.includes(leftCell));+ const rightRects =+ leftRect == null+ ? []+ : rects.filter(+ (rect) => rect.left > leftRect.left + 100 && rect.top >= leftRect.top - 12,+ );+ if (!leftRect || rightRects.length < 2) {+ return null;+ }++ return {+ leftTop: leftRect.top,+ leftX: leftRect.left,+ rightRects,+ };+ },+ {+ leftCell: 'Emily Puetz',+ },+ );+ await expect.poll(() => getTableRects(), { timeout: 20000 }).not.toBeNull();+ const tableRects = await getTableRects();+ const highestRightRect = Math.min(...tableRects!.rightRects.map(({ top }) => top));+ const leftmostRightRect = Math.min(...tableRects!.rightRects.map(({ left }) => left));+ expect(Math.abs(tableRects!.leftTop - highestRightRect)).toBeLessThanOrEqual(12);+ expect(leftmostRightRect - tableRects!.leftX).toBeGreaterThan(100);+ expect(new Set(tableRects!.rightRects.map(({ top }) => top)).size).toBeGreaterThan(1);++ const highlightCountInTargetRow = await page.evaluate(+ ({ leftBoundary, rowTop, rowBottom }) => {+ return Array.from(document.querySelectorAll<HTMLElement>('#harper-highlight')).filter(+ (highlight) => {+ const box = highlight.getBoundingClientRect();+ const centerX = box.left + box.width / 2;+ const centerY = box.top + box.height / 2;+ return centerX > leftBoundary && centerY >= rowTop && centerY <= rowBottom;+ },+ ).length;+ },+ {+ leftBoundary: tableRects!.leftX + 100,+ rowTop: highestRightRect - 12,+ rowBottom: Math.max(...tableRects!.rightRects.map(({ top }) => top)) + 24,+ },+ );+ expect(highlightCountInTargetRow).toBe(0);+ });+ }+});diff --git a/packages/chrome-plugin/tests/google_docs_table_anchor.spec.ts b/packages/chrome-plugin/tests/google_docs_table_anchor.spec.tsnew file mode 100644index 000000000..93a6304d4--- /dev/null+++ b/packages/chrome-plugin/tests/google_docs_table_anchor.spec.ts@@ -0,0 +1,193 @@+import type { Page } from '@playwright/test';+import { expect, test } from './fixtures';+import { waitForHarperHighlightCenter } from './testUtils';++type MockGoogleDocsRect = {+ label: string;+ left: number;+ top: number;+ width: number;+ height: number;+ fontCss?: string;+};++const GOOGLE_DOCS_HIGHLIGHT_TIMEOUT_MS = 20000;++function buildMockGoogleDocsHtml(rects: MockGoogleDocsRect[]): string {+ const rectMarkup = rects+ .map(+ (rect, index) => `+ <rect+ data-rect-index="${index}"+ x="${rect.left}"+ y="${rect.top}"+ width="${rect.width}"+ height="${rect.height}"+ fill="rgba(15, 23, 42, 0.001)"+ aria-label="${escapeHtml(rect.label)}"+ data-font-css="${escapeHtml(rect.fontCss ?? '')}"+ />+ `,+ )+ .join('');++ return `<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <title>Mock Google Docs</title>+ <style>+ body {+ margin: 0;+ font: 16px/1.4 sans-serif;+ background: #f3f4f6;+ }++ #docs-editor {+ position: relative;+ width: 900px;+ height: 240px;+ margin: 32px auto;+ background: white;+ border: 1px solid #d1d5db;+ }++ svg {+ width: 100%;+ height: 100%;+ }+ </style>+ </head>+ <body>+ <div id="docs-editor" class="kix-appview-editor">+ <svg>${rectMarkup}</svg>+ </div>+ </body>+</html>`;+}++function escapeHtml(text: string): string {+ return text+ .replaceAll('&', '&')+ .replaceAll('"', '"')+ .replaceAll('<', '<')+ .replaceAll('>', '>');+}++async function openMockGoogleDocsPage(+ page: Page,+ url: string,+ rects: MockGoogleDocsRect[],+ annotatedText: string,+) {+ await page.route(url, async (route) => {+ await route.fulfill({+ contentType: 'text/html',+ body: buildMockGoogleDocsHtml(rects),+ });+ });+ await page.goto(url);+ await page.evaluate(+ ({ pageText }) => {+ (+ window as Window & {+ __harperMockGoogleDocsText?: string;+ _docs_annotate_getAnnotatedText?: () => Promise<{+ getText: () => string;+ setSelection: () => void;+ getSelection: () => Array<{ start: number; end: number }>;+ }>;+ }+ ).__harperMockGoogleDocsText = pageText;+ (+ window as Window & {+ __harperMockGoogleDocsText?: string;+ _docs_annotate_getAnnotatedText?: () => Promise<{+ getText: () => string;+ setSelection: () => void;+ getSelection: () => Array<{ start: number; end: number }>;+ }>;+ }+ )._docs_annotate_getAnnotatedText = async () => ({+ getText: () =>+ (+ window as Window & {+ __harperMockGoogleDocsText?: string;+ }+ ).__harperMockGoogleDocsText ?? '',+ setSelection: () => {},+ getSelection: () => [{ start: 0, end: 0 }],+ });+ },+ { pageText: annotatedText },+ );+ await page.locator('#harper-google-docs-target').waitFor({ state: 'attached' });+}++async function getBridgeSource(page: Page) {+ return await page+ .locator('#harper-google-docs-target')+ .evaluate((node) => node.getAttribute('data-harper-gdocs-source'));+}++test.describe('Google Docs support', () => {+ test('Google Docs anchors table-cell typo highlights to the right column text', async ({+ page,+ }) => {+ const testPageUrl = 'CHANGE_ME';+ const typoRects: MockGoogleDocsRect[] = [+ {+ label: 'Dana Mills',+ left: 48,+ top: 48,+ width: 88,+ height: 18,+ fontCss: '16px Arial',+ },+ {+ label: 'Emily Stone',+ left: 48,+ top: 120,+ width: 92,+ height: 18,+ fontCss: '16px Arial',+ },+ {+ label: 'writes careful notes for the team.',+ left: 296,+ top: 48,+ width: 224,+ height: 18,+ fontCss: '16px Arial',+ },+ {+ label: 'This is teh plan.',+ left: 296,+ top: 120,+ width: 120,+ height: 18,+ fontCss: '16px Arial',+ },+ ];+ const typoText = [+ 'Dana Mills',+ 'writes careful notes for the team.',+ 'Emily Stone',+ 'This is teh plan.',+ ].join('\n');++ await openMockGoogleDocsPage(page, testPageUrl, typoRects, typoText);++ await expect.poll(() => getBridgeSource(page), { timeout: 10000 }).toBe('logical');+ await expect+ .poll(async () => await page.locator('#harper-highlight').count(), {+ timeout: GOOGLE_DOCS_HIGHLIGHT_TIMEOUT_MS,+ })+ .toBeGreaterThan(0);++ const center = await waitForHarperHighlightCenter(page, GOOGLE_DOCS_HIGHLIGHT_TIMEOUT_MS);+ expect(center).not.toBeNull();+ expect(center!.x).toBeGreaterThan(260);+ expect(center!.y).toBeGreaterThan(140);+ });+});diff --git a/packages/lint-framework/src/index.ts b/packages/lint-framework/src/index.tsindex 5356c178f..84e1ac687 100644--- a/packages/lint-framework/src/index.ts+++ b/packages/lint-framework/src/index.ts@@ -1,5 +1,5 @@export * from './lint/Box';-export { default as computeLintBoxes } from './lint/computeLintBoxes';+export { default as computeLintBoxes } from './lint/computeLintBoxes/index';export * from './lint/domUtils';export * from './lint/editorUtils';export { default as Highlights } from './lint/Highlights';diff --git a/packages/lint-framework/src/lint/Highlights.ts b/packages/lint-framework/src/lint/Highlights.tsindex 4d193a74f..2d2aec384 100644--- a/packages/lint-framework/src/lint/Highlights.ts+++ b/packages/lint-framework/src/lint/Highlights.ts@@ -16,6 +16,13 @@ import {getSlateRoot,getTrixRoot,} from './editorUtils';+import {+ applyGoogleDocsRenderHostStyle,+ getGoogleDocsRenderOffset,+ getGoogleDocsRenderTarget,+ isGoogleDocsSource,+ isGoogleDocsSourceSyncing,+} from './googleDocsAdapter';import { type LintKind, lintKindColor } from './lintKindColor';import RenderBox from './RenderBox';import type SourceElement from './SourceElement';@@ -108,27 +115,19 @@ export default class Highlights {const updated = new Set();for (const [source, { boxes, cpa }] of sourceToBoxes.entries()) {+ if (isGoogleDocsSourceSyncing(source)) {+ updated.add(source);+ continue;+ }+const renderBox = this.renderBoxes.get(source)!;const host = renderBox.getShadowHost();host.id = 'harper-highlight-host';- const isGoogleDocsSource =- source instanceof HTMLElement &&- (source.classList.contains('kix-appview-editor') ||- source.closest('.kix-appview-editor') != null);-- if (isGoogleDocsSource) {- const hostStyle = host.style;+ const isGoogleDocs = isGoogleDocsSource(source);- hostStyle.position = 'absolute';- hostStyle.top = '0px';- hostStyle.left = '0px';- hostStyle.pointerEvents = 'none';- hostStyle.width = '0px';- hostStyle.height = '0px';- hostStyle.contain = 'none';- hostStyle.transform = 'none';- hostStyle.zIndex = '2147483647';+ if (applyGoogleDocsRenderHostStyle(host, source)) {+ // The Google Docs adapter owns the host positioning details.} else if (cpa != null) {const hostStyle = host.style;@@ -145,13 +144,10 @@ export default class Highlights {host.removeAttribute('style');}- const gdocsRenderOffset =- isGoogleDocsSource && source instanceof HTMLElement- ? this.getGoogleDocsRenderOffset(source)- : null;+ const googleDocsRenderOffset = getGoogleDocsRenderOffset(source);const offset =- gdocsRenderOffset ?? (isGoogleDocsSource || cpa == null ? null : { x: cpa.x, y: cpa.y });- const boxPosition: 'absolute' | 'fixed' = isGoogleDocsSource ? 'absolute' : 'fixed';+ 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));updated.add(source);@@ -159,6 +155,9 @@ export default class Highlights {for (const [source, box] of this.renderBoxes.entries()) {if (!updated.has(source)) {+ if (isGoogleDocsSourceSyncing(source)) {+ continue;+ }box.render(h('div', {}, []));}}@@ -227,11 +226,9 @@ export default class Highlights {/** Determines which target the render boxes should be attached to.* Depends on text editor. */private computeRenderTarget(el: SourceElement): HTMLElement {- if (- el instanceof HTMLElement &&- (el.classList.contains('kix-appview-editor') || el.closest('.kix-appview-editor') != null)- ) {- return el;+ const googleDocsRenderTarget = getGoogleDocsRenderTarget(el);+ if (googleDocsRenderTarget != null) {+ return googleDocsRenderTarget;}if (el.parentElement?.classList.contains('ProseMirror')) {@@ -263,15 +260,6 @@ export default class Highlights {return el.parentElement!;}-- private getGoogleDocsRenderOffset(source: HTMLElement): { x: number; y: number } {- const editorRect = source.getBoundingClientRect();-- return {- x: editorRect.x - source.scrollLeft,- y: editorRect.y - source.scrollTop,- };- }}function getInitialContainingRect(el: HTMLElement): DOMRect | null {@@ -286,7 +274,6 @@ function getInitialContainingRect(el: HTMLElement): DOMRect | null {return null;}-/*** Determines whether a given element would form the containing block* for a descendant with `position: fixed`, based on CSS transforms,diff --git a/packages/lint-framework/src/lint/LintFramework.ts b/packages/lint-framework/src/lint/LintFramework.tsindex 0615894fe..36523607a 100644--- a/packages/lint-framework/src/lint/LintFramework.ts+++ b/packages/lint-framework/src/lint/LintFramework.ts@@ -1,6 +1,6 @@import type { LintOptions } from 'harper.js';import { closestBox, type IgnorableLintBox } from './Box';-import computeLintBoxes from './computeLintBoxes';+import computeLintBoxes from './computeLintBoxes/index';import { isHeading, isVisible } from './domUtils';import { getCaretPosition, getCMRoot } from './editorUtils';import Highlights from './Highlights';diff --git a/packages/lint-framework/src/lint/computeLintBoxes/googleDocsUtilities.ts b/packages/lint-framework/src/lint/computeLintBoxes/googleDocsUtilities.tsnew file mode 100644index 000000000..427b37d44--- /dev/null+++ b/packages/lint-framework/src/lint/computeLintBoxes/googleDocsUtilities.ts@@ -0,0 +1,345 @@+import type { Span } from 'harper.js';+import { leafNodes } from '../domUtils';+import type { UnpackedLint, UnpackedSpan } from '../unpackLint';++type GoogleDocsReplacePayload = {+ start: number;+ end: number;+ replacementText: string;+ expectedText: string;+ beforeContext: string;+ afterContext: string;+};++type GoogleDocsBridgeClientLike = {+ replaceText: (+ start: number,+ end: number,+ replacementText: string,+ expectedText?: string,+ beforeContext?: string,+ afterContext?: string,+ ) => Promise<unknown> | unknown;+};++type WindowWithGoogleDocsBridgeClient = Window & {+ __harperGoogleDocsBridgeClient?: GoogleDocsBridgeClientLike;+};++let googleDocsMeasurementContext: CanvasRenderingContext2D | null | undefined;++function getGoogleDocsMeasurementContext(): CanvasRenderingContext2D | null {+ if (googleDocsMeasurementContext !== undefined) {+ return googleDocsMeasurementContext;+ }++ const canvas = document.createElement('canvas');+ googleDocsMeasurementContext = canvas.getContext('2d');+ return googleDocsMeasurementContext;+}++function getGoogleDocsTextSliceRect(+ host: HTMLElement,+ text: string,+ startOffset: number,+ endOffset: number,+): DOMRect | null {+ const hostRect = host.getBoundingClientRect();+ if (hostRect.width <= 0 || hostRect.height <= 0) {+ return null;+ }++ const safeStart = Math.max(0, Math.min(startOffset, text.length));+ const safeEnd = Math.max(safeStart, Math.min(endOffset, text.length));+ if (safeStart === safeEnd) {+ return null;+ }++ const ctx = getGoogleDocsMeasurementContext();+ if (ctx == null) {+ return hostRect;+ }++ const style = getComputedStyle(host);+ const font =+ style.font && style.font !== ''+ ? style.font+ : `${style.fontStyle} ${style.fontVariant} ${style.fontWeight} ${style.fontSize} / ${style.lineHeight} ${style.fontFamily}`;+ ctx.font = font;++ const prefix = text.slice(0, safeStart);+ const slice = text.slice(safeStart, safeEnd);+ const prefixWidth = ctx.measureText(prefix).width;+ const sliceWidth = Math.max(1, ctx.measureText(slice).width);+ const letterSpacing = Number.parseFloat(style.letterSpacing);+ const spacing = Number.isFinite(letterSpacing) ? letterSpacing : 0;+ const spacedPrefixWidth = prefixWidth + Math.max(0, safeStart - 1) * spacing;+ const spacedSliceWidth = sliceWidth + Math.max(0, safeEnd - safeStart - 1) * spacing;+ const x = hostRect.x + Math.min(hostRect.width, Math.max(0, spacedPrefixWidth));+ const width = Math.max(1, Math.min(hostRect.right - x, spacedSliceWidth));++ return new DOMRect(x, hostRect.y, width, hostRect.height);+}++function getCommonPrefixLength(left: string, right: string): number {+ const max = Math.min(left.length, right.length);+ let length = 0;++ while (length < max && left.charCodeAt(length) === right.charCodeAt(length)) {+ length += 1;+ }++ return length;+}++function getCommonSuffixLength(left: string, right: string): number {+ const max = Math.min(left.length, right.length);+ let length = 0;++ while (+ length < max &&+ left.charCodeAt(left.length - 1 - length) === right.charCodeAt(right.length - 1 - length)+ ) {+ length += 1;+ }++ return length;+}++function getLongestCommonSubsequenceLength(left: string, right: string): number {+ if (!left || !right) {+ return 0;+ }++ const prev = new Array(right.length + 1).fill(0);+ const next = new Array(right.length + 1).fill(0);++ for (let i = 1; i <= left.length; i += 1) {+ next[0] = 0;++ for (let j = 1; j <= right.length; j += 1) {+ if (left.charCodeAt(i - 1) === right.charCodeAt(j - 1)) {+ next[j] = prev[j - 1] + 1;+ } else {+ next[j] = Math.max(prev[j], next[j - 1]);+ }+ }++ for (let j = 0; j <= right.length; j += 1) {+ prev[j] = next[j];+ }+ }++ return prev[right.length];+}++/**+ * Re-resolves a Google Docs lint span against the bridge's current text.+ *+ * Google Docs text can shift between linting and rendering, so this uses the+ * original span text plus nearby context to find the best current match.+ */+export function resolveGoogleDocsSpan(+ currentSource: string,+ lint: UnpackedLint,+): UnpackedSpan | null {+ const safeStart = Math.max(0, Math.min(lint.span.start, lint.source.length));+ const safeEnd = Math.max(safeStart, Math.min(lint.span.end, lint.source.length));+ const expectedText = lint.source.slice(safeStart, safeEnd);+ if (expectedText.length === 0) {+ return null;+ }++ const directText = currentSource.slice(safeStart, safeEnd);+ if (directText === expectedText) {+ return { start: safeStart, end: safeEnd };+ }++ const spanLength = safeEnd - safeStart;+ const delta = currentSource.length - lint.source.length;+ const expectedStart = Math.max(0, safeStart + delta);++ for (let offset = -12; offset <= 12; offset += 1) {+ const start = expectedStart + offset;+ if (start < 0) {+ continue;+ }++ const end = start + spanLength;+ if (end > currentSource.length) {+ continue;+ }++ if (currentSource.slice(start, end) === expectedText) {+ return { start, end };+ }+ }++ const contextRadius = 64;+ const beforeContext = lint.source.slice(Math.max(0, safeStart - contextRadius), safeStart);+ const afterContext = lint.source.slice(+ safeEnd,+ Math.min(lint.source.length, safeEnd + contextRadius),+ );+ const beforeWindowLength = Math.max(beforeContext.length * 2, beforeContext.length + 64);+ const afterWindowLength = Math.max(afterContext.length * 2, afterContext.length + 64);+ const hits: Array<{ start: number; end: number; score: number }> = [];+ let cursor = 0;++ while (cursor <= currentSource.length) {+ const start = currentSource.indexOf(expectedText, cursor);+ if (start < 0) {+ break;+ }++ const end = start + expectedText.length;+ const candidateBefore = currentSource.slice(Math.max(0, start - beforeWindowLength), start);+ const candidateAfter = currentSource.slice(+ end,+ Math.min(currentSource.length, end + afterWindowLength),+ );+ let score = 0;++ score += getLongestCommonSubsequenceLength(beforeContext, candidateBefore) * 8;+ score += getLongestCommonSubsequenceLength(afterContext, candidateAfter) * 8;+ score += getCommonPrefixLength(beforeContext, candidateBefore) * 4;+ score += getCommonSuffixLength(beforeContext, candidateBefore) * 4;+ score += getCommonPrefixLength(afterContext, candidateAfter) * 4;+ score += getCommonSuffixLength(afterContext, candidateAfter) * 4;+ score -= Math.abs(start - expectedStart) / 1000;+ hits.push({ start, end, score });+ cursor = start + 1;+ }++ if (hits.length === 0) {+ return null;+ }++ hits.sort((left, right) => right.score - left.score);+ return { start: hits[0].start, end: hits[0].end };+}++/**+ * Identifies Harper's hidden Google Docs bridge target element.+ */+export function isGoogleDocsTarget(el: HTMLElement): boolean {+ return el.getAttribute('data-harper-google-docs-target') === 'true';+}++/**+ * Maps a span within the mirrored Google Docs target back to visible client rects.+ *+ * This prefers the positioned bridge spans used for Google Docs text slices and+ * falls back to DOM Range geometry when needed.+ */+export function getGoogleDocsHighlightRects(target: HTMLElement, span: Span): DOMRect[] {+ const children = leafNodes(target);+ const rects: DOMRect[] = [];+ let traversed = 0;++ for (const child of children) {+ const childText = child.textContent ?? '';+ const childLength = childText.length;+ const childStart = traversed;+ const childEnd = childStart + childLength;+ traversed = childEnd;+ const localStart = Math.max(0, span.start - childStart);+ const localEnd = Math.min(childLength, span.end - childStart);++ if (childLength === 0 || childEnd <= span.start || childStart >= span.end) {+ continue;+ }++ const positionedHost = getGoogleDocsPositionedLeafHost(child, target);+ if (positionedHost != null) {+ const rect = getGoogleDocsTextSliceRect(positionedHost, childText, localStart, localEnd);+ if (rect != null && rect.width > 0 && rect.height > 0) {+ rects.push(rect);+ continue;+ }+ }++ const range = document.createRange();+ range.setStart(child, localStart);+ range.setEnd(child, localEnd);+ const rangeRects = Array.from(range.getClientRects()).filter(+ (rect) => rect.width > 0 && rect.height > 0,+ );+ if (rangeRects.length > 0) {+ rects.push(...rangeRects);+ (range as any).detach?.();+ continue;+ }++ const rect = positionedHost?.getBoundingClientRect();+ if (rect != null && rect.width > 0 && rect.height > 0) {+ rects.push(rect);+ }++ (range as any).detach?.();+ }++ return rects;+}++function getGoogleDocsPositionedLeafHost(child: Node, target: HTMLElement): HTMLElement | null {+ let current = child.parentElement;++ while (current != null && current !== target) {+ if (getComputedStyle(current).position === 'absolute') {+ return current;+ }++ current = current.parentElement;+ }++ return null;+}++/**+ * Dispatches a Google Docs replacement through the bridge client exposed on `window`.+ *+ * The payload includes nearby context so the bridge can recover when the original+ * offsets have gone stale by the time the suggestion is applied.+ */+export function replaceGoogleDocsValue(+ span: { start: number; end: number },+ replacementText: string,+ source: string,+) {+ try {+ const safeStart = Math.max(0, Math.min(span.start, source.length));+ const safeEnd = Math.max(safeStart, Math.min(span.end, source.length));+ const expectedText = source.slice(safeStart, safeEnd);+ const contextRadius = 64;+ const beforeContext = source.slice(Math.max(0, safeStart - contextRadius), safeStart);+ const afterContext = source.slice(safeEnd, Math.min(source.length, safeEnd + contextRadius));++ const payload: GoogleDocsReplacePayload = {+ start: span.start,+ end: span.end,+ replacementText,+ expectedText,+ beforeContext,+ afterContext,+ };+ // This looks awkward because lint-framework cannot import chrome-plugin code directly.+ // The content script puts the bridge client on window so this shared package can call it.+ const bridgeClient = (window as WindowWithGoogleDocsBridgeClient)+ .__harperGoogleDocsBridgeClient;+ if (bridgeClient && typeof bridgeClient.replaceText === 'function') {+ void Promise.resolve(+ bridgeClient.replaceText(+ payload.start,+ payload.end,+ payload.replacementText,+ payload.expectedText,+ payload.beforeContext,+ payload.afterContext,+ ),+ );+ }+ } catch {+ // Ignore bridge dispatch failures.+ }+}diff --git a/packages/lint-framework/src/lint/computeLintBoxes.ts b/packages/lint-framework/src/lint/computeLintBoxes/index.tssimilarity index 69%rename from packages/lint-framework/src/lint/computeLintBoxes.tsrename to packages/lint-framework/src/lint/computeLintBoxes/index.tsindex d8f81122b..41372d0bb 100644--- a/packages/lint-framework/src/lint/computeLintBoxes.ts+++ b/packages/lint-framework/src/lint/computeLintBoxes/index.ts@@ -1,6 +1,6 @@import { type Span, SuggestionKind } from 'harper.js';-import { domRectToBox, type IgnorableLintBox, isBottomEdgeInBox, shrinkBoxToFit } from './Box';-import { getRangeForTextSpan } from './domUtils';+import { domRectToBox, type IgnorableLintBox, isBottomEdgeInBox, shrinkBoxToFit } from '../Box';+import { getRangeForTextSpan } from '../domUtils';import {getCkEditorRoot,getCMRoot,@@ -8,49 +8,32 @@ import {getLexicalRoot,getSlateRoot,isFormEl,-} from './editorUtils';-import TextFieldRange from './TextFieldRange';+} from '../editorUtils';+import { maybeComputeGoogleDocsLintBoxes } from '../googleDocsAdapter';+import TextFieldRange from '../TextFieldRange';import {applySuggestion,type UnpackedLint,type UnpackedSpan,type UnpackedSuggestion,-} from './unpackLint';--const GOOGLE_DOCS_EDITOR_SELECTOR = '.kix-appview-editor';--type GoogleDocsReplacePayload = {- start: number;- end: number;- replacementText: string;- expectedText: string;- beforeContext: string;- afterContext: string;-};--type GoogleDocsBridgeClientLike = {- replaceText: (- start: number,- end: number,- replacementText: string,- expectedText?: string,- beforeContext?: string,- afterContext?: string,- ) => Promise<unknown> | unknown;-};--type WindowWithGoogleDocsBridgeClient = Window & {- __harperGoogleDocsBridgeClient?: GoogleDocsBridgeClientLike;-};-+} from '../unpackLint';++/**+ * Converts a lint span into one or more on-screen boxes for the active editor.+ *+ * Most editors use the generic DOM/range-based path. Google Docs is delegated to+ * the Google Docs adapter, which handles its mirrored bridge target and editor-specific+ * geometry rules.+ */export default function computeLintBoxes(el: HTMLElement,lint: UnpackedLint,rule: string,opts: { ignoreLint?: (hash: string) => Promise<void> },): IgnorableLintBox[] {- if (isGoogleDocsTarget(el)) {- return computeGoogleDocsLintBoxes(el, lint, rule, opts);+ const googleDocsBoxes = maybeComputeGoogleDocsLintBoxes(el, lint, rule, opts);+ if (googleDocsBoxes != null) {+ return googleDocsBoxes;}try {@@ -118,66 +101,6 @@ export default function computeLintBoxes(}}-function isGoogleDocsTarget(el: HTMLElement): boolean {- return el.getAttribute('data-harper-google-docs-target') === 'true';-}--function computeGoogleDocsLintBoxes(- target: HTMLElement,- lint: UnpackedLint,- rule: string,- opts: { ignoreLint?: (hash: string) => Promise<void> },-): IgnorableLintBox[] {- try {- const editor = document.querySelector(GOOGLE_DOCS_EDITOR_SELECTOR) as HTMLElement | null;- const source = target.textContent ?? '';-- if (!editor) {- return [];- }-- if (lint.source !== source) {- return [];- }-- const range = getRangeForTextSpan(target, lint.span as Span);- if (!range) {- return [];- }-- const targetRects = Array.from(range.getClientRects ? range.getClientRects() : []);- const elBox = domRectToBox(range.getBoundingClientRect());- (range as any).detach?.();-- const boxes: IgnorableLintBox[] = [];- for (const targetRect of targetRects as DOMRect[]) {- if (!isBottomEdgeInBox(targetRect, elBox)) {- continue;- }-- const shrunkBox = shrinkBoxToFit(targetRect, elBox);- boxes.push({- x: shrunkBox.x,- y: shrunkBox.y,- width: shrunkBox.width,- height: shrunkBox.height,- lint,- source: editor,- rule,- applySuggestion: (sug: UnpackedSuggestion) => {- const replacementText = suggestionToReplacementText(sug, lint.span, source);- replaceGoogleDocsValue(lint.span, replacementText, source);- },- ignoreLint: opts.ignoreLint ? () => opts.ignoreLint!(lint.context_hash) : undefined,- });- }-- return boxes;- } catch {- return [];- }-}-/** Transform an arbitrary suggestion to the equivalent replacement text. */function suggestionToReplacementText(sug: UnpackedSuggestion,@@ -216,48 +139,6 @@ function replaceValue(el.dispatchEvent(new Event('change', { bubbles: true }));}-function replaceGoogleDocsValue(- span: { start: number; end: number },- replacementText: string,- source: string,-) {- try {- const safeStart = Math.max(0, Math.min(span.start, source.length));- const safeEnd = Math.max(safeStart, Math.min(span.end, source.length));- const expectedText = source.slice(safeStart, safeEnd);- const contextRadius = 64;- const beforeContext = source.slice(Math.max(0, safeStart - contextRadius), safeStart);- const afterContext = source.slice(safeEnd, Math.min(source.length, safeEnd + contextRadius));-- const payload: GoogleDocsReplacePayload = {- start: span.start,- end: span.end,- replacementText,- expectedText,- beforeContext,- afterContext,- };- // This looks awkward because lint-framework cannot import chrome-plugin code directly.- // The content script puts the bridge client on window so this shared package can call it.- const bridgeClient = (window as WindowWithGoogleDocsBridgeClient)- .__harperGoogleDocsBridgeClient;- if (bridgeClient && typeof bridgeClient.replaceText === 'function') {- void Promise.resolve(- bridgeClient.replaceText(- payload.start,- payload.end,- payload.replacementText,- payload.expectedText,- payload.beforeContext,- payload.afterContext,- ),- );- }- } catch {- // Ignore bridge dispatch failures.- }-}-function replaceFormElementValue(el: HTMLTextAreaElement | HTMLInputElement,span: { start: number; end: number },diff --git a/packages/lint-framework/src/lint/googleDocsAdapter.ts b/packages/lint-framework/src/lint/googleDocsAdapter.tsnew file mode 100644index 000000000..4fc31c8dc--- /dev/null+++ b/packages/lint-framework/src/lint/googleDocsAdapter.ts@@ -0,0 +1,154 @@+import { type Span, SuggestionKind } from 'harper.js';+import { domRectToBox, type IgnorableLintBox, isBottomEdgeInBox, shrinkBoxToFit } from './Box';+import {+ getGoogleDocsHighlightRects,+ isGoogleDocsTarget,+ replaceGoogleDocsValue,+ resolveGoogleDocsSpan,+} from './computeLintBoxes/googleDocsUtilities';+import type SourceElement from './SourceElement';+import type { UnpackedLint, UnpackedSpan, UnpackedSuggestion } from './unpackLint';++const GOOGLE_DOCS_EDITOR_SELECTOR = '.kix-appview-editor';+const GOOGLE_DOCS_SYNCING_ATTR = 'data-harper-gdocs-syncing';++/**+ * Returns Google Docs-specific lint boxes for the hidden bridge target.+ *+ * Non-Google Docs targets return `null` so callers can continue down the generic+ * lint-box pipeline without duplicating source checks.+ */+export function maybeComputeGoogleDocsLintBoxes(+ target: HTMLElement,+ lint: UnpackedLint,+ rule: string,+ opts: { ignoreLint?: (hash: string) => Promise<void> },+): IgnorableLintBox[] | null {+ if (!isGoogleDocsTarget(target)) {+ return null;+ }++ try {+ const editor = document.querySelector(GOOGLE_DOCS_EDITOR_SELECTOR) as HTMLElement | null;+ const source = target.textContent ?? '';+ const resolvedSpan = resolveGoogleDocsSpan(source, lint);++ if (!editor || resolvedSpan == null) {+ return [];+ }++ const targetRects = getGoogleDocsHighlightRects(target, resolvedSpan as Span);+ const editorBox = domRectToBox(editor.getBoundingClientRect());+ if (targetRects.length === 0) {+ return [];+ }++ const boxes: IgnorableLintBox[] = [];+ for (const targetRect of targetRects as DOMRect[]) {+ if (!isBottomEdgeInBox(targetRect, editorBox)) {+ continue;+ }++ const shrunkBox = shrinkBoxToFit(targetRect, editorBox);+ boxes.push({+ x: shrunkBox.x,+ y: shrunkBox.y,+ width: shrunkBox.width,+ height: shrunkBox.height,+ lint,+ source: editor,+ rule,+ applySuggestion: (suggestion: UnpackedSuggestion) => {+ const replacementText = suggestionToReplacementText(suggestion, resolvedSpan, source);+ replaceGoogleDocsValue(resolvedSpan, replacementText, source);+ },+ ignoreLint: opts.ignoreLint ? () => opts.ignoreLint!(lint.context_hash) : undefined,+ });+ }++ return boxes;+ } catch {+ return [];+ }+}++/**+ * Narrows a render or lint source to the live Google Docs editor container.+ */+export function isGoogleDocsSource(source: SourceElement): source is HTMLElement {+ return (+ source instanceof HTMLElement &&+ (source.classList.contains('kix-appview-editor') ||+ source.closest(GOOGLE_DOCS_EDITOR_SELECTOR) != null)+ );+}++/**+ * Reports whether Google Docs is in the middle of a bridge sync and highlights+ * should preserve their current rendered state.+ */+export function isGoogleDocsSourceSyncing(source: SourceElement): boolean {+ return isGoogleDocsSource(source) && source.getAttribute(GOOGLE_DOCS_SYNCING_ATTR) === 'true';+}++/**+ * Returns the element that should own rendered highlight boxes for a Google Docs source.+ */+export function getGoogleDocsRenderTarget(source: SourceElement): HTMLElement | null {+ return isGoogleDocsSource(source) ? source : null;+}++/**+ * Computes the absolute render offset for highlight boxes anchored to the+ * scrolling Google Docs editor surface.+ */+export function getGoogleDocsRenderOffset(source: SourceElement): { x: number; y: number } | null {+ if (!isGoogleDocsSource(source)) {+ return null;+ }++ const editorRect = source.getBoundingClientRect();++ return {+ x: editorRect.x - source.scrollLeft,+ y: editorRect.y - source.scrollTop,+ };+}++/**+ * Applies the host positioning required for Google Docs highlights.+ *+ * Returns `true` when the source was recognized as Google Docs and the caller+ * should skip its generic host styling path.+ */+export function applyGoogleDocsRenderHostStyle(host: HTMLElement, source: SourceElement): boolean {+ if (!isGoogleDocsSource(source)) {+ return false;+ }++ host.style.position = 'absolute';+ host.style.top = '0px';+ host.style.left = '0px';+ host.style.pointerEvents = 'none';+ host.style.width = '0px';+ host.style.height = '0px';+ host.style.contain = 'none';+ host.style.transform = 'none';+ host.style.zIndex = '2147483647';+ return true;+}++function suggestionToReplacementText(+ suggestion: UnpackedSuggestion,+ span: UnpackedSpan,+ source: string,+): string {+ switch (suggestion.kind) {+ case SuggestionKind.Replace:+ return suggestion.replacement_text;+ case SuggestionKind.Remove:+ return '';+ case SuggestionKind.InsertAfter:+ return source.slice(span.start, span.end) + suggestion.replacement_text;+ }+}diff --git a/packages/web/src/lib/components/LintCard.svelte b/packages/web/src/lib/components/LintCard.svelteindex b57392fee..1285d4d2a 100644--- a/packages/web/src/lib/components/LintCard.svelte+++ b/packages/web/src/lib/components/LintCard.svelte@@ -27,8 +27,12 @@ function suggestionText(s: UnpackedSuggestion): string {</script><div- class="rounded-lg border border-gray-300 dark:border-gray-700 shadow-sm bg-white dark:bg-[#0d1117]"- on:click={() => focusError?.()}+ class="rounded-lg border border-gray-300 dark:border-gray-700 shadow-sm bg-white dark:bg-[#0d1117]"+ role="button"+ tabindex="0"+ aria-label="Focus lint error"+ on:click={() => focusError?.()}+ on:keydown={(e) => (e.key === 'Enter' || e.key === ' ') && (e.preventDefault(), focusError?.())}><divrole="button"diff --git a/packages/web/src/routes/docs/contributors/chrome-extension/+page.md b/packages/web/src/routes/docs/contributors/chrome-extension/+page.mdindex 7d802aa4d..133d9ea6b 100644--- a/packages/web/src/routes/docs/contributors/chrome-extension/+page.md+++ b/packages/web/src/routes/docs/contributors/chrome-extension/+page.md@@ -68,8 +68,8 @@ That posed a complex problem for us, which is why many of our early users may reGoogle Docs was difficult to support for two simple reasons:-1. It doesn't render to the DOM at all. Instead, Google Docs uses a specialized document renderer called Kix that is composed of a single `<canvas />` element.-1. The API to access the internal document state of Kix existed, but was entirely undocumented.+1. It does not expose a normal editable DOM surface that Harper can lint directly.+1. The APIs that make the document readable and writable are not part of a normal web-editor integration.Our saving grace was the [open-sourcing of Witty Works](https://github.com/witty-works/browser-extension), an inclusive language checker.They figured out a way to access the internal document state, which we took inspiration from.@@ -77,29 +77,26 @@ Here's how it works.### How We Read and Write to Google Docs-To get Google Docs into a readable state, we need to trick it a little bit.-Kix's API is official, but Google provides it to a limited number of "supported" vendors.-In practice, that means that if a user has one of a limited number of Chrome extensions installed, Google Docs will expose it's operable underbelly.-Despite many attempts to get on Google's whitelist, Harper is not one of these extensions.-So we have to trick it.+At a high level, Harper uses three pieces:++1. A small bootstrap script that makes Google Docs enable the extension-facing machinery we need.+1. A main-world bridge script that can talk to Google Docs' internal annotated-text APIs.+1. A hidden mirrored target in the page that the normal lint framework can read from and render against.That's the purpose of the `googleDocsBootstrap.js` content script.It's short, sweet, and to the point:@code(../../../../../../chrome-plugin/src/contentScript/googleDocsBootstrap.js)-All we're doing is telling Google Docs that we're one of the supported extension, even if we technically aren't.--Once our deception is complete, Google Docs will start writing SVG nodes to the DOM, mirroring the text that's being rendered to the `<canvas />` element that we talked about earlier.+After that, Harper injects `google-docs-bridge.js` into the page's main world.+We need that because the normal extension content script runs in an isolated world and cannot directly use the Google Docs APIs we rely on.-This is where our bridge comes in.-At the soonest available opportunity, Harper will inject the `google-docs-bridge.js` script into the main world of the session.-We need to do this because normal content scripts are not allowed to read or write to the APIs necessary.-This "bridge" can.+The bridge reads the document's logical text and selection state, watches for layout changes, and exposes enough information for the rest of Harper to work.+Harper then mirrors that state into a hidden target element inside the editor.+That hidden target gives the lint framework something stable to lint, while the visible Google Docs layout is still used to place highlights in the right location.-I thoroughly encourage you to read the actual source code or reach out if you have any questions.-In short, though, the bridge maintains a mirrored version of the Google Docs state, one that is readable by the normal lint framework.-In other words, it acts as middleman between the rest of the Chrome extension and Google Docs, allowing most of the existing code to be able to treat Google Docs the same way it would treat any other text editor on the web.+Suggestion application also goes back through the bridge.+In other words, the bridge is the adapter between Google Docs' internal editor model and Harper's normal browser linting flow.## Other Readingdiff --git a/packages/web/src/routes/uninstall-browser-extension/+page.svelte b/packages/web/src/routes/uninstall-browser-extension/+page.svelteindex 7218c9ca2..6ef11a025 100644--- a/packages/web/src/routes/uninstall-browser-extension/+page.svelte+++ b/packages/web/src/routes/uninstall-browser-extension/+page.svelte@@ -24,30 +24,36 @@ function handleFormData(e: FormDataEvent) {</script><Isolate>- <div class="flex flex-row justify-center items-center h-screen">- <Card>- <h1 class="text-3xl font-semibold">Uninstalling Harper</h1> <p class="text-sm text-gray-600">We’re sorry to see you go. If you have a minute, would you mind telling us why you uninstalled our browser extension?</p>- <form method="POST" class="mt-4 space-y-6" action="/api/uninstall-feedback" on:formdata={handleFormData}>- <div class="space-y-3">- <div class="flex items-baseline gap-2">- <Label>Why did you uninstall Harper?</Label>- </div>-- <div class="space-y-3">- {#each Object.entries(reasons) as [k, r], i}- <Radio value={k} name="feedback">{r}</Radio>- {/each}-- <Radio name="feedback" value="other" bind:group={otherSelected}>Other</Radio>- {#if otherSelected}- <Input name="other" bind:value={otherText} placeholder="Your answer" />- {/if}- </div>-- <div class="flex items-center justify-between pt-2">- <Button type="submit">Submit</Button>- </div>- </form>- </Card>- </div>+ <div class="flex h-screen flex-row items-center justify-center">+ <Card>+ <h1 class="text-3xl font-semibold">Uninstalling Harper</h1>+ <p class="text-sm text-gray-600">+ We’re sorry to see you go. If you have a minute, would you mind telling us why you+ uninstalled our browser extension?+ </p>++ <form method="POST" class="mt-4 space-y-6" action="/api/uninstall-feedback" on:formdata={handleFormData}>+ <div class="space-y-3">+ <div class="flex items-baseline gap-2">+ <Label>Why did you uninstall Harper?</Label>+ </div>++ <div class="space-y-3">+ {#each Object.entries(reasons) as [k, r]}+ <Radio value={k} name="feedback">{r}</Radio>+ {/each}++ <Radio name="feedback" value="other" bind:group={otherSelected}>Other</Radio>+ {#if otherSelected}+ <Input name="other" bind:value={otherText} placeholder="Your answer" />+ {/if}+ </div>+ </div>++ <div class="flex items-center justify-between pt-2">+ <Button type="submit">Submit</Button>+ </div>+ </form>+ </Card>+ </div></Isolate>