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/**
18 * Any edit changes a block's signature, so each keystroke re-tokenizes the
19 * whole block synchronously on the main thread: a few milliseconds for a couple
20 * of hundred lines, but ~80ms at a thousand, which stalls typing.
21 */
22export const MAX_HIGHLIGHTED_CODE_BLOCK_LENGTH = 20_000;
23
24export function 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 if (!transaction.docChanged && !transaction.getMeta(composerCodeBlockHighlightKey)) {
67 return value.map(transaction.mapping, transaction.doc);
68 }
69 return buildDecorations(newState, cache, options.resolveTheme());
70 },
71 },
72
73 props: {
74 decorations(state) {
75 return composerCodeBlockHighlightKey.getState(state);
76 },
77 },
78
79 view(view) {
80 let disposed = false;
81 let paintedTheme = options.resolveTheme();
82 let scannedDoc: ProseMirrorNode | null = null;
83
84 /**
85 * Returning early when nothing is pending is what stops the
86 * dispatch below from re-triggering this on its own update.
87 */
88 const refresh = () => {
89 const theme = options.resolveTheme();
90 const themeChanged = theme !== paintedTheme;
91 paintedTheme = theme;
92 // A selection change cannot alter what needs tokenizing, and
93 // building a signature means concatenating every block's text.
94 if (!themeChanged && view.state.doc === scannedDoc) return;
95 scannedDoc = view.state.doc;
96 const blocks = collectCodeBlocks(view.state);
97 live = new Set(blocks.map(({ node }) => blockSignature(node, theme)));
98 for (const signature of cache.keys()) {
99 if (!live.has(signature)) cache.delete(signature);
100 }
101 const pending = blocks.filter(
102 ({ node }) =>
103 shouldHighlightCodeBlock(node.textContent) &&
104 !cache.has(blockSignature(node, theme)),
105 );
106 if (pending.length === 0) {
107 if (themeChanged) {
108 view.dispatch(view.state.tr.setMeta(composerCodeBlockHighlightKey, true));
109 }
110 return;
111 }
112
113 void Promise.allSettled(
114 pending.map(async ({ node }) => {
115 // The stored info string keeps everything after the language
116 // (`js title=x`); Shiki wants only the name.
117 const language =
118 languageOfInfoString(String(node.attrs.language ?? "")) || "text";
119 const signature = blockSignature(node, theme);
120 const highlighter = await getSyntaxHighlighterPromise(language);
121 if (disposed || cache.has(signature) || !live.has(signature)) return;
122 cache.set(signature, {
123 signature,
124 decorations: tokenizeBlock(highlighter, node.textContent, language, theme),
125 });
126 }),
127 ).then(() => {
128 if (disposed) return;
129 view.dispatch(view.state.tr.setMeta(composerCodeBlockHighlightKey, true));
130 });
131 };
132
133 refresh();
134 // The theme lives on <html>, outside the editor, so nothing would
135 // otherwise tell the view a repaint is due.
136 const themeObserver = new MutationObserver(refresh);
137 themeObserver.observe(document.documentElement, {
138 attributeFilter: ["class"],
139 });
140
141 return {
142 update: refresh,
143 destroy() {
144 disposed = true;
145 themeObserver.disconnect();
146 },
147 };
148 },
149 }),
150 ];
151 },
152 });
153}
154
155type Highlighter = Awaited<ReturnType<typeof getSyntaxHighlighterPromise>>;
156
157export function tokenizeBlock(
158 highlighter: Highlighter,
159 code: string,
160 language: string,
161 theme: DiffThemeName,
162): ReadonlyArray<{ from: number; to: number; color: string }> {
163 let tokens;
164 try {
165 tokens = highlighter.codeToTokens(code, { lang: language, theme }).tokens;
166 } catch {
167 return [];
168 }
169
170 const decorations: Array<{ from: number; to: number; color: string }> = [];
171 let offset = 0;
172 for (const [lineIndex, line] of tokens.entries()) {
173 // The separator between lines, which Shiki drops; CRLF is two characters.
174 if (lineIndex > 0) offset += code.startsWith("\r\n", offset) ? 2 : 1;
175 for (const token of line) {
176 const length = token.content.length;
177 if (token.color && token.content.trim()) {
178 decorations.push({ from: offset, to: offset + length, color: token.color });
179 }
180 offset += length;
181 }
182 }
183 return decorations;
184}
185
186function buildDecorations(
187 state: EditorState,
188 cache: Map<string, HighlightedBlock>,
189 theme: DiffThemeName,
190): DecorationSet {
191 const decorations: Decoration[] = [];
192 for (const { node, pos } of collectCodeBlocks(state)) {
193 if (!shouldHighlightCodeBlock(node.textContent)) continue;
194 const highlighted = cache.get(blockSignature(node, theme));
195 if (!highlighted) continue;
196 // Token offsets index the block's text, which lines up with document
197 // positions only because `codeBlock` is `text*` with no marks — one
198 // unmarked text node, so `content.size === textContent.length`. Allowing
199 // marks or hard breaks in the code block would desync these silently.
200 if (node.content.size !== node.textContent.length) continue;
201 const start = pos + 1;
202 for (const decoration of highlighted.decorations) {
203 decorations.push(
204 Decoration.inline(start + decoration.from, start + decoration.to, {
205 style: `color:${decoration.color}`,
206 }),
207 );
208 }
209 }
210 return DecorationSet.create(state.doc, decorations);
211}