Offline, privacy-first grammar checker. Fast, open-source, Rust-powered
feat(chrome-ext): support for Google Docs (#2791)
Elijah Potterbcfc612ae7a6
diff --git a/packages/chrome-plugin/package.json b/packages/chrome-plugin/package.jsonindex 42b819437..ed75d10b3 100644--- a/packages/chrome-plugin/package.json+++ b/packages/chrome-plugin/package.json@@ -25,7 +25,7 @@"test": "playwright test --headed --reporter=dot"},"devDependencies": {- "@crxjs/vite-plugin": "^2.0.0-beta.26",+ "@crxjs/vite-plugin": "^2.3.0","@playwright/test": "^1.58.0","@sveltejs/vite-plugin-svelte": "^4.0.0","@types/chrome": "^0.0.246",diff --git a/packages/chrome-plugin/public/google-docs-bridge-request-handler.js b/packages/chrome-plugin/public/google-docs-bridge-request-handler.jsnew file mode 100644index 000000000..9b34fb834--- /dev/null+++ b/packages/chrome-plugin/public/google-docs-bridge-request-handler.js@@ -0,0 +1,141 @@+/**+ * LSP type-import marker for shared protocol typedefs.+ * @typedef {import('./google-docs-protocol.js').GoogleDocsGetRectsRequest} GoogleDocsGetRectsRequest+ * @typedef {import('./google-docs-protocol.js').GoogleDocsReplaceTextRequest} GoogleDocsReplaceTextRequest+ * @typedef {import('./google-docs-protocol.js').GoogleDocsRequest} GoogleDocsRequest+ * @typedef {import('./google-docs-protocol.js').GoogleDocsRequestMessage} GoogleDocsRequestMessage+ * @typedef {import('./google-docs-protocol.js').GoogleDocsResponse} GoogleDocsResponse+ * @typedef {import('./google-docs-protocol.js').GoogleDocsResponseMessage} GoogleDocsResponseMessage+ */++const PROTOCOL_VERSION = 'harper-gdocs-bridge/v1';+const EVENT_REQUEST = 'harper:gdocs:request';+const EVENT_RESPONSE = 'harper:gdocs:response';++/**+ * @callback GoogleDocsGetRectsRequestHandler+ * @param {GoogleDocsGetRectsRequest} request+ * @returns {Promise<GoogleDocsResponse>|GoogleDocsResponse}+ */++/**+ * @callback GoogleDocsReplaceTextRequestHandler+ * @param {GoogleDocsReplaceTextRequest} request+ * @returns {Promise<GoogleDocsResponse>|GoogleDocsResponse}+ */++/**+ * Request dispatcher used by the Google Docs bridge (main-world script).+ * It mirrors the background-script style of request handling.+ */+export class GoogleDocsBridgeRequestHandler {+ /**+ * @param {{+ * onGetRectsRequest: GoogleDocsGetRectsRequestHandler,+ * onReplaceTextRequest: GoogleDocsReplaceTextRequestHandler+ * }} handlers+ */+ constructor(handlers) {+ this.handlers = handlers;+ this.onRequestEventBound = this.onRequestEvent.bind(this);+ }++ start() {+ document.addEventListener(EVENT_REQUEST, this.onRequestEventBound);+ }++ stop() {+ document.removeEventListener(EVENT_REQUEST, this.onRequestEventBound);+ }++ /**+ * @param {Event} event+ */+ async onRequestEvent(event) {+ const detail = /** @type {CustomEvent} */ (event).detail;+ if (!this.isRequestMessage(detail)) {+ return;+ }++ const requestMessage = /** @type {GoogleDocsRequestMessage} */ (detail);+ const { request } = requestMessage;+ try {+ if (request.kind === 'getRects') {+ const response = await this.handlers.onGetRectsRequest(request);+ this.sendResponse(requestMessage.requestId, response);+ return;+ }++ if (request.kind === 'replaceText') {+ const response = await this.handlers.onReplaceTextRequest(request);+ this.sendResponse(requestMessage.requestId, response);+ return;+ }++ this.sendErrorResponse(+ requestMessage.requestId,+ request.kind,+ 'unsupported_request',+ 'Unsupported request kind',+ );+ } catch (err) {+ this.sendErrorResponse(+ requestMessage.requestId,+ request.kind,+ 'handler_error',+ err instanceof Error ? err.message : 'Unknown bridge handler error',+ );+ }+ }++ /**+ * @param {string} requestId+ * @param {GoogleDocsResponse} response+ */+ sendResponse(requestId, response) {+ /** @type {GoogleDocsResponseMessage} */+ const message = {+ protocol: PROTOCOL_VERSION,+ requestId,+ response,+ };+ document.dispatchEvent(new CustomEvent(EVENT_RESPONSE, { detail: message }));+ }++ /**+ * @param {string} requestId+ * @param {GoogleDocsRequest['kind']} requestKind+ * @param {string} code+ * @param {string} message+ */+ sendErrorResponse(requestId, requestKind, code, message) {+ this.sendResponse(requestId, {+ kind: 'error',+ requestKind,+ code,+ message,+ });+ }++ /**+ * @param {unknown} value+ * @returns {value is GoogleDocsRequestMessage}+ */+ isRequestMessage(value) {+ if (!this.isObject(value)) return false;+ return (+ value.protocol === PROTOCOL_VERSION &&+ typeof value.requestId === 'string' &&+ this.isObject(value.request) &&+ typeof value.request.kind === 'string'+ );+ }++ /**+ * @param {unknown} value+ * @returns {value is Record<string, unknown>}+ */+ isObject(value) {+ return value != null && typeof value === 'object';+ }+}diff --git a/packages/chrome-plugin/public/google-docs-bridge.js b/packages/chrome-plugin/public/google-docs-bridge.jsnew file mode 100644index 000000000..e45681f65--- /dev/null+++ b/packages/chrome-plugin/public/google-docs-bridge.js@@ -0,0 +1,598 @@+import { GoogleDocsBridgeRequestHandler } from './google-docs-bridge-request-handler.js';++(() => {+ /**+ * @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+ */++ const PROTOCOL_VERSION = 'harper-gdocs-bridge/v1';+ const BRIDGE_ID = 'harper-google-docs-main-world-bridge';+ const SYNC_INTERVAL_MS = 100;+ const EDITOR_SELECTOR = '.kix-appview-editor';+ const EDITOR_CONTAINER_SELECTOR = '.kix-appview-editor-container';+ const DOCS_EDITOR_SELECTOR = '#docs-editor';+ const CARET_SELECTOR = '.kix-cursor-caret';+ const TEXT_EVENT_IFRAME_SELECTOR = '.docs-texteventtarget-iframe';+ const LAYOUT_EPOCH_ATTR = 'data-harper-layout-epoch';+ const LAYOUT_REASON_ATTR = 'data-harper-layout-reason';+ const SELECTION_START_ATTR = 'data-harper-selection-start';+ const SELECTION_END_ATTR = 'data-harper-selection-end';+ const EVENT_NOTIFICATION = 'harper:gdocs:notification';+ const EVENT_TEXT_UPDATED = 'harper:gdocs:text-updated';+ const 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);++ /** @returns {HTMLElement} */+ function ensureBridgeExists() {+ if (bridge) {+ return bridge;+ }++ const nextBridge = document.createElement('div');+ nextBridge.id = BRIDGE_ID;+ nextBridge.setAttribute('aria-hidden', 'true');+ nextBridge.style.display = 'none';+ document.documentElement.appendChild(nextBridge);+ bridge = nextBridge;++ return nextBridge;+ }++ ensureBridgeExists();++ /** @param {string} name+ * @param {Record<string, unknown>} detail+ * @returns {void}+ */+ const emitEvent = (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 {}+ };++ /**+ * @param {string} reason+ * @returns {void}+ */+ const bumpLayoutEpoch = (reason) => {+ if (layoutBumpPending) return;+ layoutBumpPending = true;+ queueMicrotask(() => {+ layoutBumpPending = 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 });+ });+ };++ /** @returns {Promise<void>} */+ const syncText = async () => {+ try {+ const getAnnotatedText = window._docs_annotate_getAnnotatedText;+ if (typeof getAnnotatedText !== 'function') return;+ /** @type {AnnotatedText | null | undefined} */+ const annotated = await getAnnotatedText();+ if (!annotated || typeof annotated.getText !== 'function') return;+ 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);+ }+ } 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 });+ }+ } catch {}+ };++ /**+ * @param {AnnotatedText} annotated+ * @param {number} position+ * @returns {Rect | null}+ */+ const getCaretRect = (annotated, position) => {+ annotated.setSelection(position, position);+ 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 =+ 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+ ) {+ return null;+ }+ 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;+ 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 deltaPos = position - lastCaretChoice.position;+ let chosen = 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 (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]);+ }+ } 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) => {+ 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]);+ }+ }++ if (!chosen) {+ chosen = pool.reduce((best, rect) => {+ const bestScore =+ Math.abs(best.y - lastCaretChoice.rect.y) * 4 + Math.abs(best.x - lastCaretChoice.rect.x);+ const rectScore =+ Math.abs(rect.y - lastCaretChoice.rect.y) * 4 + Math.abs(rect.x - lastCaretChoice.rect.x);+ return rectScore < bestScore ? rect : best;+ }, 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'],+ ];++ for (const [a, b] of candidates) {+ const start = asFiniteNumber(selection[a]);+ const end = asFiniteNumber(selection[b]);+ if (start != null && end != null) {+ return { start, end };+ }+ }++ 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 {}+ };++ /**+ * @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 maxDistance = 2000;++ if (spanStart <= selEnd && spanEnd >= selStart) {+ return true;+ }+ if (spanEnd < selStart) {+ return selStart - spanEnd <= maxDistance;+ }+ return spanStart - selEnd <= maxDistance;+ };++ /**+ * @typedef {{+ * node: Window | Element,+ * left: number,+ * top: number+ * }} ScrollSnapshot+ */++ /**+ * @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 });+ }+ 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);+ }+ continue;+ }+ if (!(snap.node instanceof Element)) continue;+ if (snap.node.scrollLeft !== snap.left) {+ snap.node.scrollLeft = snap.left;+ }+ if (snap.node.scrollTop !== snap.top) {+ snap.node.scrollTop = snap.top;+ }+ }+ };++ /**+ * @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');++ try {+ return fn();+ } finally {+ for (let i = restorers.length - 1; i >= 0; i -= 1) {+ restorers[i]();+ }+ }+ };++ /**+ * @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 (!annotated || typeof annotated.setSelection !== 'function') {+ return { kind: 'getRects', rects: [] };+ }++ const currentSelection = annotated.getSelection?.()?.[0];+ const previousSelection = getSelectionEndpoints(currentSelection);+ if (!isSpanNearSelection(start, end, previousSelection)) {+ return { kind: 'getRects', rects: [] };+ }++ /** @type {Rect[]} */+ const rects = [];+ isComputingRects = true;+ const scrollSnapshot = 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),+ };+ });++ if (startRect && endRect && Math.abs(startRect.y - endRect.y) < 6) {+ rects.push({+ x: Math.min(startRect.x, endRect.x),+ y: startRect.y,+ width: Math.max(4, Math.abs(endRect.x - startRect.x)),+ height: startRect.height,+ });+ } else if (startRect) {+ rects.push({+ x: startRect.x,+ y: startRect.y,+ width: 8,+ height: startRect.height,+ });+ }+ } finally {+ isComputingRects = false;+ restoreSelection(annotated, previousSelection);+ restoreScroll(scrollSnapshot);+ requestAnimationFrame(() => restoreScroll(scrollSnapshot));+ }++ 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') {+ 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;+ }+ }+ }+ }++ annotated.setSelection(start, end);+ const iframe = document.querySelector(TEXT_EVENT_IFRAME_SELECTOR);+ const target = iframe?.contentDocument?.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 };+ };++ const requestHandler = new GoogleDocsBridgeRequestHandler({+ onGetRectsRequest: handleGetRectsRequest,+ onReplaceTextRequest: handleReplaceTextRequest,+ });+ 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);+ 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'],+ });+ };++ observeLayout();+ syncText();+ setInterval(syncText, SYNC_INTERVAL_MS);+})();diff --git a/packages/chrome-plugin/public/google-docs-protocol.js b/packages/chrome-plugin/public/google-docs-protocol.jsnew file mode 100644index 000000000..f845616e1--- /dev/null+++ b/packages/chrome-plugin/public/google-docs-protocol.js@@ -0,0 +1,115 @@+/**+ * Type-only protocol specification for Google Docs bridge communication.+ *+ * This mirrors `protocol.ts` style:+ * - A single list of request and response types.+ * - No runtime code or constants.+ * - Transport details are handled by client/handler implementations.+ */++/**+ * A rectangle in viewport coordinates.+ * @typedef {object} GoogleDocsRect+ * @property {number} x Left coordinate in CSS pixels.+ * @property {number} y Top coordinate in CSS pixels.+ * @property {number} width Width in CSS pixels.+ * @property {number} height Height in CSS pixels.+ */++/**+ * Request to resolve rects for a text span.+ * @typedef {object} GoogleDocsGetRectsRequest+ * @property {'getRects'} kind Request kind.+ * @property {number} start Start offset in bridge text.+ * @property {number} end End offset in bridge text.+ */++/**+ * Request to replace text in Google Docs.+ * @typedef {object} GoogleDocsReplaceTextRequest+ * @property {'replaceText'} kind Request kind.+ * @property {number} start Start offset in bridge text.+ * @property {number} end End offset in bridge text.+ * @property {string} replacementText Replacement text.+ * @property {string=} expectedText Optional expected source text for defensive re-alignment.+ * @property {string=} beforeContext Optional context before the span for re-alignment scoring.+ * @property {string=} afterContext Optional context after the span for re-alignment scoring.+ */++/**+ * All supported bridge requests.+ * @typedef {GoogleDocsGetRectsRequest | GoogleDocsReplaceTextRequest} GoogleDocsRequest+ */++/**+ * Successful response for `getRects`.+ * @typedef {object} GoogleDocsGetRectsResponse+ * @property {'getRects'} kind Response kind.+ * @property {GoogleDocsRect[]} rects Resolved span rects.+ */++/**+ * Successful response for `replaceText`.+ * @typedef {object} GoogleDocsReplaceTextResponse+ * @property {'replaceText'} kind Response kind.+ * @property {boolean} applied Whether the bridge dispatched the edit operation to Docs.+ */++/**+ * Error response for any request.+ * @typedef {object} GoogleDocsErrorResponse+ * @property {'error'} kind Response kind.+ * @property {GoogleDocsRequest['kind']} requestKind Kind of request that failed.+ * @property {string} code Machine-readable error code.+ * @property {string} message Human-readable error message.+ */++/**+ * All bridge responses.+ * @typedef {GoogleDocsGetRectsResponse | GoogleDocsReplaceTextResponse | GoogleDocsErrorResponse} GoogleDocsResponse+ */++/**+ * Notification when bridge text changes.+ * @typedef {object} GoogleDocsTextUpdatedNotification+ * @property {'textUpdated'} kind Notification kind.+ * @property {number} length Current bridge text length.+ */++/**+ * Notification when bridge layout changes.+ * @typedef {object} GoogleDocsLayoutChangedNotification+ * @property {'layoutChanged'} kind Notification kind.+ * @property {number} layoutEpoch Monotonic layout epoch.+ * @property {string} reason Layout change reason.+ */++/**+ * All bridge notifications.+ * @typedef {GoogleDocsTextUpdatedNotification | GoogleDocsLayoutChangedNotification} GoogleDocsNotification+ */++/**+ * Transport envelope for a request event.+ * @typedef {object} GoogleDocsRequestMessage+ * @property {string} protocol Protocol version string.+ * @property {string} requestId Correlation id for request/response pairing.+ * @property {GoogleDocsRequest} request Request payload.+ */++/**+ * Transport envelope for a response event.+ * @typedef {object} GoogleDocsResponseMessage+ * @property {string} protocol Protocol version string.+ * @property {string} requestId Correlation id matching a prior request.+ * @property {GoogleDocsResponse} response Response payload.+ */++/**+ * Transport envelope for a notification event.+ * @typedef {object} GoogleDocsNotificationMessage+ * @property {string} protocol Protocol version string.+ * @property {GoogleDocsNotification} notification Notification payload.+ */++export {};diff --git a/packages/chrome-plugin/src/background/index.ts b/packages/chrome-plugin/src/background/index.tsindex 46dbcd15d..9e4d402d0 100644--- a/packages/chrome-plugin/src/background/index.ts+++ b/packages/chrome-plugin/src/background/index.ts@@ -124,6 +124,7 @@ async function enableDefaultDomains() {'ckeditor.com','app.slack.com','openrouter.ai',+ 'docs.google.com','typst.app',];diff --git a/packages/chrome-plugin/src/contentScript/GoogleDocsBridgeClient.ts b/packages/chrome-plugin/src/contentScript/GoogleDocsBridgeClient.tsnew file mode 100644index 000000000..2594317d9--- /dev/null+++ b/packages/chrome-plugin/src/contentScript/GoogleDocsBridgeClient.ts@@ -0,0 +1,193 @@+// @ts-nocheck++import type {+ GoogleDocsGetRectsResponse,+ GoogleDocsNotificationMessage,+ GoogleDocsRect,+ GoogleDocsRequest,+ GoogleDocsRequestMessage,+ GoogleDocsResponse,+ GoogleDocsResponseMessage,+} from '../../public/google-docs-protocol.js';++type PendingRequest = {+ resolve: (value: GoogleDocsResponse) => void;+ reject: (reason?: unknown) => void;+ timerId: 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';++/** Content-script client for Google Docs bridge request/response + notifications. */+export default class GoogleDocsBridgeClient {+ private readonly documentRef: Document;+ private readonly timeoutMs: number;+ private readonly pending = new Map<string, PendingRequest>();+ 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) {+ this.documentRef = documentRef;+ this.timeoutMs = timeoutMs;+ this.onResponseBound = this.onResponse.bind(this);+ this.onNotificationBound = this.onNotification.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`));+ }+ this.pending.clear();+ this.textUpdatedListeners.clear();+ this.layoutChangedListeners.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,+ replacementText: string,+ expectedText?: string,+ beforeContext?: string,+ afterContext?: string,+ ): Promise<boolean> {+ const response = await this.request({+ kind: 'replaceText',+ start,+ end,+ replacementText,+ expectedText,+ 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);+ }++ /** 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);+ }++ /** 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 = {+ protocol: PROTOCOL_VERSION,+ requestId,+ request,+ };++ return new Promise((resolve, reject) => {+ const timerId = window.setTimeout(() => {+ this.pending.delete(requestId);+ reject(new Error(`Google Docs bridge request "${request.kind}" timed out`));+ }, this.timeoutMs);++ this.pending.set(requestId, { resolve, reject, timerId });+ this.documentRef.dispatchEvent(new CustomEvent(EVENT_REQUEST, { detail: message }));+ });+ }++ /** Route bridge responses to the matching pending request. */+ private onResponse(event: Event) {+ const detail = (event as CustomEvent).detail;+ if (!this.isResponseMessage(detail)) {+ return;+ }++ const pending = this.pending.get(detail.requestId);+ if (!pending) {+ return;+ }++ this.pending.delete(detail.requestId);+ clearTimeout(pending.timerId);+ if (detail.response.kind === 'error') {+ pending.reject(new Error(detail.response.message || 'Google Docs bridge request failed'));+ return;+ }++ pending.resolve(detail.response);+ }++ /** Route bridge notifications to local subscribers. */+ private onNotification(event: Event) {+ const detail = (event as CustomEvent).detail;+ if (!this.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);+ }+ }+ }++ /** 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.tsnew file mode 100644index 000000000..a6235e860--- /dev/null+++ b/packages/chrome-plugin/src/contentScript/googleDocs.ts@@ -0,0 +1,323 @@+import type { LintFramework } from 'lint-framework';+import GoogleDocsBridgeClient from './GoogleDocsBridgeClient';++declare global {+ interface Window {+ __harperGoogleDocsBridgeClient?: GoogleDocsBridgeClient;+ }+}++const GOOGLE_DOCS_BRIDGE_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_LINE_BREAK_THRESHOLD_PX = 6;+const GOOGLE_DOCS_TABLE_CELL_GAP_THRESHOLD_PX = 60;++type LayoutRefreshFramework = LintFramework & {+ refreshLayout?: () => void;+};++export function isGoogleDocsPage(): boolean {+ return (+ window.location.hostname === 'docs.google.com' &&+ window.location.pathname.startsWith('/document/')+ );+}++/**+ * 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');+ editor.appendChild(bridge);+ }++ if (bridge.parentElement !== editor) {+ editor.appendChild(bridge);+ }++ return bridge;+ }++ /**+ * 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)) {+ 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();+ }++ /**+ * 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) {+ return;+ }++ googleDocsEventsBound = true;+ googleDocsBridgeClient = new GoogleDocsBridgeClient(document);+ window.__harperGoogleDocsBridgeClient = googleDocsBridgeClient;+ googleDocsBridgeClient.onTextUpdated(() => {+ void syncGoogleDocsBridge();+ });+ googleDocsBridgeClient.onLayoutChanged((reason) => {+ if (!GOOGLE_DOCS_SCROLL_LAYOUT_REASONS.has(String(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';+ continue;+ }++ if (token.length === 1 && !token.match(/[a-zA-Z]/)) {+ tokens[i] = ` ${token} `;+ 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);++ tokens[i] = !isLast && !keepTightTrailing && !keepTightLeadingNext ? `${token} ` : token;+ }++ return tokens.join('');+ }++ /**+ * 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;+ }+ return next;+ }++ /**+ * 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);+ const editorRect = editor.getBoundingClientRect();+ const scrollTop = editor.scrollTop;+ const scrollLeft = editor.scrollLeft;+ const fragment = document.createDocumentFragment();+ const parts: string[] = [];+ let nextHash = 5381;+ let lastTop: number | null = null;+ let lastRight: number | null = null;+ let segmentCount = 0;++ for (const rectNode of Array.from(rectNodes)) {+ const areaLabel = rectNode.getAttribute('aria-label');+ if (!areaLabel) continue;++ const normalizedLabel = normalizeGoogleDocsLabel(areaLabel);+ if (!normalizedLabel) continue;++ 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;++ if (lastTop != null && Math.abs(top - lastTop) >= GOOGLE_DOCS_LINE_BREAK_THRESHOLD_PX) {+ if (parts.length > 0 && !parts[parts.length - 1].endsWith('\n')) {+ parts.push('\n');+ fragment.appendChild(document.createTextNode('\n'));+ }+ }+ if (+ lastTop != null &&+ lastRight != null &&+ Math.abs(top - lastTop) < GOOGLE_DOCS_LINE_BREAK_THRESHOLD_PX &&+ left - lastRight >= GOOGLE_DOCS_TABLE_CELL_GAP_THRESHOLD_PX+ ) {+ if (parts.length > 0 && !parts[parts.length - 1].endsWith('\n')) {+ parts.push('\n');+ fragment.appendChild(document.createTextNode('\n'));+ }+ }++ 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);+ lastTop = top;+ lastRight = right;+ segmentCount += 1;++ nextHash = addHashToken(nextHash, normalizedLabel);+ nextHash = addHashToken(+ nextHash,+ `${Math.round(top)}:${Math.round(left)}:${Math.round(rect.width)}`,+ );+ }++ const nextText = parts.join('');+ nextHash = addHashToken(+ nextHash,+ `${nextText.length}:${segmentCount}:${Math.round(scrollTop)}`,+ );+ const nextSignature = String(nextHash);+ if (nextSignature === googleDocsCloneSignature && clone.textContent === nextText) {+ return { changed: false };+ }++ clone.replaceChildren(fragment);+ clone.setAttribute('data-harper-gdocs-segments', String(segmentCount));+ googleDocsCloneSignature = nextSignature;+ return { changed: 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;+ return;+ }++ if (googleDocsSyncInFlight) {+ googleDocsSyncPending = true;+ return;+ }++ googleDocsSyncInFlight = true;++ try {+ ensureGoogleDocsMainWorldBridge();+ bindGoogleDocsBridgeEvents(syncGoogleDocsBridge);++ const editor = document.querySelector(GOOGLE_DOCS_EDITOR_SELECTOR);+ if (!(editor instanceof HTMLElement)) {+ return;+ }+ const target = getGoogleDocsBridge(editor);+ const { changed } = rebuildGoogleDocsClone(editor, target);++ if (!googleDocsBridgeAttached) {+ await fw.addTarget(target);+ googleDocsBridgeAttached = true;+ }++ if (changed) {+ await fw.update();+ }+ } catch (err) {+ console.error('Failed to sync Google Docs bridge text', err);+ } finally {+ googleDocsSyncInFlight = false;++ if (googleDocsSyncPending) {+ googleDocsSyncPending = false;+ void syncGoogleDocsBridge();+ }+ }+ }++ return syncGoogleDocsBridge;+}diff --git a/packages/chrome-plugin/src/contentScript/googleDocsBootstrap.js b/packages/chrome-plugin/src/contentScript/googleDocsBootstrap.jsnew file mode 100644index 000000000..f811bdad2--- /dev/null+++ b/packages/chrome-plugin/src/contentScript/googleDocsBootstrap.js@@ -0,0 +1,7 @@+(() => {+ try {+ // Google Docs checks this main-world flag very early to enable+ // extension-specific annotation/canvas behavior.+ window._docs_annotate_canvas_by_ext = 'hokifickgkhplphjiodbggjmoafhignh';+ } catch {}+})();diff --git a/packages/chrome-plugin/src/contentScript/index.ts b/packages/chrome-plugin/src/contentScript/index.tsindex aee11eadd..a3d1b43a2 100644--- a/packages/chrome-plugin/src/contentScript/index.ts+++ b/packages/chrome-plugin/src/contentScript/index.ts@@ -9,6 +9,7 @@ import {import isSubstack from '../isSubstack';import isWordPress from '../isWordPress';import ProtocolClient from '../ProtocolClient';+import { createGoogleDocsBridgeSync, isGoogleDocsPage } from './googleDocs';if (isWordPress() || isSubstack()) {ProtocolClient.setDomainEnabled(window.location.hostname, true, false);@@ -35,6 +36,8 @@ const fw = new LintFramework(},);+const syncGoogleDocsBridge = createGoogleDocsBridgeSync(fw);+function padWithContext(source: string, start: number, end: number, contextLength: number): string {const normalizedStart = Math.max(0, Math.min(start, source.length));const normalizedEnd = Math.max(normalizedStart, Math.min(end, source.length));@@ -46,6 +49,7 @@ function padWithContext(source: string, start: number, end: number, contextLengtconst keepAliveCallback = () => {ProtocolClient.lint('', 'example.com', {});+ void syncGoogleDocsBridge();setTimeout(keepAliveCallback, 400);};@@ -53,6 +57,12 @@ const keepAliveCallback = () => {keepAliveCallback();function scan() {+ void syncGoogleDocsBridge();++ if (isGoogleDocsPage()) {+ return;+ }+document.querySelectorAll<HTMLTextAreaElement>('textarea').forEach((element) => {if (!isVisible(element) ||@@ -177,6 +187,9 @@ function scan() {}scan();-new MutationObserver(scan).observe(document.body, { childList: true, subtree: true });+new MutationObserver(scan).observe(document.body, {+ childList: true,+ subtree: true,+});setTimeout(scan, 1000);diff --git a/packages/chrome-plugin/src/manifest.ts b/packages/chrome-plugin/src/manifest.tsindex c1a200465..d7eb16785 100644--- a/packages/chrome-plugin/src/manifest.ts+++ b/packages/chrome-plugin/src/manifest.ts@@ -59,6 +59,13 @@ export default defineManifest({type: 'module',},content_scripts: [+ {+ matches: ['https://docs.google.com/document/*'],+ all_frames: false,+ js: ['src/contentScript/googleDocsBootstrap.js'],+ run_at: 'document_start',+ world: 'MAIN',+ },{matches: ['<all_urls>'],all_frames: true,@@ -70,7 +77,12 @@ export default defineManifest({web_accessible_resources: [{matches: ['<all_urls>'],- resources: ['wasm/harper_wasm_bg.wasm'],+ resources: [+ 'wasm/harper_wasm_bg.wasm',+ 'google-docs-bridge.js',+ 'google-docs-protocol.js',+ 'google-docs-bridge-request-handler.js',+ ],},],icons: {diff --git a/packages/chrome-plugin/tests/testUtils.ts b/packages/chrome-plugin/tests/testUtils.tsindex f03903b4b..6d79fee00 100644--- a/packages/chrome-plugin/tests/testUtils.ts+++ b/packages/chrome-plugin/tests/testUtils.ts@@ -73,7 +73,7 @@ export async function clickHarperHighlight(page: Page): Promise<boolean> {// Wait briefly for at least one highlight to appear.// If none appear within a reasonable time, return false.try {- await highlights.first().waitFor({ state: 'visible', timeout: 5000 });+ await highlights.first().waitFor({ state: 'visible', timeout: 12000 });} catch {return false;}@@ -137,6 +137,7 @@ export async function testBasicSuggestion(setup?: (page: Page, editor: Locator) => Promise<void>,) {test('Can apply basic suggestion.', async ({ page }) => {+ test.slow();const url = await resolveTestPage(testPageUrl, page);await page.goto(url);@@ -146,9 +147,8 @@ export async function testBasicSuggestion(}await replaceEditorContent(editor, 'This is an test');- await page.waitForTimeout(6000);-- await clickHarperHighlight(page);+ const opened = await clickHarperHighlight(page);+ expect(opened).toBe(true);await page.getByTitle('Replace with "a"').click();await page.waitForTimeout(3000);@@ -175,6 +175,7 @@ export async function testCanIgnoreSuggestion(setup?: (page: Page, editor: Locator) => Promise<void>,) {test('Can ignore suggestion.', async ({ page }) => {+ test.slow();const url = await resolveTestPage(testPageUrl, page);await page.goto(url);@@ -186,8 +187,6 @@ export async function testCanIgnoreSuggestion(const cacheSalt = randomString(5);await replaceEditorContent(editor, cacheSalt);- await page.waitForTimeout(6000);-// Open the popup for the first highlight and click Ignore.const opened = await clickHarperHighlight(page);expect(opened).toBe(true);@@ -210,6 +209,7 @@ export async function testCanBlockRuleSuggestion(setup?: (page: Page, editor: Locator) => Promise<void>,) {test('Can hide with rule block button', async ({ page }) => {+ test.slow();const url = await resolveTestPage(testPageUrl, page);await page.goto(url);@@ -219,9 +219,8 @@ export async function testCanBlockRuleSuggestion(}await replaceEditorContent(editor, 'This is an test.');- await page.waitForTimeout(6000);-- await clickHarperHighlight(page);+ const opened = await clickHarperHighlight(page);+ expect(opened).toBe(true);await page.getByTitle('Disable the AnA rule').click();diff --git a/packages/lint-framework/src/lint/Highlights.ts b/packages/lint-framework/src/lint/Highlights.tsindex ad23ede04..4d193a74f 100644--- a/packages/lint-framework/src/lint/Highlights.ts+++ b/packages/lint-framework/src/lint/Highlights.ts@@ -112,8 +112,24 @@ export default class Highlights {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 (cpa != null) {+ if (isGoogleDocsSource) {+ const hostStyle = host.style;++ 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';+ } else if (cpa != null) {const hostStyle = host.style;hostStyle.position = 'absolute';@@ -129,17 +145,15 @@ export default class Highlights {host.removeAttribute('style');}- renderBox.render(- this.renderTree(- boxes,- cpa- ? {- x: cpa.x,- y: cpa.y,- }- : null,- ),- );+ const gdocsRenderOffset =+ isGoogleDocsSource && source instanceof HTMLElement+ ? this.getGoogleDocsRenderOffset(source)+ : null;+ const offset =+ gdocsRenderOffset ?? (isGoogleDocsSource || cpa == null ? null : { x: cpa.x, y: cpa.y });+ const boxPosition: 'absolute' | 'fixed' = isGoogleDocsSource ? 'absolute' : 'fixed';++ renderBox.render(this.renderTree(boxes, offset, boxPosition));updated.add(source);}@@ -162,20 +176,37 @@ export default class Highlights {}}- private renderTree(boxes: LintBox[], offset: { x: number; y: number } | null): VNode {+ private renderTree(+ boxes: LintBox[],+ offset: { x: number; y: number } | null,+ boxPosition: 'absolute' | 'fixed',+ ): VNode {const elements = [];const offsetX = offset?.x ?? 0;const offsetY = offset?.y ?? 0;for (const box of boxes) {+ const x = box.x - offsetX;+ const y = box.y - offsetY;+ const positionStyle =+ boxPosition === 'fixed'+ ? {+ position: 'fixed',+ left: '0px',+ top: '0px',+ transform: `translate(${x}px, ${y}px)`,+ }+ : {+ position: 'absolute',+ left: `${x}px`,+ top: `${y}px`,+ };+const boxEl = h('div',{style: {- position: 'fixed',- left: '0px',- top: '0px',- transform: `translate(${box.x - offsetX}px, ${box.y - offsetY}px)`,+ ...positionStyle,width: `${box.width}px`,height: `${box.height}px`,pointerEvents: 'none',@@ -196,6 +227,13 @@ 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;+ }+if (el.parentElement?.classList.contains('ProseMirror')) {return el.parentElement.parentElement!;}@@ -225,6 +263,15 @@ 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 {diff --git a/packages/lint-framework/src/lint/RenderBox.ts b/packages/lint-framework/src/lint/RenderBox.tsindex 87a269d54..537440104 100644--- a/packages/lint-framework/src/lint/RenderBox.ts+++ b/packages/lint-framework/src/lint/RenderBox.ts@@ -5,6 +5,8 @@ import patch from 'virtual-dom/patch';/** Wraps `virtual-dom` to create a box that is unaffected by the style of the rest of the page. */export default class RenderBox {+ /** The node we reattach into if a host is removed by editor-managed DOM updates. */+ private parent: Node;/** The element our virtual DOM is attached to. */private virtualRoot: Element | undefined;/** The current state of the virtual DOM */@@ -13,12 +15,17 @@ export default class RenderBox {private shadowHost: HTMLElement;constructor(parent: Node) {+ this.parent = parent;this.shadowHost = document.createElement('harper-render-box');parent.appendChild(this.shadowHost);}/** Render to the box. */public render(node: VNode) {+ if (!this.shadowHost.isConnected) {+ this.parent.appendChild(this.shadowHost);+ }+if (!this.virtualRoot || !this.virtualTree) {this.virtualRoot = createElement(node);const shadow = this.shadowHost.attachShadow({ mode: 'open' });diff --git a/packages/lint-framework/src/lint/computeLintBoxes.ts b/packages/lint-framework/src/lint/computeLintBoxes.tsindex 932d885d5..d8f81122b 100644--- a/packages/lint-framework/src/lint/computeLintBoxes.ts+++ b/packages/lint-framework/src/lint/computeLintBoxes.ts@@ -17,12 +17,42 @@ import {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;+};+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);+ }+try {let range: Range | TextFieldRange | null = null;@@ -88,6 +118,66 @@ 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,@@ -126,6 +216,48 @@ 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/domUtils.ts b/packages/lint-framework/src/lint/domUtils.tsindex 3214e6391..4e726c81c 100644--- a/packages/lint-framework/src/lint/domUtils.ts+++ b/packages/lint-framework/src/lint/domUtils.ts@@ -132,6 +132,15 @@ export function isVisible(node: Node): boolean {if (node instanceof Element) {if (!node.isConnected) return false;++ // Google Docs integration uses an off-screen bridge element that is intentionally+ // hidden from users. Treat it as visible when its editor container is on-screen.+ if (node.getAttribute('data-harper-google-docs-target') === 'true') {+ const editor = node.closest('.kix-appview-editor') as HTMLElement | null;+ if (!editor) return false;+ return isBoxInScreen(editor.getBoundingClientRect());+ }+const rect = node.getBoundingClientRect();if (!isBoxInScreen(rect)) return false;const cv = (node as any).checkVisibility;diff --git a/packages/web/src/routes/docs/contributors/chrome-extension/+page.md b/packages/web/src/routes/docs/contributors/chrome-extension/+page.mdindex d2686887b..7d802aa4d 100644--- a/packages/web/src/routes/docs/contributors/chrome-extension/+page.md+++ b/packages/web/src/routes/docs/contributors/chrome-extension/+page.md@@ -59,6 +59,48 @@ It:Despite the name of the package, the `chrome-plugin` also supports Firefox.To build for Firefox, just use `pnpm zip-for-firefox` or otherwise compile with the environment variable `TARGET_BROWSER=firefox`.+## Google Docs Support++Google Docs is a complex beast.+Used by billions around the world, it's honestly an engineering marvel.+Naturally, we want to allow Harper users to use that marvel if they so wish.+That posed a complex problem for us, which is why many of our early users may remember a (relatively) long era where we simply didn't support Google Docs.++Google 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.++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.+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.++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.++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.++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.+## Other Reading- [Putting Harper in the Browser: Technical Details](https://elijahpotter.dev/articles/putting_harper_in_your_browser)diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 97d6ef448..7e1f7a9ac 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -66,8 +66,8 @@ importers:version: 4.0.4([email protected])devDependencies:'@crxjs/vite-plugin':- specifier: ^2.0.0-beta.26- version: 2.0.0-beta.32+ specifier: ^2.3.0+ version: 2.3.0'@playwright/test':specifier: ^1.58.0version: 1.58.0@@ -1446,9 +1446,8 @@ packages:'@codemirror/[email protected]':resolution: {integrity: sha512-ZQ0V5ovw/miKEXTvjgzRyjnrk9TwriUB1k4R5p7uNnHR9Hus+D1SXHGdJshijEzPFjU25xea/7nhIeSqYFKdbA==}- '@crxjs/[email protected]':- resolution: {integrity: sha512-FnEZFrmi4zWG+qPzz658riLIN6TTSOq/M8uEBcENUKoV/UOVUaPrTBjN3aTNOd+tMB7PlqYknKHZYddz/plRdQ==}- deprecated: Beta versions are no longer maintained. Please upgrade to the stable 2.0.0 release+ '@crxjs/[email protected]':+ resolution: {integrity: sha512-+0CNVGS4bB30OoaF1vUsHVwWU1Lm7MxI0XWY9Fd/Ob+ZVTZgEFNqJ1ZC69IVwQsoYhY0sMQLvpLWiFIuDz8htg==}'@csstools/[email protected]':resolution: {integrity: sha512-Up7rBoV77rv29d3uKHUIVubz1BTcgyUK72IvCQAbfbMv584xHcGKCKbWh7i8hPrRJ7qU4Y8IO3IY9m+iTB7P3A==}@@ -14130,19 +14129,20 @@ snapshots:style-mod: 4.1.2w3c-keyname: 2.2.8- '@crxjs/[email protected]':+ '@crxjs/[email protected]':dependencies:'@rollup/pluginutils': 4.2.1'@webcomponents/custom-elements': 1.6.0acorn-walk: 8.3.4cheerio: 1.0.0convert-source-map: 1.9.0- debug: 4.4.0+ debug: 4.4.3es-module-lexer: 0.10.5fast-glob: 3.3.3fs-extra: 10.1.0jsesc: 3.1.0- magic-string: 0.30.17+ magic-string: 0.30.21+ pathe: 2.0.3picocolors: 1.1.1react-refresh: 0.13.0rollup: 2.79.2@@ -18520,7 +18520,7 @@ snapshots:dependencies:- acorn: 8.14.0+ acorn: 8.15.0