Offline, privacy-first grammar checker. Fast, open-source, Rust-powered
feat(chrome-ext): use new CSS Highlights API where possible (#1970)
Elijah Potter7f98e4cef90a
diff --git a/packages/chrome-plugin/package.json b/packages/chrome-plugin/package.jsonindex 663abd401..16205c054 100644--- a/packages/chrome-plugin/package.json+++ b/packages/chrome-plugin/package.json@@ -52,8 +52,8 @@"@tailwindcss/vite": "^4.1.4","@webcomponents/custom-elements": "^1.6.0","harper.js": "workspace:*",- "lint-framework": "workspace:*","jquery": "^3.7.1",+ "lint-framework": "workspace:*","lodash-es": "^4.17.21","lru-cache": "^11.1.0","tailwindcss": "^4.1.4"diff --git a/packages/lint-framework/package.json b/packages/lint-framework/package.jsonindex ac8fbe997..37ad3ca0f 100644--- a/packages/lint-framework/package.json+++ b/packages/lint-framework/package.json@@ -21,6 +21,7 @@"test": "echo 'no tests'"},"dependencies": {+ "bowser": "^2.12.1","virtual-dom": "^2.1.1"},"peerDependencies": {diff --git a/packages/lint-framework/src/lint/Box.ts b/packages/lint-framework/src/lint/Box.tsindex 070457712..65f670f00 100644--- a/packages/lint-framework/src/lint/Box.ts+++ b/packages/lint-framework/src/lint/Box.ts@@ -15,6 +15,8 @@ export type Box = {export type LintBox = Box & {lint: UnpackedLint;source: SourceElement;+ /** Optionally provided to improve highlight rendering performance. */+ range?: Range;applySuggestion: (sug: UnpackedSuggestion) => void;};diff --git a/packages/lint-framework/src/lint/Highlights.ts b/packages/lint-framework/src/lint/Highlights.tsindex e2291e440..e5a7b576d 100644--- a/packages/lint-framework/src/lint/Highlights.ts+++ b/packages/lint-framework/src/lint/Highlights.ts@@ -1,3 +1,4 @@+import Bowser from 'bowser';import type { VNode } from 'virtual-dom';import h from 'virtual-dom/h';import type { LintBox } from './Box';@@ -16,23 +17,70 @@ import {getSlateRoot,getTrixRoot,} from './editorUtils';-import lintKindColor from './lintKindColor';+import lintKindColor, { type LintKind } from './lintKindColor';import RenderBox from './RenderBox';import type SourceElement from './SourceElement';+import type { UnpackedLint } from './unpackLint';/** A class that renders highlights to a page and nothing else. Uses a virtual DOM to minimize jitter. */export default class Highlights {renderBoxes: Map<SourceElement, RenderBox>;+ highlights: Map<LintKind, Highlight> | null;constructor() {this.renderBoxes = new Map();+ this.highlights = supportsCustomHighlights() ? new Map() : null;+ }++ /** Used for CSS highlight API */+ private insertHighlightStyle(tag: string, lint: UnpackedLint) {+ const color = lintKindColor(lint.lint_kind);+ const textDecor = `underline ${color} solid 2px`;+ const backgroundColor = `${color}22`;++ const styleId = `harper-highlight-style-${lint.lint_kind}`;+ if (document.getElementById(styleId)) return;++ const style = document.createElement('style');+ style.id = styleId;+ style.textContent = `+ ::highlight(${tag}) {+ text-decoration: ${textDecor};+ background-color: ${backgroundColor};+ }+ `;+ document.head.appendChild(style);}public renderLintBoxes(boxes: LintBox[]) {// Sort the lint boxes based on their source, so we can render them all together.const sourceToBoxes: Map<SourceElement, { boxes: LintBox[]; cpa: DOMRect | null }> = new Map();+ // Clear old highlights if they exist+ if (this.highlights) {+ for (const [_, highlight] of this.highlights) {+ highlight.clear();+ }+ }+for (const box of boxes) {+ if (box.range && this.highlights != null) {+ let highlight = this.highlights.get(box.lint.lint_kind);++ if (highlight != null) {+ highlight.add(box.range);+ } else {+ highlight = new Highlight();+ const tag = `harper-${box.lint.lint_kind}`;+ CSS.highlights.set(tag, highlight);+ this.insertHighlightStyle(tag, box.lint);+ highlight.add(box.range);+ this.highlights.set(box.lint.lint_kind, highlight);+ }++ continue;+ }+let renderBox = this.renderBoxes.get(box.source);if (renderBox == null) {@@ -242,3 +290,36 @@ function isContainingBlock(el: Element): boolean {return false;}++export function supportsCustomHighlights(ua = navigator.userAgent) {+ const root = globalThis.document?.documentElement;+ const disableFlag =+ root?.getAttribute?.('data-harper-disable-css-highlights') === 'true' ||+ root?.dataset?.harperDisableCssHighlights === 'true';+ if (disableFlag) {+ return false;+ }+ const isAutomated = globalThis.navigator?.webdriver === true;+ if (isAutomated) {+ return false;+ }+ const parser = Bowser.getParser(ua);+ const isFirefox = parser.getBrowserName(true) === 'firefox';+ if (isFirefox) return false;+ if (!('CSS' in window) || typeof CSS.supports !== 'function') return false;+ const supportsSelector = CSS.supports('selector(::highlight(__x))');+ const reg = CSS?.highlights as any;+ const hasRegistry =+ !!reg && ['get', 'set', 'has', 'delete', 'clear'].every((m) => typeof reg[m] === 'function');+ const hasCtor = typeof window.Highlight === 'function';+ let canRegister = false;+ if (hasRegistry && hasCtor) {+ try {+ const h = new Highlight();+ CSS.highlights.set('__probe__', h);+ canRegister = CSS.highlights.has('__probe__');+ CSS.highlights.delete('__probe__');+ } catch {}+ }+ return supportsSelector && hasRegistry && hasCtor && canRegister;+}diff --git a/packages/lint-framework/src/lint/LintFramework.ts b/packages/lint-framework/src/lint/LintFramework.tsindex 6c13f7bc3..8d07fafa2 100644--- a/packages/lint-framework/src/lint/LintFramework.ts+++ b/packages/lint-framework/src/lint/LintFramework.ts@@ -1,4 +1,3 @@-import type { IgnorableLintBox } from './Box';import computeLintBoxes from './computeLintBoxes';import { isVisible } from './domUtils';import Highlights from './Highlights';@@ -18,16 +17,12 @@ export default class LintFramework {private popupHandler: PopupHandler;private targets: Set<Node>;private scrollableAncestors: Set<HTMLElement>;- private scrollPositions: Map<HTMLElement, { left: number; top: number }>;private lintRequested = false;private renderRequested = false;private lastLints: { target: HTMLElement; lints: UnpackedLint[] }[] = [];- private lastBoxes: IgnorableLintBox[] = [];/** The function to be called to re-render the highlights. This is a variable because it is used to register/deregister event listeners. */private updateEventCallback: () => void;- /** Scroll handler used to register/deregister scroll listeners. */- private scrollEventCallback: (ev: Event) => void;/** Function used to fetch lints for a given text/domain. */private lintProvider: (text: string, domain: string) => Promise<UnpackedLint[]>;@@ -58,18 +53,12 @@ export default class LintFramework {});this.targets = new Set();this.scrollableAncestors = new Set();- this.scrollPositions = new Map();this.lastLints = [];- this.lastBoxes = [];this.updateEventCallback = () => {this.update();};- this.scrollEventCallback = (ev: Event) => {- this.onAncestorScroll(ev);- };-const timeoutCallback = () => {this.update();@@ -170,15 +159,7 @@ export default class LintFramework {for (const el of scrollableAncestors) {if (!this.scrollableAncestors.has(el as HTMLElement)) {this.scrollableAncestors.add(el as HTMLElement);- // Initialize scroll position tracking- const scroller = el as HTMLElement;- this.scrollPositions.set(scroller, {- left: scroller.scrollLeft,- top: scroller.scrollTop,- });-- // Listen for scroll with immediate highlight shift- (el as HTMLElement).addEventListener('scroll', this.scrollEventCallback, {+ (el as HTMLElement).addEventListener('scroll', this.updateEventCallback, {capture: true,passive: true,});@@ -198,47 +179,6 @@ export default class LintFramework {}}- /**- * Handle scrolls on tracked ancestor elements by shifting the last-rendered- * boxes immediately by the scroll delta, then schedule a full recompute.- */- private onAncestorScroll(ev: Event) {- const scroller = ev.target as HTMLElement | null;- if (!scroller) return;-- const prev = this.scrollPositions.get(scroller);- const current = { left: scroller.scrollLeft, top: scroller.scrollTop };- if (!prev) {- this.scrollPositions.set(scroller, current);- this.updateEventCallback();- return;- }-- const dx = current.left - prev.left;- const dy = current.top - prev.top;-- // Update stored position immediately- this.scrollPositions.set(scroller, current);-- if ((dx !== 0 || dy !== 0) && this.lastBoxes.length > 0) {- // Shift only boxes whose source is within this scroller- const adjusted: IgnorableLintBox[] = this.lastBoxes.map((b) => {- const sourceEl = b.source as any as HTMLElement;- if (sourceEl && scroller.contains(sourceEl)) {- return { ...b, x: b.x - dx, y: b.y - dy };- }- return b;- });-- // Render immediately so highlights track content without visible lag- this.highlights.renderLintBoxes(adjusted);- this.popupHandler.updateLintBoxes(adjusted);- }-- // Continue with normal update to recompute accurate layout- this.updateEventCallback();- }-private requestRender() {if (this.renderRequested) {return;@@ -254,8 +194,6 @@ export default class LintFramework {): [],);- // Save for immediate scroll adjustments- this.lastBoxes = boxes;this.highlights.renderLintBoxes(boxes);this.popupHandler.updateLintBoxes(boxes);diff --git a/packages/lint-framework/src/lint/computeLintBoxes.ts b/packages/lint-framework/src/lint/computeLintBoxes.tsindex 44f68790e..77bb6215a 100644--- a/packages/lint-framework/src/lint/computeLintBoxes.ts+++ b/packages/lint-framework/src/lint/computeLintBoxes.ts@@ -67,6 +67,7 @@ export default function computeLintBoxes(height: shrunkBox.height,lint,source,+ range: range instanceof Range ? range : undefined,applySuggestion: (sug: UnpackedSuggestion) => {const current = isFormEl(el)? (el as HTMLInputElement | HTMLTextAreaElement).valuediff --git a/packages/lint-framework/src/lint/unpackLint.ts b/packages/lint-framework/src/lint/unpackLint.tsindex fea122be0..87a5a264f 100644--- a/packages/lint-framework/src/lint/unpackLint.ts+++ b/packages/lint-framework/src/lint/unpackLint.ts@@ -1,4 +1,5 @@import { type Lint, type Linter, SuggestionKind } from 'harper.js';+import type { LintKind } from './lintKindColor';export type UnpackedSpan = {start: number;@@ -9,7 +10,7 @@ export type UnpackedLint = {span: UnpackedSpan;message_html: string;problem_text: string;- lint_kind: string;+ lint_kind: LintKind;lint_kind_pretty: string;suggestions: UnpackedSuggestion[];context_hash: string;@@ -32,7 +33,7 @@ export default async function unpackLint(span: { start: span.start, end: span.end },message_html: lint.message_html(),problem_text: lint.get_problem_text(),- lint_kind: lint.lint_kind(),+ lint_kind: lint.lint_kind() as LintKind,lint_kind_pretty: lint.lint_kind_pretty(),suggestions: lint.suggestions().map((sug) => {return { kind: sug.kind(), replacement_text: sug.get_replacement_text() };diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex ddc32063a..b0fd4697e 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -182,6 +182,9 @@ importers:packages/lint-framework:dependencies:+ bowser:+ specifier: ^2.12.1+ version: 2.12.1harper.js:specifier: workspace:*version: link:../harper.js@@ -4746,6 +4749,9 @@ packages:resolution: {integrity: sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww==}+ resolution: {integrity: sha512-z4rE2Gxh7tvshQ4hluIT7XcFrgLIQaw9X3A+kTTRdovCz5PMukm/0QC/BKSYPj3omF5Qfypn9O/c5kgpmvYUCw==}+resolution: {integrity: sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==}@@ -17669,6 +17675,8 @@ snapshots:+ [email protected]: {}+dependencies:balanced-match: 1.0.2