Open History to see the last commit
1import {
2 renderTokenLines,
3 type DiffsHighlighter,
4 type ThemedToken,
5 type TokensResult,
6} from "@pierre/diffs";
7
8import type { DiffThemeName } from "./diffRendering";
9
10function highlightedDocument(
11 result: TokensResult,
12 lines = renderTokenLines(result.tokens, {}),
13): { type: "root"; children: ReturnType<typeof renderTokenLines> } {
14 return {
15 type: "root" as const,
16 children: [
17 {
18 type: "element" as const,
19 tagName: "pre",
20 properties: {
21 class: "diffs",
22 style:
23 result.rootStyle === false
24 ? undefined
25 : (result.rootStyle ??
26 [
27 result.fg != null ? `color:${result.fg}` : "",
28 result.bg != null ? `background-color:${result.bg}` : "",
29 ]
30 .filter(Boolean)
31 .join(";")),
32 tabIndex: 0,
33 },
34 children: [
35 {
36 type: "element" as const,
37 tagName: "code",
38 properties: {},
39 children: lines.flatMap((line, index) =>
40 index === 0 ? [line] : [{ type: "text" as const, value: "\n" }, line],
41 ),
42 },
43 ],
44 },
45 ],
46 };
47}
48
49export function highlightCodeToHast(
50 highlighter: DiffsHighlighter,
51 code: string,
52 language: string,
53 theme: DiffThemeName,
54) {
55 return highlightedDocument(highlighter.codeToTokens(code, { lang: language, theme }));
56}
57
58export function createIncrementalHighlightedDocument(
59 highlighter: DiffsHighlighter,
60 language: string,
61 theme: DiffThemeName,
62) {
63 const options = { lang: language, theme };
64 let shell: TokensResult | undefined;
65 let tokenizer: ReturnType<DiffsHighlighter["createStreamTokenizer"]> | undefined;
66 let previous = "";
67 const completedLines: ReturnType<typeof renderTokenLines> = [];
68
69 function dispose() {
70 tokenizer?.dispose();
71 tokenizer = undefined;
72 previous = "";
73 completedLines.length = 0;
74 }
75
76 return Object.assign(
77 (code: string) => {
78 // ANSI and partial CRLF sequences need the full-source normalization path.
79 if (language === "ansi" || code.includes("\r")) {
80 dispose();
81 return highlightCodeToHast(highlighter, code, language, theme);
82 }
83 if (!code.startsWith(previous)) dispose();
84 // Created on first use so an unknown language throws inside the caller's fallback.
85 shell ??= highlighter.codeToTokens("", options);
86 tokenizer ??= highlighter.createStreamTokenizer(options);
87 const update = tokenizer.enqueue(code.slice(previous.length));
88 if (update instanceof Promise) {
89 dispose();
90 void update.catch(() => {});
91 return highlightCodeToHast(highlighter, code, language, theme);
92 }
93 previous = code;
94 let line: ThemedToken[] = [];
95 for (const token of update.stable) {
96 if (token.content === "\n") {
97 completedLines.push(...renderTokenLines([line], {}));
98 line = [];
99 } else line.push(token);
100 }
101 // Completed line nodes retain their identity while the final line changes.
102 return highlightedDocument(shell, [
103 ...completedLines,
104 ...renderTokenLines([update.unstable], {}),
105 ]);
106 },
107 { dispose },
108 );
109}