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