Offline, privacy-first grammar checker. Fast, open-source, Rust-powered
feat(chrome-ext): build out support for the online Typst playground (#2706)
Elijah Potter08d2987fe9d9
diff --git a/packages/chrome-plugin/src/background/index.ts b/packages/chrome-plugin/src/background/index.tsindex a93c02012..46dbcd15d 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',+ 'typst.app',];for (const item of defaultEnabledDomains) {diff --git a/packages/chrome-plugin/src/contentScript/index.ts b/packages/chrome-plugin/src/contentScript/index.tsindex 341ac0430..aee11eadd 100644--- a/packages/chrome-plugin/src/contentScript/index.ts+++ b/packages/chrome-plugin/src/contentScript/index.ts@@ -98,7 +98,33 @@ function scan() {}});+ document+ .querySelectorAll<HTMLElement>('.cm-editor .cm-content[contenteditable="true"]')+ .forEach((element) => {+ const isTypstPlayground = window.location.hostname === 'typst.app';+ const explicitlyTypst = element.getAttribute('data-language') === 'typst';++ if (!isTypstPlayground && !explicitlyTypst) {+ return;+ }++ if (element.closest('[contenteditable="false"],[disabled],[readonly]') != null) {+ return;+ }++ if (!isVisible(element)) {+ return;+ }++ element.setAttribute('data-language', 'typst');+ fw.addTarget(element);+ });+document.querySelectorAll('[contenteditable="true"],[contenteditable]').forEach((element) => {+ if (element.classList.contains('cm-content') && element.closest('.cm-editor') != null) {+ return;+ }+if (element.matches('[role="combobox"]') ||element.getAttribute('data-enable-grammarly') === 'false' ||diff --git a/packages/chrome-plugin/tests/typst.spec.ts b/packages/chrome-plugin/tests/typst.spec.tsnew file mode 100644index 000000000..e7b327b29--- /dev/null+++ b/packages/chrome-plugin/tests/typst.spec.ts@@ -0,0 +1,45 @@+import type { Page } from '@playwright/test';+import { expect, test } from './fixtures';+import { clickHarperHighlight, getHarperHighlights, replaceEditorContent } from './testUtils';++const TEST_PAGE_URL = 'https://typst.app/play/';++async function assertHighlightCount(page: Page, count: number) {+ await expect(getHarperHighlights(page)).toHaveCount(count, { timeout: 30000 });+}++test('Typst CodeMirror editor can apply a suggestion', async ({ page }) => {+ await page.goto(TEST_PAGE_URL, { waitUntil: 'domcontentloaded' });++ const editor = page.locator('.cm-editor .cm-content[contenteditable="true"]').first();+ await expect(editor).toBeVisible({ timeout: 30000 });+ await replaceEditorContent(editor, 'This is an test');++ await assertHighlightCount(page, 1);++ expect(await clickHarperHighlight(page)).toBe(true);+ await page.getByTitle('Replace with "a"').click();++ await expect(editor).toContainText('This is a test');+});++test('Typst CodeMirror handles multiline suggestions distinctly', async ({ page }) => {+ test.setTimeout(120000);+ await page.goto(TEST_PAGE_URL, { waitUntil: 'domcontentloaded' });++ const editor = page.locator('.cm-editor .cm-content[contenteditable="true"]').first();+ await expect(editor).toBeVisible({ timeout: 30000 });+ await replaceEditorContent(editor, 'First line an test\nSecond line an test');++ await expect(editor).toContainText('First line an test');+ await expect(editor).toContainText('Second line an test');+ await assertHighlightCount(page, 2);+ const initialHighlightCount = 2;+ expect(await clickHarperHighlight(page)).toBe(true);+ await page.getByTitle('Replace with "a"').click();++ const editorText = await editor.innerText();+ expect((editorText.match(/an test/g) ?? []).length).toBe(1);+ expect((editorText.match(/a test/g) ?? []).length).toBe(1);+ await assertHighlightCount(page, initialHighlightCount - 1);+});diff --git a/packages/harper.js/src/LocalLinter.ts b/packages/harper.js/src/LocalLinter.tsindex 517557b43..f7a41c2b4 100644--- a/packages/harper.js/src/LocalLinter.ts+++ b/packages/harper.js/src/LocalLinter.ts@@ -61,7 +61,20 @@ export default class LocalLinter implements Linter {async organizedLints(text: string, options?: LintOptions): Promise<Record<string, Lint[]>> {const inner = await this.inner;- const language = options?.language === 'plaintext' ? Language.Plain : Language.Markdown;+ let language = Language.Markdown;++ switch (options?.language) {+ case 'plaintext':+ language = Language.Plain;+ break;+ case 'markdown':+ language = Language.Markdown;+ break;+ case 'typst':+ language = Language.Typst;+ break;+ }+const lintGroups = inner.organized_lints(text,language,diff --git a/packages/lint-framework/src/lint/LintFramework.ts b/packages/lint-framework/src/lint/LintFramework.tsindex 415be9f84..0615894fe 100644--- a/packages/lint-framework/src/lint/LintFramework.ts+++ b/packages/lint-framework/src/lint/LintFramework.ts@@ -2,7 +2,7 @@ import type { LintOptions } from 'harper.js';import { closestBox, type IgnorableLintBox } from './Box';import computeLintBoxes from './computeLintBoxes';import { isHeading, isVisible } from './domUtils';-import { getCaretPosition } from './editorUtils';+import { getCaretPosition, getCMRoot } from './editorUtils';import Highlights from './Highlights';import PopupHandler from './PopupHandler';import type { UnpackedLint, UnpackedLintGroups } from './unpackLint';@@ -131,18 +131,56 @@ export default class LintFramework {return { target: null as HTMLElement | null, lints: {} };}- const text =- target instanceof HTMLTextAreaElement || target instanceof HTMLInputElement- ? target.value- : target.textContent;+ let text = null;++ // Check if it is a CodeMirror instance, which needs to be handled in a specific way.+ const isCM = target instanceof HTMLElement && getCMRoot(target) != null;++ if (isCM) {+ const lineElements = target.querySelectorAll<HTMLElement>('.cm-line');+ const lines = Array.from(lineElements).map((el) => el.textContent);+ text = lines.reduce((acc: string, x: string) => `${acc + x}\n`, '');+ } else {+ text =+ target instanceof HTMLTextAreaElement || target instanceof HTMLInputElement+ ? target.value+ : target.textContent;+ }++ const newLineIndices = [];+ let i = 0;+ for (const c of text ?? '') {+ if (c == '\n') {+ newLineIndices.push(i);+ }+ i++;+ }if (!text || text.length > 120000) {return { target: null as HTMLElement | null, lints: {} };}- const lintsBySource = await this.lintProvider(text, window.location.hostname, {+ const language = getTargetLanguage(target);+ let lintsBySource = await this.lintProvider(text, window.location.hostname, {forceAllHeadings: isHeading(target),+ language,});++ if (isCM) {+ // We're about to modify a reference, so let's work on a copy.+ lintsBySource = window.structuredClone(lintsBySource);++ for (const lints of Object.values(lintsBySource)) {+ for (const lint of lints) {+ const offset_start = newLineIndices.findIndex((i) => i > lint.span.start);+ const offset_end = newLineIndices.findIndex((i) => i > lint.span.end);++ lint.span.start -= offset_start;+ lint.span.end -= offset_end;+ }+ }+ }+return { target: target as HTMLElement, lints: lintsBySource };}),);@@ -315,3 +353,17 @@ function getScrollableAncestors(element: Node): Element[] {return scrollables;}++function getTargetLanguage(target: Node): LintOptions['language'] | undefined {+ if (!(target instanceof Element)) return undefined;++ const language = target.getAttribute('data-language');+ switch (language) {+ case 'plaintext':+ case 'markdown':+ case 'typst':+ return language;+ default:+ return undefined;+ }+}diff --git a/packages/lint-framework/src/lint/computeLintBoxes.ts b/packages/lint-framework/src/lint/computeLintBoxes.tsindex a153ec2e6..932d885d5 100644--- a/packages/lint-framework/src/lint/computeLintBoxes.ts+++ b/packages/lint-framework/src/lint/computeLintBoxes.ts@@ -3,6 +3,7 @@ import { domRectToBox, type IgnorableLintBox, isBottomEdgeInBox, shrinkBoxToFitimport { getRangeForTextSpan } from './domUtils';import {getCkEditorRoot,+ getCMRoot,getDraftRoot,getLexicalRoot,getSlateRoot,@@ -114,6 +115,8 @@ function replaceValue(replaceLexicalValue(el, span, replacementText);} else if (getDraftRoot(el) != null) {replaceDraftValue(el, span, replacementText);+ } else if (getCMRoot(el) != null) {+ replaceCodeMirrorValue(el, span, replacementText);} else if (getSlateRoot(el) != null || getCkEditorRoot(el) != null) {replaceRichTextEditorValue(el, span, replacementText);} else {@@ -228,6 +231,45 @@ function replaceRichTextEditorValue(}}+function replaceCodeMirrorValue(+ el: HTMLElement,+ span: { start: number; end: number },+ replacementText: string,+) {+ const setup = selectSpanInEditor(el, span);+ if (!setup) return;++ const { doc, sel, range } = setup;++ const evInit: InputEventInit = {+ bubbles: true,+ cancelable: true,+ inputType: 'insertReplacementText',+ data: replacementText,+ };++ if ('StaticRange' in self) {+ evInit.targetRanges = [new StaticRange(range)];+ }++ const beforeEvt = new InputEvent('beforeinput', evInit);+ el.dispatchEvent(beforeEvt);++ // CodeMirror-style editors can handle replacement during beforeinput.+ // If not handled, fall back to direct DOM replacement.+ if (!beforeEvt.defaultPrevented) {+ replaceTextInRange(doc, sel, range, replacementText);+ el.dispatchEvent(+ new InputEvent('input', {+ bubbles: true,+ cancelable: false,+ inputType: 'insertReplacementText',+ data: replacementText,+ }),+ );+ }+}+function replaceTextInRange(doc: Document, sel: Selection, range: Range, replacementText: string) {const startContainer = range.startContainer;const endContainer = range.endContainer;