Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

composerCodeBlockHighlight.ts

231 lines9.4 KB

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 /** Guards against repainting a block whose text and language are unchanged. */
12 readonly signature: string;
13 readonly decorations: ReadonlyArray<{ from: number; to: number; color: string }>;
15​
16const composerCodeBlockHighlightKey = new PluginKey<DecorationSet>("composerCodeBlockHighlight");
17​
18/**
19 * Past this many characters a fence is left plain. Any edit changes a block's
20 * signature, so each keystroke re-tokenizes the whole block synchronously on
21 * the main thread: a few milliseconds for a couple of hundred lines, but ~80ms
22 * at a thousand, which stalls typing. 20k characters is roughly 400–500 lines
23 * of ordinary code; a fence that shrinks back under it is highlighted again.
24 */
25export const MAX_HIGHLIGHTED_CODE_BLOCK_LENGTH = 20_000;
26​
27export function shouldHighlightCodeBlock(code: string): boolean {
28 return code.length <= MAX_HIGHLIGHTED_CODE_BLOCK_LENGTH;
30function blockSignature(node: ProseMirrorNode, theme: DiffThemeName): string {
31 // A separator that cannot occur in a language name keeps the parts distinct.
32 return [theme, String(node.attrs.language ?? ""), node.textContent].join("\u0000");
34​
35/**
36 * The composer's code blocks, which are always top-level: list items and
37 * quotes cannot hold one. Scanning only the top level keeps a keystroke in a
38 * long draft from walking every node in it.
39 */
40function collectCodeBlocks(state: EditorState): Array<{ node: ProseMirrorNode; pos: number }> {
41 const blocks: Array<{ node: ProseMirrorNode; pos: number }> = [];
42 state.doc.forEach((node, pos) => {
43 if (node.type.name === "codeBlock") blocks.push({ node, pos });
44 });
45 return blocks;
47​
48/**
49 * Highlights composer code blocks with the same Shiki instance the chat view
50 * uses, painted as inline decorations so the text nodes stay editable.
51 *
52 * Highlighting is asynchronous and per block: a keystroke re-tokenizes only the
53 * block that changed, and only after its highlighter has resolved. Blocks whose
54 * text and language are unchanged reuse their previous decorations.
55 */
56export function composerCodeBlockHighlight(options: {
57 resolveTheme: () => DiffThemeName;
58}): Extension {
59 return Extension.create({
60 name: "composerCodeBlockHighlight",
61​
62 addProseMirrorPlugins() {
63 // Every keystroke in a code block mints a new signature, so each scan
64 // drops the signatures the document no longer holds. The cache is then
65 // bounded by the document itself, and no block it holds is ever evicted.
66 const cache = new Map<string, HighlightedBlock>();
67 // The latest scan's signatures, so a tokenize that resolves after its
68 // block was edited away does not put it back.
69 let live = new Set<string>();
70​
71 return [
72 new Plugin<DecorationSet>({
73 key: composerCodeBlockHighlightKey,
74​
75 state: {
76 init: () => DecorationSet.empty,
77 apply(transaction, value, _oldState, newState) {
78 if (!transaction.docChanged && !transaction.getMeta(composerCodeBlockHighlightKey)) {
79 return value.map(transaction.mapping, transaction.doc);
80 }
81 return buildDecorations(newState, cache, options.resolveTheme());
82 },
83 },
84​
85 props: {
86 decorations(state) {
87 return composerCodeBlockHighlightKey.getState(state);
88 },
89 },
90​
91 view(view) {
92 let disposed = false;
93 let paintedTheme = options.resolveTheme();
94 let scannedDoc: ProseMirrorNode | null = null;
95​
96 /**
97 * Tokenizes any block missing from the cache, then repaints once.
98 * Returning early when nothing is pending is what stops the
99 * dispatch below from re-triggering this on its own update.
100 */
101 const refresh = () => {
102 const theme = options.resolveTheme();
103 const themeChanged = theme !== paintedTheme;
104 paintedTheme = theme;
105 // A selection change cannot alter what needs tokenizing, and
106 // building a signature means concatenating every block's text.
107 if (!themeChanged && view.state.doc === scannedDoc) return;
108 scannedDoc = view.state.doc;
109 const blocks = collectCodeBlocks(view.state);
110 live = new Set(blocks.map(({ node }) => blockSignature(node, theme)));
111 for (const signature of cache.keys()) {
112 if (!live.has(signature)) cache.delete(signature);
113 }
114 const pending = blocks.filter(
115 ({ node }) =>
116 shouldHighlightCodeBlock(node.textContent) &&
117 !cache.has(blockSignature(node, theme)),
118 );
119 if (pending.length === 0) {
120 // A theme switch keeps every signature but changes which one
121 // applies, so the painted decorations still have to be rebuilt.
122 if (themeChanged) {
123 view.dispatch(view.state.tr.setMeta(composerCodeBlockHighlightKey, true));
124 }
125 return;
126 }
127​
128 // Settled rather than all: a block whose highlighter fails to
129 // load stays plain, and the others are still painted.
130 void Promise.allSettled(
131 pending.map(async ({ node }) => {
132 // The stored info string keeps everything after the language
133 // (`js title=x`); Shiki wants only the name.
134 const language =
135 languageOfInfoString(String(node.attrs.language ?? "")) || "text";
136 const signature = blockSignature(node, theme);
137 const highlighter = await getSyntaxHighlighterPromise(language);
138 if (disposed || cache.has(signature) || !live.has(signature)) return;
139 cache.set(signature, {
140 signature,
141 decorations: tokenizeBlock(highlighter, node.textContent, language, theme),
142 });
143 }),
144 ).then(() => {
145 if (disposed) return;
146 view.dispatch(view.state.tr.setMeta(composerCodeBlockHighlightKey, true));
147 });
148 };
149​
150 refresh();
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);
154 themeObserver.observe(document.documentElement, {
155 attributeFilter: ["class"],
156 });
157​
158 return {
159 update: refresh,
160 destroy() {
161 disposed = true;
162 themeObserver.disconnect();
163 },
164 };
165 },
166 }),
167 ];
168 },
169 });
171​
172type Highlighter = Awaited<ReturnType<typeof getSyntaxHighlighterPromise>>;
173​
174/** Flattens Shiki's line/token structure into offsets within the block's text. */
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 // An unsupported language should read as plain text, not break the editor.
186 return [];
187 }
188​
189 const decorations: Array<{ from: number; to: number; color: string }> = [];
190 let offset = 0;
191 for (const [lineIndex, line] of tokens.entries()) {
192 // The separator between lines, which Shiki drops; CRLF is two characters.
193 if (lineIndex > 0) offset += code.startsWith("\r\n", offset) ? 2 : 1;
194 for (const token of line) {
195 const length = token.content.length;
196 if (token.color && token.content.trim()) {
197 decorations.push({ from: offset, to: offset + length, color: token.color });
198 }
199 offset += length;
200 }
201 }
202 return decorations;
204​
205function buildDecorations(
206 state: EditorState,
207 cache: Map<string, HighlightedBlock>,
208 theme: DiffThemeName,
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) continue;
215 // Token offsets index the block's text, which lines up with document
216 // positions only because `codeBlock` is `text*` with no marks — one
217 // unmarked text node, so `content.size === textContent.length`. Allowing
218 // marks or hard breaks in the code block would desync these silently.
219 if (node.content.size !== node.textContent.length) continue;
220 // +1 steps past the code block's opening token into its text.
221 const start = pos + 1;
222 for (const decoration of highlighted.decorations) {
223 decorations.push(
224 Decoration.inline(start + decoration.from, start + decoration.to, {
225 style: `color:${decoration.color}`,
226 }),
227 );
228 }
229 }
230 return DecorationSet.create(state.doc, decorations);