Open History to see the last commit
1import { Extension } from "@tiptap/core";
2import { type EditorState, Plugin, PluginKey } from "@tiptap/pm/state";
3import { Decoration, DecorationSet } from "@tiptap/pm/view";
4import type { Node as ProseMirrorNode } from "@tiptap/pm/model";
5
6import type { DiffThemeName } from "~/lib/diffRendering";
7import { languageOfInfoString } from "~/composer-code-languages";
8import { getSyntaxHighlighterPromise } from "~/lib/syntaxHighlighting";
9import { subscribeToThemeSyntax } from "~/themePalette";
10import { highlighterLanguageOf } from "./chat/MarkdownCodeBlock.logic";
11
12interface HighlightedBlock {
13 readonly signature: string;
14 readonly decorations: ReadonlyArray<{ from: number; to: number; color: string }>;
15}
16
17const composerCodeBlockHighlightKey = new PluginKey<DecorationSet>("composerCodeBlockHighlight");
18
19// Tokenizing larger fences can stall the main thread.
20const MAX_HIGHLIGHTED_CODE_BLOCK_LENGTH = 20_000;
21
22// Keep mapped colors while typing in long fences, then refresh after a pause.
23const DEFERRED_HIGHLIGHT_CODE_BLOCK_LENGTH = 2_000;
24const DEFERRED_HIGHLIGHT_DELAY_MS = 300;
25
26function shouldHighlightCodeBlock(code: string): boolean {
27 return code.length <= MAX_HIGHLIGHTED_CODE_BLOCK_LENGTH;
28}
29function blockSignature(node: ProseMirrorNode, theme: DiffThemeName): string {
30 return [theme, String(node.attrs.language ?? ""), node.textContent].join("\u0000");
31}
32
33/** Code blocks are always top-level; avoid walking the whole draft per keystroke. */
34function collectCodeBlocks(state: EditorState): Array<{ node: ProseMirrorNode; pos: number }> {
35 const blocks: Array<{ node: ProseMirrorNode; pos: number }> = [];
36 state.doc.forEach((node, pos) => {
37 if (node.type.name === "codeBlock") blocks.push({ node, pos });
38 });
39 return blocks;
40}
41
42export function composerCodeBlockHighlight(options: {
43 resolveTheme: () => DiffThemeName;
44}): Extension {
45 return Extension.create({
46 name: "composerCodeBlockHighlight",
47
48 addProseMirrorPlugins() {
49 // Prune obsolete signatures each scan so the cache is bounded by the document without evicting live
50 // blocks.
51 const cache = new Map<string, HighlightedBlock>();
52 // Track live signatures so late tokenization cannot restore edited-away blocks.
53 let live = new Set<string>();
54
55 return [
56 new Plugin<DecorationSet>({
57 key: composerCodeBlockHighlightKey,
58
59 state: {
60 // A swapped-in draft may hold fences already cached, which no tokenization repaints.
61 init: (_config, state) =>
62 buildDecorations(state, cache, options.resolveTheme(), DecorationSet.empty),
63 apply(transaction, value, _oldState, newState) {
64 const mapped = value.map(transaction.mapping, transaction.doc);
65 if (!transaction.docChanged && !transaction.getMeta(composerCodeBlockHighlightKey)) {
66 return mapped;
67 }
68 return buildDecorations(newState, cache, options.resolveTheme(), mapped);
69 },
70 },
71
72 props: {
73 decorations(state) {
74 return composerCodeBlockHighlightKey.getState(state);
75 },
76 },
77
78 view(view) {
79 let disposed = false;
80 let paintedTheme = options.resolveTheme();
81 let scannedDoc: ProseMirrorNode | null = null;
82 let deferredRefresh: ReturnType<typeof setTimeout> | undefined;
83
84 // Repaint dispatches and selection changes must not restart the debounce.
85 const refresh = (deferLong: boolean) => {
86 const theme = options.resolveTheme();
87 const themeChanged = theme !== paintedTheme;
88 paintedTheme = theme;
89 // Selection changes cannot affect tokens; avoid rebuilding every block's text signature.
90 if (!themeChanged && view.state.doc === scannedDoc) return;
91 clearTimeout(deferredRefresh);
92 scannedDoc = view.state.doc;
93 const blocks = collectCodeBlocks(view.state);
94 const signatures = new Set(blocks.map(({ node }) => blockSignature(node, theme)));
95 live = signatures;
96 for (const signature of cache.keys()) {
97 if (!live.has(signature)) cache.delete(signature);
98 }
99 const missing = blocks.filter(
100 ({ node }) =>
101 shouldHighlightCodeBlock(node.textContent) &&
102 !cache.has(blockSignature(node, theme)),
103 );
104 const pending =
105 deferLong && !themeChanged
106 ? missing.filter(
107 ({ node }) => node.textContent.length <= DEFERRED_HIGHLIGHT_CODE_BLOCK_LENGTH,
108 )
109 : missing;
110 if (pending.length < missing.length) {
111 deferredRefresh = setTimeout(() => {
112 scannedDoc = null;
113 refresh(false);
114 }, DEFERRED_HIGHLIGHT_DELAY_MS);
115 }
116 if (pending.length === 0) {
117 if (themeChanged) {
118 view.dispatch(view.state.tr.setMeta(composerCodeBlockHighlightKey, true));
119 }
120 return;
121 }
122
123 void Promise.allSettled(
124 pending.map(async ({ node }) => {
125 // Stored info includes metadata after the language; Shiki needs only the name.
126 const language = highlighterLanguageOf(
127 languageOfInfoString(String(node.attrs.language ?? "")) || "text",
128 );
129 const signature = blockSignature(node, theme);
130 // Cache failure as plain text to clear retained colors.
131 const highlighter = await getSyntaxHighlighterPromise(language).catch(() => null);
132 // An older request must not bypass the debounce if its text returns.
133 if (disposed || live !== signatures || cache.has(signature)) return;
134 cache.set(signature, {
135 signature,
136 decorations: highlighter
137 ? tokenizeBlock(highlighter, node.textContent, language, theme)
138 : [],
139 });
140 }),
141 ).then(() => {
142 if (disposed || live !== signatures) return;
143 view.dispatch(view.state.tr.setMeta(composerCodeBlockHighlightKey, true));
144 });
145 };
146
147 refresh(false);
148 // The theme lives on <html>, outside the editor, so nothing would
149 // otherwise tell the view a repaint is due.
150 const themeObserver = new MutationObserver(() => refresh(false));
151 themeObserver.observe(document.documentElement, {
152 attributeFilter: ["class"],
153 });
154 const unsubscribeSyntax = subscribeToThemeSyntax(() => refresh(false));
155
156 return {
157 update: () => refresh(true),
158 destroy() {
159 disposed = true;
160 clearTimeout(deferredRefresh);
161 themeObserver.disconnect();
162 unsubscribeSyntax();
163 },
164 };
165 },
166 }),
167 ];
168 },
169 });
170}
171
172type Highlighter = Awaited<ReturnType<typeof getSyntaxHighlighterPromise>>;
173
174export function tokenizeBlock(
175 highlighter: Highlighter,
176 code: string,
177 language: string,
178 theme: DiffThemeName,
179): ReadonlyArray<{ from: number; to: number; color: string }> {
180 let tokens;
181 try {
182 tokens = highlighter.codeToTokens(code, { lang: language, theme }).tokens;
183 } catch {
184 return [];
185 }
186
187 const decorations: Array<{ from: number; to: number; color: string }> = [];
188 let offset = 0;
189 for (const [lineIndex, line] of tokens.entries()) {
190 // The separator between lines, which Shiki drops; CRLF is two characters.
191 if (lineIndex > 0) offset += code.startsWith("\r\n", offset) ? 2 : 1;
192 for (const token of line) {
193 const length = token.content.length;
194 if (token.color && token.content.trim()) {
195 decorations.push({ from: offset, to: offset + length, color: token.color });
196 }
197 offset += length;
198 }
199 }
200 return decorations;
201}
202
203function buildDecorations(
204 state: EditorState,
205 cache: Map<string, HighlightedBlock>,
206 theme: DiffThemeName,
207 previous: DecorationSet,
208): DecorationSet {
209 const decorations: Decoration[] = [];
210 for (const { node, pos } of collectCodeBlocks(state)) {
211 if (!shouldHighlightCodeBlock(node.textContent)) continue;
212 const highlighted = cache.get(blockSignature(node, theme));
213 if (!highlighted) {
214 // A mapped token can span split fences and the paragraph between them.
215 const start = pos + 1;
216 const end = start + node.content.size;
217 for (const decoration of previous.find(start, end)) {
218 if (decoration.from >= start && decoration.to <= end) {
219 decorations.push(decoration);
220 continue;
221 }
222 const from = Math.max(decoration.from, start);
223 const to = Math.min(decoration.to, end);
224 if (from < to) decorations.push(colorDecoration(from, to, decoration.spec.color));
225 }
226 continue;
227 }
228 // Token offsets index the block's text, which lines up with document
229 // positions only because `codeBlock` is `text*` with no marks — one
230 // unmarked text node, so `content.size === textContent.length`. Allowing
231 // marks or hard breaks in the code block would desync these silently.
232 if (node.content.size !== node.textContent.length) continue;
233 const start = pos + 1;
234 for (const decoration of highlighted.decorations) {
235 decorations.push(
236 colorDecoration(start + decoration.from, start + decoration.to, decoration.color),
237 );
238 }
239 }
240 return DecorationSet.create(state.doc, decorations);
241}
242
243// Keep the color available when clipping mapped decorations to a fence.
244function colorDecoration(from: number, to: number, color: string): Decoration {
245 return Decoration.inline(from, to, { style: `color:${color}` }, { color });
246}