TypeScript
perf(web): long composer code blocks no longer re-highlight on every keystroke (#19439)
MohibShaikh09792213363d
diff --git a/apps/web/src/components/composerCodeBlockHighlight.test.ts b/apps/web/src/components/composerCodeBlockHighlight.test.tsindex 409db501956..adc725eae4a 100644--- a/apps/web/src/components/composerCodeBlockHighlight.test.ts+++ b/apps/web/src/components/composerCodeBlockHighlight.test.ts@@ -1,7 +1,8 @@import { Editor } from "@tiptap/core";-import type { EditorView } from "@tiptap/pm/view";+import { EditorState, type Plugin, type Transaction } from "@tiptap/pm/state";+import type { DecorationSet, EditorView } from "@tiptap/pm/view";import StarterKit from "@tiptap/starter-kit";-import { afterEach, describe, expect, it, vi } from "vite-plus/test";+import { afterEach, describe, expect, it, onTestFinished, vi } from "vite-plus/test";import { ComposerCodeBlockExtension } from "~/composer-rich-text-doc";import type { DiffThemeName } from "~/lib/diffRendering";@@ -16,7 +17,7 @@ import {vi.mock("~/lib/syntaxHighlighting", () => ({ getSyntaxHighlighterPromise: vi.fn() }));-const THEME = "github-dark" as DiffThemeName;+const THEME = "pierre-dark" as DiffThemeName;function fakeHighlighter(colorFor: (content: string) => string | undefined) {return {@@ -138,3 +139,181 @@ describe("a highlighter that fails to load", () => {await expect(repainted).resolves.toBeUndefined();});});++describe("highlighting edited fences", () => {+ afterEach(() => {+ vi.useRealTimers();+ vi.unstubAllGlobals();+ });++ async function mountFence(text: string, resolveTheme = () => THEME) {+ vi.useFakeTimers();+ const highlighter = fakeHighlighter((content) =>+ content.startsWith("x") ? "#ff0000" : undefined,+ );+ const tokenize = vi.spyOn(highlighter, "codeToTokens");+ vi.mocked(getSyntaxHighlighterPromise).mockResolvedValue(highlighter);+ const editor = new Editor({+ extensions: [+ StarterKit.configure({ codeBlock: false, trailingNode: false }),+ ComposerCodeBlockExtension,+ composerCodeBlockHighlight({ resolveTheme }),+ ],+ content: {+ type: "doc",+ content: [+ { type: "codeBlock", attrs: { language: "ts" }, content: [{ type: "text", text }] },+ ],+ },+ });+ vi.stubGlobal("document", { documentElement: {} });+ vi.stubGlobal(+ "MutationObserver",+ class {+ observe() {}+ disconnect() {}+ },+ );+ const plugin = editor.extensionManager.plugins.find((candidate) =>+ (candidate as unknown as { key: string }).key.startsWith("composerCodeBlockHighlight"),+ ) as Plugin<DecorationSet>;+ // A headless editor holds no plugins in its state, so give this one its own.+ let state = EditorState.create({ doc: editor.state.doc, plugins: [plugin] });+ // Like a real view, every dispatch updates the plugin's view.+ let pluginView: ReturnType<NonNullable<typeof plugin.spec.view>> | undefined;+ const view = {+ get state() {+ return state;+ },+ dispatch: (transaction: Transaction) => {+ const previous = state;+ state = state.apply(transaction);+ pluginView?.update?.(view, previous);+ },+ } as unknown as EditorView;+ pluginView = plugin.spec.view!(view);+ onTestFinished(() => {+ pluginView?.destroy?.();+ editor.destroy();+ });+ await vi.advanceTimersByTimeAsync(0);+ return {+ tokenize,+ ranges: () =>+ plugin+ .getState(state)!+ .find()+ .map(({ from, to }) => [from, to]),+ edit: async (change: (transaction: Transaction) => Transaction) => {+ view.dispatch(change(state.tr));+ await vi.advanceTimersByTimeAsync(0);+ },+ colored: () =>+ plugin+ .getState(state)!+ .find()+ .map((decoration) => state.doc.textBetween(decoration.from, decoration.to)),+ };+ }++ it("maps colors while typing above 2,000 characters and refreshes 300 ms after the last edit", async () => {+ const fence = await mountFence(`x ${"y".repeat(1_999)}`);+ expect(fence.tokenize).toHaveBeenCalledTimes(1);++ await fence.edit((tr) => tr.insertText("x ", 1));+ await vi.advanceTimersByTimeAsync(250);+ await fence.edit((tr) => tr.insertText("y ", 1));+ await vi.advanceTimersByTimeAsync(299);++ expect(fence.tokenize).toHaveBeenCalledTimes(1);+ expect(fence.colored()).toEqual(["x"]);+ expect(fence.ranges()).toEqual([[5, 6]]);++ await vi.advanceTimersByTimeAsync(1);++ expect(fence.tokenize).toHaveBeenCalledTimes(2);+ expect(fence.colored()).toEqual(["x", "x"]);+ });++ it("ignores a pending highlight when its text is edited away and restored", async () => {+ const fence = await mountFence(`x ${"y".repeat(1_999)}`);+ const staleHighlighter = fakeHighlighter(() => "#00ff00");+ const staleTokenize = vi.spyOn(staleHighlighter, "codeToTokens");+ let finishLoading!: () => void;+ vi.mocked(getSyntaxHighlighterPromise).mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ finishLoading = () => resolve(staleHighlighter);+ }),+ );++ await fence.edit((tr) => tr.insertText("x ", 1));+ await vi.advanceTimersByTimeAsync(300);+ await fence.edit((tr) => tr.insertText("y ", 1));+ await fence.edit((tr) => tr.delete(1, 3));+ finishLoading();+ await vi.advanceTimersByTimeAsync(0);++ expect(staleTokenize).not.toHaveBeenCalled();+ expect(fence.colored()).toEqual(["x"]);+ await vi.advanceTimersByTimeAsync(300);+ expect(fence.tokenize).toHaveBeenCalledTimes(2);+ expect(fence.colored()).toEqual(["x", "x"]);+ });++ it("refreshes a long fence immediately when the theme changes during a pending edit", async () => {+ let theme = THEME;+ const fence = await mountFence(`x ${"y".repeat(1_999)}`, () => theme);+ await fence.edit((tr) => tr.insertText("x ", 1));++ theme = "pierre-light";+ await fence.edit((tr) => tr.setMeta("theme", true));++ expect(fence.tokenize).toHaveBeenCalledTimes(2);+ expect(fence.tokenize).toHaveBeenLastCalledWith(expect.any(String), { lang: "ts", theme });+ expect(fence.colored()).toEqual(["x", "x"]);+ await vi.advanceTimersByTimeAsync(300);+ expect(fence.tokenize).toHaveBeenCalledTimes(2);+ });++ it("refreshes immediately when an edit leaves the fence at 2,000 characters", async () => {+ const fence = await mountFence(`x ${"y".repeat(1_996)}`);++ await fence.edit((tr) => tr.insertText("x ", 1));++ expect(fence.tokenize).toHaveBeenCalledTimes(2);+ expect(fence.colored()).toEqual(["x", "x"]);+ });++ it("clips a split token to its fences without coloring the paragraph between them", async () => {+ const fence = await mountFence("x".repeat(6_000));++ await fence.edit((tr) =>+ tr+ .split(3_001)+ .insert(+ 3_002,+ tr.doc.type.schema.node("paragraph", null, [tr.doc.type.schema.text("plain")]),+ ),+ );++ expect(fence.tokenize).toHaveBeenCalledTimes(1);+ expect(fence.ranges()).toEqual([+ [1, 3_001],+ [3_010, 6_010],+ ]);+ expect(fence.colored()).toEqual(["x".repeat(3_000), "x".repeat(3_000)]);+ });++ it("clears retained colors when the new language highlighter fails to load", async () => {+ const fence = await mountFence(`x ${"y".repeat(1_999)}`);+ vi.mocked(getSyntaxHighlighterPromise).mockRejectedValue(new Error("Shiki failed to load"));++ await fence.edit((tr) => tr.setNodeMarkup(0, undefined, { language: "py" }));+ expect(fence.colored()).toEqual(["x"]);++ await vi.advanceTimersByTimeAsync(300);++ expect(fence.colored()).toEqual([]);+ });+});diff --git a/apps/web/src/components/composerCodeBlockHighlight.ts b/apps/web/src/components/composerCodeBlockHighlight.tsindex 91c3a669b99..86621f5d787 100644--- a/apps/web/src/components/composerCodeBlockHighlight.ts+++ b/apps/web/src/components/composerCodeBlockHighlight.ts@@ -14,13 +14,13 @@ interface HighlightedBlock {const composerCodeBlockHighlightKey = new PluginKey<DecorationSet>("composerCodeBlockHighlight");-/**- * Any edit changes a block's signature, so each keystroke re-tokenizes the- * whole block synchronously on the main thread: a few milliseconds for a couple- * of hundred lines, but ~80ms at a thousand, which stalls typing.- */+// Tokenizing larger fences can stall the main thread.export const MAX_HIGHLIGHTED_CODE_BLOCK_LENGTH = 20_000;+// Keep mapped colors while typing in long fences, then refresh after a pause.+const DEFERRED_HIGHLIGHT_CODE_BLOCK_LENGTH = 2_000;+const DEFERRED_HIGHLIGHT_DELAY_MS = 300;+export function shouldHighlightCodeBlock(code: string): boolean {return code.length <= MAX_HIGHLIGHTED_CODE_BLOCK_LENGTH;}@@ -63,10 +63,11 @@ export function composerCodeBlockHighlight(options: {state: {init: () => DecorationSet.empty,apply(transaction, value, _oldState, newState) {+ const mapped = value.map(transaction.mapping, transaction.doc);if (!transaction.docChanged && !transaction.getMeta(composerCodeBlockHighlightKey)) {- return value.map(transaction.mapping, transaction.doc);+ return mapped;}- return buildDecorations(newState, cache, options.resolveTheme());+ return buildDecorations(newState, cache, options.resolveTheme(), mapped);},},@@ -80,29 +81,41 @@ export function composerCodeBlockHighlight(options: {let disposed = false;let paintedTheme = options.resolveTheme();let scannedDoc: ProseMirrorNode | null = null;+ let deferredRefresh: ReturnType<typeof setTimeout> | undefined;- /**- * Returning early when nothing is pending is what stops the- * dispatch below from re-triggering this on its own update.- */- const refresh = () => {+ // Repaint dispatches and selection changes must not restart the debounce.+ const refresh = (deferLong: boolean) => {const theme = options.resolveTheme();const themeChanged = theme !== paintedTheme;paintedTheme = theme;// A selection change cannot alter what needs tokenizing, and// building a signature means concatenating every block's text.if (!themeChanged && view.state.doc === scannedDoc) return;+ clearTimeout(deferredRefresh);scannedDoc = view.state.doc;const blocks = collectCodeBlocks(view.state);- live = new Set(blocks.map(({ node }) => blockSignature(node, theme)));+ const signatures = new Set(blocks.map(({ node }) => blockSignature(node, theme)));+ live = signatures;for (const signature of cache.keys()) {if (!live.has(signature)) cache.delete(signature);}- const pending = blocks.filter(+ const missing = blocks.filter(({ node }) =>shouldHighlightCodeBlock(node.textContent) &&!cache.has(blockSignature(node, theme)),);+ const pending =+ deferLong && !themeChanged+ ? missing.filter(+ ({ node }) => node.textContent.length <= DEFERRED_HIGHLIGHT_CODE_BLOCK_LENGTH,+ )+ : missing;+ if (pending.length < missing.length) {+ deferredRefresh = setTimeout(() => {+ scannedDoc = null;+ refresh(false);+ }, DEFERRED_HIGHLIGHT_DELAY_MS);+ }if (pending.length === 0) {if (themeChanged) {view.dispatch(view.state.tr.setMeta(composerCodeBlockHighlightKey, true));@@ -117,31 +130,36 @@ export function composerCodeBlockHighlight(options: {const language =languageOfInfoString(String(node.attrs.language ?? "")) || "text";const signature = blockSignature(node, theme);- const highlighter = await getSyntaxHighlighterPromise(language);- if (disposed || cache.has(signature) || !live.has(signature)) return;+ // Cache failure as plain text to clear retained colors.+ const highlighter = await getSyntaxHighlighterPromise(language).catch(() => null);+ // An older request must not bypass the debounce if its text returns.+ if (disposed || live !== signatures || cache.has(signature)) return;cache.set(signature, {signature,- decorations: tokenizeBlock(highlighter, node.textContent, language, theme),+ decorations: highlighter+ ? tokenizeBlock(highlighter, node.textContent, language, theme)+ : [],});}),).then(() => {- if (disposed) return;+ if (disposed || live !== signatures) return;view.dispatch(view.state.tr.setMeta(composerCodeBlockHighlightKey, true));});};- refresh();+ refresh(false);// The theme lives on <html>, outside the editor, so nothing would// otherwise tell the view a repaint is due.- const themeObserver = new MutationObserver(refresh);+ const themeObserver = new MutationObserver(() => refresh(false));themeObserver.observe(document.documentElement, {attributeFilter: ["class"],});return {- update: refresh,+ update: () => refresh(true),destroy() {disposed = true;+ clearTimeout(deferredRefresh);themeObserver.disconnect();},};@@ -187,12 +205,27 @@ function buildDecorations(state: EditorState,cache: Map<string, HighlightedBlock>,theme: DiffThemeName,+ previous: DecorationSet,): DecorationSet {const decorations: Decoration[] = [];for (const { node, pos } of collectCodeBlocks(state)) {if (!shouldHighlightCodeBlock(node.textContent)) continue;const highlighted = cache.get(blockSignature(node, theme));- if (!highlighted) continue;+ if (!highlighted) {+ // A mapped token can span split fences and the paragraph between them.+ const start = pos + 1;+ const end = start + node.content.size;+ for (const decoration of previous.find(start, end)) {+ if (decoration.from >= start && decoration.to <= end) {+ decorations.push(decoration);+ continue;+ }+ const from = Math.max(decoration.from, start);+ const to = Math.min(decoration.to, end);+ if (from < to) decorations.push(colorDecoration(from, to, decoration.spec.color));+ }+ continue;+ }// Token offsets index the block's text, which lines up with document// positions only because `codeBlock` is `text*` with no marks — one// unmarked text node, so `content.size === textContent.length`. Allowing@@ -201,11 +234,14 @@ function buildDecorations(const start = pos + 1;for (const decoration of highlighted.decorations) {decorations.push(- Decoration.inline(start + decoration.from, start + decoration.to, {- style: `color:${decoration.color}`,- }),+ colorDecoration(start + decoration.from, start + decoration.to, decoration.color),);}}return DecorationSet.create(state.doc, decorations);}++// Keep the color available when clipping mapped decorations to a fence.+function colorDecoration(from: number, to: number, color: string): Decoration {+ return Decoration.inline(from, to, { style: `color:${color}` }, { color });+}