Skip to content

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

fix(chrome-ext): correctly apply suggestions in Google Doc table (#4761)

Elijah Potter41bc616b3c30
diff --git a/packages/chrome-plugin/public/google-docs-bridge.js b/packages/chrome-plugin/public/google-docs-bridge.js
index fbca76661..23134d33b 100644
--- a/packages/chrome-plugin/public/google-docs-bridge.js
+++ b/packages/chrome-plugin/public/google-docs-bridge.js
@@ -31,6 +31,8 @@ import { GoogleDocsBridgeRequestHandler } from './google-docs-bridge-request-han
const EVENT_REPLACE = 'harper:gdocs:replace';
const CARET_DIRECTION_THRESHOLD = 20;
const CARET_CHOICE_STALE_MS = 1500;
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: Mapped edits must not replace native structural controls.
+ const GOOGLE_DOCS_CONTROL_CHARACTERS = /[\u0000-\u001f]/u;
let bridgeNode = /** @type {HTMLElement | null} */ (document.getElementById(BRIDGE_ID));
let currentAnnotated = /** @type {AnnotatedText | null} */ (null);
@@ -569,10 +571,7 @@ import { GoogleDocsBridgeRequestHandler } from './google-docs-bridge-request-han
}
if (hits.length === 0) {
- return {
- start: normalizedStart,
- end: normalizedEnd,
- };
+ return null;
}
hits.sort((left, right) => right.score - left.score);
@@ -644,6 +643,15 @@ import { GoogleDocsBridgeRequestHandler } from './google-docs-bridge-request-han
}
}
+ function isInsideSurrogatePair(text, offset) {
+ return (
+ offset > 0 &&
+ offset < text.length &&
+ /[\ud800-\udbff]/u.test(text[offset - 1]) &&
+ /[\udc00-\udfff]/u.test(text[offset])
+ );
+ }
+
async function handleReplaceTextRequest(request) {
const getAnnotatedText = getAnnotatedTextApi();
if (!getAnnotatedText) {
@@ -658,17 +666,49 @@ import { GoogleDocsBridgeRequestHandler } from './google-docs-bridge-request-han
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 expectedText = String(request.expectedText ?? '');
+ const mapped = 'rangeSource' in request || 'nativeSnapshot' in request;
+ // Mapped requests carry an exact local snapshot, not a search hint. Never
+ // downgrade incomplete, stale, or unknown mapping metadata to legacy search.
+ if (
+ mapped &&
+ (request.rangeSource !== 'native-utf16-v1' ||
+ typeof request.replacementText !== 'string' ||
+ typeof request.nativeSnapshot !== 'string' ||
+ request.nativeSnapshot !== currentText ||
+ !Number.isInteger(request.start) ||
+ !Number.isInteger(request.end) ||
+ request.start < 0 ||
+ request.end <= request.start ||
+ request.end > currentText.length ||
+ typeof request.expectedText !== 'string' ||
+ currentText.slice(request.start, request.end) !== request.expectedText ||
+ GOOGLE_DOCS_CONTROL_CHARACTERS.test(request.expectedText) ||
+ isInsideSurrogatePair(currentText, request.start) ||
+ isInsideSurrogatePair(currentText, request.end))
+ ) {
+ return { kind: 'replaceText', applied: false };
+ }
+ const replacementText = String(request.replacementText ?? '');
+ const resolvedRange = mapped
+ ? { start: request.start, end: request.end }
+ : resolveReplacementRange(
+ currentText,
+ Number(request.start),
+ Number(request.end),
+ expectedText,
+ String(request.beforeContext ?? ''),
+ String(request.afterContext ?? ''),
+ );
+ if (
+ resolvedRange == null ||
+ currentText.slice(resolvedRange.start, resolvedRange.end) !== expectedText
+ ) {
+ return { kind: 'replaceText', applied: false };
+ }
+
const rawStart = normalizedToRawOffset(rawText, resolvedRange.start);
const rawEnd = normalizedToRawOffset(rawText, resolvedRange.end);
@@ -689,7 +729,10 @@ import { GoogleDocsBridgeRequestHandler } from './google-docs-bridge-request-han
const didApplyReplacement = async () => {
const nextAnnotated = await getAnnotatedText();
- return normalizeGoogleDocsText(nextAnnotated?.getText?.()) === expectedNextText;
+ const nextRaw = nextAnnotated?.getText?.();
+ return mapped
+ ? nextRaw === rawText.slice(0, rawStart) + replacementText + rawText.slice(rawEnd)
+ : normalizeGoogleDocsText(nextRaw) === expectedNextText;
};
const dataTransfer = new DataTransfer();
diff --git a/packages/chrome-plugin/public/google-docs-protocol.js b/packages/chrome-plugin/public/google-docs-protocol.js
index f845616e1..665c25dd1 100644
--- a/packages/chrome-plugin/public/google-docs-protocol.js
+++ b/packages/chrome-plugin/public/google-docs-protocol.js
@@ -34,6 +34,8 @@
* @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.
+ * @property {'native-utf16-v1'=} rangeSource Strict native UTF-16 range mode. No relocation is permitted.
+ * @property {string=} nativeSnapshot Exact bridge-normalized text captured with the lint. Required with rangeSource.
*/
/**
diff --git a/packages/chrome-plugin/src/contentScript/GoogleDocsBridgeClient.ts b/packages/chrome-plugin/src/contentScript/GoogleDocsBridgeClient.ts
index d06e2869a..bf57d4b7d 100644
--- a/packages/chrome-plugin/src/contentScript/GoogleDocsBridgeClient.ts
+++ b/packages/chrome-plugin/src/contentScript/GoogleDocsBridgeClient.ts
@@ -24,6 +24,8 @@ type GoogleDocsRequest =
expectedText?: string;
beforeContext?: string;
afterContext?: string;
+ rangeSource?: 'native-utf16-v1';
+ nativeSnapshot?: string;
};
type GoogleDocsGetRectsResponse = {
@@ -149,6 +151,7 @@ export default class GoogleDocsBridgeClient {
expectedText?: string,
beforeContext?: string,
afterContext?: string,
+ nativeRange?: { rangeSource: 'native-utf16-v1'; nativeSnapshot: string },
): Promise<boolean> {
const response = await this.request({
kind: 'replaceText',
@@ -158,6 +161,7 @@ export default class GoogleDocsBridgeClient {
expectedText,
beforeContext,
afterContext,
+ ...nativeRange,
});
return response.kind === 'replaceText' ? response.applied : false;
diff --git a/packages/chrome-plugin/src/contentScript/googleDocs.ts b/packages/chrome-plugin/src/contentScript/googleDocs.ts
index 50ba8060b..143ee8ef5 100644
--- a/packages/chrome-plugin/src/contentScript/googleDocs.ts
+++ b/packages/chrome-plugin/src/contentScript/googleDocs.ts
@@ -24,6 +24,12 @@ 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;
+// biome-ignore lint/suspicious/noControlCharactersInRegex: Observed native Google Docs table separators, masked one code unit at a time.
+const GOOGLE_DOCS_TABLE_SEPARATORS = /[\u0010\u0011\u0012\u001c]/gu;
+// biome-ignore lint/suspicious/noControlCharactersInRegex: Native Shift+Enter becomes one space only in the lint projection.
+const GOOGLE_DOCS_SOFT_BREAKS = /\u000b/gu;
+// biome-ignore lint/suspicious/noControlCharactersInRegex: Native control characters cannot own visible source geometry.
+const GOOGLE_DOCS_CONTROL_CHARACTERS = /[\u0000-\u001f]/u;
type LayoutRefreshFramework = LintFramework & {
refreshLayout?: () => void;
@@ -39,7 +45,9 @@ type GoogleDocsRectSegment = {
type GoogleDocsCloneSnapshot = {
fragment: DocumentFragment;
text: string;
- source: 'logical' | 'rects';
+ source: 'logical' | 'rects' | 'native';
+ nativeSnapshot?: string;
+ nativeRuns?: Array<[number, number, number]>;
segmentCount: number;
signature: string;
};
@@ -583,24 +591,227 @@ export function createGoogleDocsBridgeSync(fw: LintFramework): () => Promise<voi
};
}
+ function buildNativeTableSnapshot(
+ editor: HTMLElement,
+ segments: GoogleDocsRectSegment[],
+ nativeSnapshot: string,
+ ): GoogleDocsCloneSnapshot {
+ // Mask the observed controls without changing source characters. Confirmed
+ // paragraph boundaries below can add LF, so lint offsets need explicit runs.
+ // This is not a parser for the complete Google Docs control grammar.
+ const masked = nativeSnapshot
+ .replace(GOOGLE_DOCS_TABLE_SEPARATORS, '\n')
+ .replace(GOOGLE_DOCS_SOFT_BREAKS, ' ');
+ const comparable = nativeSnapshot.replace(/\u00a0/gu, ' ');
+ const matchesBySegment = new Map<
+ GoogleDocsRectSegment,
+ { start: number; end: number; segment: GoogleDocsRectSegment }
+ >();
+ const labels = new Map(
+ segments.map((segment) => [
+ segment,
+ (segment.rectNode.getAttribute('aria-label') ?? '').replace(/\u00a0/gu, ' '),
+ ]),
+ );
+ for (const segment of segments) {
+ // Preserve source characters. Only an equal-length space alias is used.
+ const label = labels.get(segment)!;
+ const start = comparable.indexOf(label);
+ if (
+ !label.trim() ||
+ GOOGLE_DOCS_CONTROL_CHARACTERS.test(label) ||
+ start < 0 ||
+ comparable.indexOf(label, start + 1) >= 0
+ )
+ continue;
+ matchesBySegment.set(segment, { start, end: start + label.length, segment });
+ }
+ // A paragraph's contiguous labels can uniquely anchor a repeated short word.
+ // Screen order is used only within this group, never between native cells.
+ // Multiple full matches are ambiguity, not permission to pick the nearest.
+ const continuations = new Map<number, Set<Element>>();
+ const groups = new Map<Element, GoogleDocsRectSegment[]>();
+ for (const segment of segments) {
+ const group = segment.rectNode.closest('g[role="paragraph"]');
+ if (group) groups.set(group, [...(groups.get(group) ?? []), segment]);
+ }
+ for (const [group, groupSegments] of groups) {
+ const ordered = groupSegments.toSorted(compareSegments);
+ if (
+ ordered.length < 2 ||
+ ordered.some(
+ (segment) =>
+ !labels.get(segment)!.trim() ||
+ GOOGLE_DOCS_CONTROL_CHARACTERS.test(labels.get(segment)!),
+ )
+ )
+ continue;
+ const firstLabel = labels.get(ordered[0])!;
+ let cursor = 0;
+ let unique: Array<{ start: number; end: number; segment: GoogleDocsRectSegment }> | null =
+ null;
+ while (cursor < comparable.length) {
+ const first = comparable.indexOf(firstLabel, cursor);
+ if (first < 0) break;
+ const sequence = [{ start: first, end: first + firstLabel.length, segment: ordered[0] }];
+ for (const segment of ordered.slice(1)) {
+ const previousEnd = sequence[sequence.length - 1].end;
+ const label = labels.get(segment)!;
+ const start = comparable.indexOf(label, previousEnd);
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: Only ordinary whitespace may separate labels inside one native region.
+ if (start < 0 || !/^[ \r\n ]*$/u.test(comparable.slice(previousEnd, start))) break;
+ sequence.push({ start, end: start + label.length, segment });
+ }
+ if (sequence.length === ordered.length) {
+ if (unique != null) {
+ unique = null;
+ break;
+ }
+ unique = sequence;
+ }
+ cursor = first + 1;
+ }
+ for (const match of unique ?? []) matchesBySegment.set(match.segment, match);
+ // An aligned paragraph can identify LF as a wrap between its labels.
+ // Keep this evidence separate from highlight resolution, which can
+ // still reject overlapping boxes for the same native source range.
+ for (let index = 1; unique != null && index < unique.length; index += 1) {
+ const previous = unique[index - 1];
+ const gap = nativeSnapshot.slice(previous.end, unique[index].start);
+ const newline = gap.indexOf('\n');
+ if (newline >= 0 && gap.indexOf('\n', newline + 1) < 0) {
+ const offset = previous.end + newline;
+ const agreeing = continuations.get(offset) ?? new Set<Element>();
+ agreeing.add(group);
+ continuations.set(offset, agreeing);
+ }
+ }
+ }
+ const matches = Array.from(matchesBySegment.values());
+ const softLineBreaks = new Set<number>();
+ for (const [newline, agreeing] of continuations) {
+ // A separate anchored paragraph touching this LF contradicts a wrap.
+ // Do not let conflicting SVG groups override the native hard boundary.
+ const conflicting = matches.some(({ start, end, segment }) => {
+ const group = segment.rectNode.closest('g[role="paragraph"]');
+ if (group == null || agreeing.has(group)) return false;
+ return (
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: Only non-line-breaking whitespace may touch this LF.
+ (end <= newline && /^[ \r ]*$/u.test(comparable.slice(end, newline))) ||
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: Only non-line-breaking whitespace may touch this LF.
+ (start > newline && /^[ \r ]*$/u.test(comparable.slice(newline + 1, start)))
+ );
+ });
+ if (!conflicting) softLineBreaks.add(newline);
+ }
+ // Contradictory geometry is local ambiguity, never a reason to lint visual
+ // table prose. Both overlapping assignments remain non-geometric gaps.
+ const resolved = matches.filter(
+ (match) =>
+ !matches.some(
+ (other) => other !== match && other.start < match.end && other.end > match.start,
+ ),
+ );
+ resolved.sort((left, right) => left.start - right.start);
+ const paragraphBreaks = new Set<number>();
+ // Native Enter is LF, even if either paragraph is repeated or unrendered.
+ // Its linguistic meaning must not depend on a unique highlight anchor.
+ // Keep positively identified same-paragraph wraps soft; page margins and
+ // missing geometry are not evidence for a continuation. VT stays native.
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: Observed native paragraph/table boundaries plus adjacent whitespace.
+ for (const gap of nativeSnapshot.matchAll(/[ \r\n \u0010\u0011\u0012\u001c]+/gu)) {
+ const end = gap.index + gap[0].length;
+ if (
+ gap.index === 0 ||
+ end === nativeSnapshot.length ||
+ gap[0].replace(GOOGLE_DOCS_TABLE_SEPARATORS, '\n').includes('\n\n')
+ )
+ continue;
+ const tableBoundary = gap[0].search(GOOGLE_DOCS_TABLE_SEPARATORS);
+ const newline = gap[0].indexOf('\n');
+ const boundary =
+ tableBoundary >= 0
+ ? tableBoundary
+ : newline >= 0 && !softLineBreaks.has(gap.index + newline)
+ ? newline
+ : -1;
+ if (boundary >= 0) paragraphBreaks.add(gap.index + boundary + 1);
+ }
+ const breaks = Array.from(paragraphBreaks).sort((left, right) => left - right);
+ // Each run is [projection start, native start, UTF-16 length]. Inserted
+ // separators are deliberately outside runs and cannot own an edit range.
+ const nativeRuns: Array<[number, number, number]> = [];
+ const parts: string[] = [];
+ let nativeCursor = 0;
+ let projectionCursor = 0;
+ for (const end of [...breaks, nativeSnapshot.length]) {
+ const slice = masked.slice(nativeCursor, end);
+ nativeRuns.push([projectionCursor, nativeCursor, slice.length]);
+ parts.push(slice);
+ projectionCursor += slice.length;
+ if (end < nativeSnapshot.length) {
+ parts.push('\n');
+ projectionCursor += 1;
+ }
+ nativeCursor = end;
+ }
+ const text = parts.join('');
+ const projectOffset = (offset: number) => offset + breaks.filter((end) => end <= offset).length;
+ const fragment = document.createDocumentFragment();
+ let cursor = 0;
+ for (const { start, end, segment } of resolved) {
+ const projectedStart = projectOffset(start);
+ const projectedEnd = projectOffset(end);
+ fragment.appendChild(document.createTextNode(text.slice(cursor, projectedStart)));
+ const span = createCloneSpan(segment, text.slice(projectedStart, projectedEnd));
+ span.setAttribute('data-harper-gdocs-native-start', String(start));
+ fragment.appendChild(span);
+ cursor = projectedEnd;
+ }
+ fragment.appendChild(document.createTextNode(text.slice(cursor)));
+ return {
+ fragment,
+ text,
+ source: 'native',
+ nativeSnapshot,
+ nativeRuns,
+ segmentCount: resolved.length,
+ // Mapping identity includes exact ranges, geometry, and font. Legacy
+ // normalized labels can stay equal when native matching changes.
+ signature: JSON.stringify([
+ editor.scrollTop,
+ editor.scrollLeft,
+ nativeRuns,
+ resolved.map(({ start, end, segment }) => [
+ start,
+ end,
+ segment.rect,
+ segment.rectNode.getAttribute('data-font-css'),
+ ]),
+ ]),
+ };
+ }
+
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') ?? '';
-
+ // The bridge removes only its leading sentinel and final newline. Keep the
+ // exact remaining code units for mapped requests; CRLF conversion shifts them.
+ const nativeText = document.getElementById(GOOGLE_DOCS_MAIN_WORLD_BRIDGE_ID)?.textContent ?? '';
+ if (nativeText.search(GOOGLE_DOCS_TABLE_SEPARATORS) >= 0) {
+ return buildNativeTableSnapshot(editor, segments, nativeText);
+ }
// Display normalization is lossy: it can turn a raw label into an exact
// match for a different native paragraph, or hide known omitted prose.
// Keep raw source labels throughout ordinary native matching/projection.
// Without native text, retain the legacy display-only normalization.
const ordinarySegments =
- logicalText.length > 0
+ nativeText.length > 0
? segments.map((segment) => ({
...segment,
text: segment.rectNode.getAttribute('aria-label')!,
}))
: segments;
+ const logicalText = nativeText.replace(/\r\n?/gu, '\n');
return (
buildLogicalSnapshot(editor, ordinarySegments, logicalText) ??
buildRectSnapshot(editor, ordinarySegments, logicalText)
@@ -608,11 +819,23 @@ export function createGoogleDocsBridgeSync(fw: LintFramework): () => Promise<voi
}
function applySnapshot(target: HTMLElement, snapshot: GoogleDocsCloneSnapshot): boolean {
- if (snapshot.signature === lastCloneSignature && target.textContent === snapshot.text) {
+ const previousNative = target.getAttribute('data-harper-gdocs-native-snapshot');
+ if (
+ snapshot.signature === lastCloneSignature &&
+ target.textContent === snapshot.text &&
+ previousNative === (snapshot.nativeSnapshot ?? null)
+ ) {
return false;
}
target.replaceChildren(snapshot.fragment);
+ if (snapshot.nativeSnapshot != null) {
+ target.setAttribute('data-harper-gdocs-native-snapshot', snapshot.nativeSnapshot);
+ target.setAttribute('data-harper-gdocs-native-runs', JSON.stringify(snapshot.nativeRuns));
+ } else {
+ target.removeAttribute('data-harper-gdocs-native-snapshot');
+ target.removeAttribute('data-harper-gdocs-native-runs');
+ }
target.setAttribute('data-harper-gdocs-source', snapshot.source);
target.setAttribute('data-harper-gdocs-segments', String(snapshot.segmentCount));
lastCloneSignature = snapshot.signature;
diff --git a/packages/lint-framework/src/lint/LintFramework.ts b/packages/lint-framework/src/lint/LintFramework.ts
index 6574a707a..fe41a61cd 100644
--- a/packages/lint-framework/src/lint/LintFramework.ts
+++ b/packages/lint-framework/src/lint/LintFramework.ts
@@ -4,6 +4,7 @@ import { isGoogleDocsTarget } from './computeLintBoxes/googleDocsUtilities';
import computeLintBoxes from './computeLintBoxes/index';
import { isHeading, isVisible } from './domUtils';
import { getCaretPosition, getCMRoot } from './editorUtils';
+import { getGoogleDocsLintWindows, MAX_LINT_TEXT_LENGTH } from './googleDocsLintWindows';
import Highlights from './Highlights';
import PopupHandler from './PopupHandler';
import { remapLintToCurrentSource } from './spanMapping';
@@ -177,11 +178,40 @@ export default class LintFramework {
const { text, isCM, newLineIndices } = this.getTargetText(target);
- if (!text || text.length > 120000) {
+ if (!text) {
return { target: null as HTMLElement | null, lints: {} };
}
const language = getTargetLanguage(target);
+ if (text.length > MAX_LINT_TEXT_LENGTH) {
+ const windows =
+ target instanceof HTMLElement ? getGoogleDocsLintWindows(target, text) : [];
+ if (windows.length === 0) {
+ return { target: null as HTMLElement | null, lints: {} };
+ }
+ const lintsBySource: UnpackedLintGroups = {};
+ for (const span of windows) {
+ const windowText = text.slice(span.start, span.end);
+ // Providers can cache their objects. Keep their window-local spans/source
+ // intact, and bind our copy to the full projection captured before await.
+ const groups = window.structuredClone(
+ await this.lintProvider(windowText, window.location.hostname, {
+ forceAllHeadings: isHeading(target),
+ language,
+ }),
+ );
+ for (const [rule, lints] of Object.entries(groups)) {
+ for (const lint of lints) {
+ lint.span.start += span.start;
+ lint.span.end += span.start;
+ lint.source = text;
+ }
+ lintsBySource[rule] ??= [];
+ lintsBySource[rule].push(...lints);
+ }
+ }
+ return { target: target as HTMLElement, lints: lintsBySource };
+ }
let lintsBySource = await this.lintProvider(text, window.location.hostname, {
forceAllHeadings: isHeading(target),
language,
@@ -376,6 +406,9 @@ export default class LintFramework {
if (!target) {
return [];
}
+ const mapped =
+ isGoogleDocsTarget(target) &&
+ target.getAttribute('data-harper-gdocs-source') === 'native';
const { text, isCM } = this.getTargetText(target);
if (text == null) {
@@ -384,11 +417,12 @@ export default class LintFramework {
return Object.entries(lints).flatMap(([ruleName, ls]) =>
ls.flatMap((lint) => {
- const currentLint = isCM
- ? lint.source === text
- ? lint
- : null
- : remapLintToCurrentSource(lint, text);
+ const currentLint =
+ isCM || mapped
+ ? lint.source === text
+ ? lint
+ : null
+ : remapLintToCurrentSource(lint, text);
if (currentLint == null) {
return [];
}
diff --git a/packages/lint-framework/src/lint/computeLintBoxes/googleDocsUtilities.ts b/packages/lint-framework/src/lint/computeLintBoxes/googleDocsUtilities.ts
index 4269a6073..62519c873 100644
--- a/packages/lint-framework/src/lint/computeLintBoxes/googleDocsUtilities.ts
+++ b/packages/lint-framework/src/lint/computeLintBoxes/googleDocsUtilities.ts
@@ -2,6 +2,11 @@ import type { Span } from 'harper.js';
import { leafNodes } from '../domUtils';
import type { UnpackedLint, UnpackedSpan } from '../unpackLint';
+type GoogleDocsNativeRange = {
+ rangeSource: 'native-utf16-v1';
+ nativeSnapshot: string;
+};
+
type GoogleDocsReplacePayload = {
start: number;
end: number;
@@ -19,6 +24,7 @@ type GoogleDocsBridgeClientLike = {
expectedText?: string,
beforeContext?: string,
afterContext?: string,
+ nativeRange?: GoogleDocsNativeRange,
) => Promise<unknown> | unknown;
};
@@ -251,6 +257,13 @@ export function getGoogleDocsHighlightRects(target: HTMLElement, span: Span): DO
}
const positionedHost = getGoogleDocsPositionedLeafHost(child, target);
+ // Native gaps have text but no geometry. DOM Range on the hidden mirror
+ // would otherwise manufacture a box near the editor origin.
+ if (
+ target.getAttribute('data-harper-gdocs-source') === 'native' &&
+ !positionedHost?.hasAttribute('data-harper-gdocs-native-start')
+ )
+ continue;
if (positionedHost != null) {
const rect = getGoogleDocsTextSliceRect(positionedHost, childText, localStart, localEnd);
if (rect != null && rect.width > 0 && rect.height > 0) {
@@ -306,6 +319,7 @@ export async function replaceGoogleDocsValue(
span: { start: number; end: number },
replacementText: string,
source: string,
+ nativeRange?: GoogleDocsNativeRange,
): Promise<boolean> {
try {
const safeStart = Math.max(0, Math.min(span.start, source.length));
@@ -334,6 +348,7 @@ export async function replaceGoogleDocsValue(
payload.expectedText,
payload.beforeContext,
payload.afterContext,
+ nativeRange,
);
return Boolean(applied);
}
diff --git a/packages/lint-framework/src/lint/googleDocsAdapter.ts b/packages/lint-framework/src/lint/googleDocsAdapter.ts
index 858943baa..9247028bb 100644
--- a/packages/lint-framework/src/lint/googleDocsAdapter.ts
+++ b/packages/lint-framework/src/lint/googleDocsAdapter.ts
@@ -11,6 +11,57 @@ import type { UnpackedLint, UnpackedSpan, UnpackedSuggestion } from './unpackLin
const GOOGLE_DOCS_EDITOR_SELECTOR = '.kix-appview-editor';
const GOOGLE_DOCS_SYNCING_ATTR = 'data-harper-gdocs-syncing';
+// biome-ignore lint/suspicious/noControlCharactersInRegex: Must match the content script's native table projection.
+const GOOGLE_DOCS_TABLE_SEPARATORS = /[\u0010\u0011\u0012\u001c]/gu;
+// biome-ignore lint/suspicious/noControlCharactersInRegex: Match extraction's one-unit lint projection of native Shift+Enter.
+const GOOGLE_DOCS_SOFT_BREAKS = /\u000b/gu;
+// biome-ignore lint/suspicious/noControlCharactersInRegex: Corrections must not cross native structural boundaries.
+const GOOGLE_DOCS_CONTROL_CHARACTERS = /[\u0000-\u001f]/u;
+
+function resolveNativeSpan(
+ target: HTMLElement,
+ source: string,
+ nativeSnapshot: string,
+ span: UnpackedSpan,
+): UnpackedSpan | null {
+ const runs: unknown = JSON.parse(target.getAttribute('data-harper-gdocs-native-runs') ?? 'null');
+ if (!Array.isArray(runs) || runs.length === 0) return null;
+ const masked = nativeSnapshot
+ .replace(GOOGLE_DOCS_TABLE_SEPARATORS, '\n')
+ .replace(GOOGLE_DOCS_SOFT_BREAKS, ' ');
+ let projectionCursor = 0;
+ let nativeCursor = 0;
+ let resolved: UnpackedSpan | null = null;
+ for (const run of runs) {
+ if (!Array.isArray(run) || run.length !== 3 || !run.every(Number.isInteger)) return null;
+ const [projectionStart, nativeStart, length] = run;
+ if (nativeCursor > 0) {
+ // Only the extra LF of a paragraph boundary may be outside a run.
+ if (masked[nativeCursor - 1] !== '\n' || source[projectionCursor] !== '\n') return null;
+ projectionCursor += 1;
+ }
+ if (
+ projectionStart !== projectionCursor ||
+ nativeStart !== nativeCursor ||
+ length <= 0 ||
+ nativeStart + length > nativeSnapshot.length ||
+ source.slice(projectionStart, projectionStart + length) !==
+ masked.slice(nativeStart, nativeStart + length)
+ )
+ return null;
+ if (span.start >= projectionStart && span.end <= projectionStart + length) {
+ resolved = {
+ start: nativeStart + span.start - projectionStart,
+ end: nativeStart + span.end - projectionStart,
+ };
+ }
+ nativeCursor += length;
+ projectionCursor += length;
+ }
+ return nativeCursor === nativeSnapshot.length && projectionCursor === source.length
+ ? resolved
+ : null;
+}
/**
* Returns Google Docs-specific lint boxes for the hidden bridge target.
@@ -31,13 +82,50 @@ export function maybeComputeGoogleDocsLintBoxes(
try {
const editor = document.querySelector(GOOGLE_DOCS_EDITOR_SELECTOR) as HTMLElement | null;
const source = target.textContent ?? '';
- const resolvedSpan = resolveGoogleDocsSpan(source, lint);
+ const sourceMode = target.getAttribute('data-harper-gdocs-source');
+ const nativeSnapshot = target.getAttribute('data-harper-gdocs-native-snapshot');
+ const mapped =
+ sourceMode === 'native' ||
+ nativeSnapshot != null ||
+ target.hasAttribute('data-harper-gdocs-native-runs') ||
+ target.querySelector('[data-harper-gdocs-native-start]') != null;
+ // Capture provenance when the box is made, not when its action is clicked.
+ // An old lint must not inherit the current target's native snapshot.
+ const resolvedSpan = mapped
+ ? nativeSnapshot != null
+ ? resolveNativeSpan(target, source, nativeSnapshot, lint.span)
+ : null
+ : resolveGoogleDocsSpan(source, lint);
if (!editor || resolvedSpan == null) {
return [];
}
+ if (
+ mapped &&
+ (sourceMode !== 'native' ||
+ nativeSnapshot == null ||
+ lint.source !== source ||
+ !Number.isInteger(lint.span.start) ||
+ !Number.isInteger(lint.span.end) ||
+ lint.span.start < 0 ||
+ lint.span.end <= lint.span.start ||
+ !Number.isInteger(resolvedSpan.start) ||
+ !Number.isInteger(resolvedSpan.end) ||
+ resolvedSpan.start < 0 ||
+ resolvedSpan.end <= resolvedSpan.start ||
+ resolvedSpan.end > nativeSnapshot.length ||
+ GOOGLE_DOCS_CONTROL_CHARACTERS.test(
+ nativeSnapshot.slice(resolvedSpan.start, resolvedSpan.end),
+ ) ||
+ nativeSnapshot.slice(resolvedSpan.start, resolvedSpan.end) !== lint.problem_text)
+ ) {
+ return [];
+ }
- const targetRects = getGoogleDocsHighlightRects(target, resolvedSpan as Span);
+ const targetRects = getGoogleDocsHighlightRects(
+ target,
+ (mapped ? lint.span : resolvedSpan) as Span,
+ );
const editorBox = domRectToBox(editor.getBoundingClientRect());
if (targetRects.length === 0) {
return [];
@@ -59,8 +147,20 @@ export function maybeComputeGoogleDocsLintBoxes(
source: editor,
rule,
applySuggestion: async (suggestion: UnpackedSuggestion) => {
- const replacementText = suggestionToReplacementText(suggestion, resolvedSpan, source);
- await replaceGoogleDocsValue(resolvedSpan, replacementText, source);
+ const replacementSource = nativeSnapshot ?? source;
+ const replacementText = suggestionToReplacementText(
+ suggestion,
+ resolvedSpan,
+ replacementSource,
+ );
+ await replaceGoogleDocsValue(
+ resolvedSpan,
+ replacementText,
+ replacementSource,
+ mapped
+ ? { rangeSource: 'native-utf16-v1', nativeSnapshot: nativeSnapshot! }
+ : undefined,
+ );
},
ignoreLint: opts.ignoreLint ? () => opts.ignoreLint!(lint.context_hash) : undefined,
});
diff --git a/packages/lint-framework/src/lint/googleDocsLintWindows.ts b/packages/lint-framework/src/lint/googleDocsLintWindows.ts
new file mode 100644
index 000000000..392aa47c8
--- /dev/null
+++ b/packages/lint-framework/src/lint/googleDocsLintWindows.ts
@@ -0,0 +1,61 @@
+import { isGoogleDocsTarget } from './computeLintBoxes/googleDocsUtilities';
+import { leafNodes } from './domUtils';
+import type { UnpackedSpan } from './unpackLint';
+
+export const MAX_LINT_TEXT_LENGTH = 120000;
+const MAX_VISIBLE_PARAGRAPHS = 32;
+
+/**
+ * Select complete paragraphs from the full native projection, not from visual
+ * labels. Projection offsets and Harper JS spans both count UTF-16 code units.
+ * The native mirror inserts blank lines at hard paragraph/table boundaries;
+ * single newlines can be soft wraps and must stay inside their paragraph.
+ */
+export function getGoogleDocsLintWindows(target: HTMLElement, source: string): UnpackedSpan[] {
+ if (!isGoogleDocsTarget(target) || target.getAttribute('data-harper-gdocs-source') !== 'native') {
+ return [];
+ }
+ const editor = target.closest('.kix-appview-editor');
+ if (!editor) return [];
+ const editorRect = editor.getBoundingClientRect();
+ const windows: UnpackedSpan[] = [];
+ const seen = new Set<number>();
+ let traversed = 0;
+ let remaining = MAX_LINT_TEXT_LENGTH;
+ for (const leaf of leafNodes(target)) {
+ const start = traversed;
+ traversed += leaf.textContent?.length ?? 0;
+ const host = leaf.parentElement?.closest('[data-harper-gdocs-native-start]');
+ if (!host || !target.contains(host)) continue;
+ const rect = host.getBoundingClientRect();
+ if (
+ rect.width <= 0 ||
+ rect.height <= 0 ||
+ rect.bottom <= Math.max(0, editorRect.top) ||
+ rect.top >= Math.min(window.innerHeight, editorRect.bottom) ||
+ rect.right <= Math.max(0, editorRect.left) ||
+ rect.left >= Math.min(window.innerWidth, editorRect.right)
+ ) {
+ continue;
+ }
+ let cursor = start;
+ while (cursor < traversed) {
+ const previousBreak = source.lastIndexOf('\n\n', cursor - 1);
+ const paragraphStart = previousBreak < 0 ? 0 : previousBreak + 2;
+ const nextBreak = source.indexOf('\n\n', cursor);
+ const paragraphEnd = nextBreak < 0 ? source.length : nextBreak;
+ const length = paragraphEnd - paragraphStart;
+ if (!seen.has(paragraphStart)) {
+ seen.add(paragraphStart);
+ // Never clip a paragraph to fit. Later, smaller paragraphs can still fit.
+ if (length > 0 && length <= remaining) {
+ windows.push({ start: paragraphStart, end: paragraphEnd });
+ remaining -= length;
+ if (windows.length === MAX_VISIBLE_PARAGRAPHS) return windows;
+ }
+ }
+ cursor = paragraphEnd + 2;
+ }
+ }
+ return windows;
+}