Open History to see the last commit
1import type { DiffsHighlighter } from "@pierre/diffs";
2
3import type { DiffThemeName } from "./diffRendering";
4
5function codeChildren(root: ReturnType<DiffsHighlighter["codeToHast"]>) {
6 const pre = root.children.find((node) => node.type === "element" && node.tagName === "pre");
7 if (pre?.type !== "element") throw new Error("Missing highlighted pre element");
8 const code = pre.children.find((node) => node.type === "element" && node.tagName === "code");
9 if (code?.type !== "element") throw new Error("Missing highlighted code element");
10 return code.children;
11}
12
13export function createIncrementalHighlightedDocument(
14 highlighter: DiffsHighlighter,
15 language: string,
16 theme: DiffThemeName,
17): (code: string) => ReturnType<DiffsHighlighter["codeToHast"]> {
18 const options = { lang: language, theme };
19 const newline = { type: "text" as const, value: "\n" };
20 let cached:
21 | {
22 prefix: string;
23 state: ReturnType<DiffsHighlighter["getLastGrammarState"]>;
24 children: ReturnType<typeof codeChildren>;
25 }
26 | undefined;
27
28 return (code: string) => {
29 // Plain text and ANSI do not have a TextMate grammar state. A CR at the end
30 // of a chunk can still become a CRLF, so keep that input on the full path.
31 if (
32 !language ||
33 ["text", "plaintext", "plain", "txt", "ansi"].includes(language) ||
34 code.includes("\r")
35 ) {
36 return highlighter.codeToHast(code, options);
37 }
38 if (cached && !code.startsWith(cached.prefix)) cached = undefined;
39 const end = code.lastIndexOf("\n") + 1;
40 if (end > (cached?.prefix.length ?? 0)) {
41 // Omit the final newline: Shiki would tokenize an extra empty line and
42 // advance the grammar state twice before we process the following line.
43 const root = highlighter.codeToHast(code.slice(cached?.prefix.length ?? 0, end - 1), {
44 ...options,
45 ...(cached ? { grammarState: cached.state } : {}),
46 });
47 const state = highlighter.getLastGrammarState(root);
48 if (!state) {
49 cached = undefined;
50 return highlighter.codeToHast(code, options);
51 }
52 cached = {
53 prefix: code.slice(0, end),
54 state,
55 children: [...(cached ? [...cached.children, newline] : []), ...codeChildren(root)],
56 };
57 }
58 const prefix = cached;
59 if (!prefix) return highlighter.codeToHast(code, options);
60 return highlighter.codeToHast(code.slice(prefix.prefix.length), {
61 ...options,
62 grammarState: prefix.state,
63 transformers: [
64 {
65 code: (node) => ({ ...node, children: [...prefix.children, newline, ...node.children] }),
66 },
67 ],
68 });
69 };
70}