Open History to see the last commit
1import { use, useMemo, type CSSProperties } from "react";
2
3import { resolveDiffThemeName } from "../../lib/diffRendering";
4import type { EmbeddedScript } from "../../lib/embeddedScripts";
5import { getSyntaxHighlighterPromise } from "../../lib/syntaxHighlighting";
6
7interface SyntaxToken {
8 readonly content: string;
9 readonly offset: number;
10 readonly color?: string;
11 readonly fontStyle?: number;
12}
13
14type TokenLines = ReadonlyArray<ReadonlyArray<SyntaxToken>>;
15
16const NO_EMBEDDED_SCRIPTS: ReadonlyArray<EmbeddedScript> = [];
17
18function syntaxTokenStyle(token: SyntaxToken): CSSProperties {
19 const fontStyle = token.fontStyle ?? 0;
20 return {
21 ...(token.color ? { color: token.color } : {}),
22 ...(fontStyle & 1 ? { fontStyle: "italic" } : {}),
23 ...(fontStyle & 2 ? { fontWeight: 700 } : {}),
24 ...(fontStyle & 4 ? { textDecoration: "underline" } : {}),
25 };
26}
27
28/**
29 * Suspends while the grammar loads; wrap it in Suspense with the plain text as
30 * the fallback.
31 */
32export function HighlightedTokens({
33 code,
34 language,
35 embedded = NO_EMBEDDED_SCRIPTS,
36 theme,
37 wordClassName,
38}: {
39 code: string;
40 language: string;
41 embedded?: ReadonlyArray<EmbeddedScript>;
42 theme: "light" | "dark";
43 wordClassName?: string;
44}) {
45 const highlighter = use(getSyntaxHighlighterPromise(language));
46 for (const script of embedded) use(getSyntaxHighlighterPromise(script.language));
47 const lines = useMemo(() => {
48 const themeName = resolveDiffThemeName(theme);
49 const tokenize = (text: string, lang: string) =>
50 highlighter.codeToTokens(text, { lang, theme: themeName }).tokens;
51 return keyedLines(
52 code,
53 withEmbeddedScripts(code, tokenize(code, language), embedded, tokenize),
54 );
55 }, [code, embedded, highlighter, language, theme]);
56
57 return lines.map(({ key, tokens, ending }) => (
58 <span key={key}>
59 {wordClassName
60 ? wordsOf(tokens).map((part) =>
61 typeof part === "string" ? (
62 part
63 ) : (
64 <span key={part.key} className={wordClassName}>
65 {part.pieces.map((piece) => (
66 <span key={piece.key} style={syntaxTokenStyle(piece.token)}>
67 {piece.text}
68 </span>
69 ))}
70 </span>
71 ),
72 )
73 : tokens.map((token) => (
74 <span key={`${token.offset}:${token.content}`} style={syntaxTokenStyle(token)}>
75 {token.content}
76 </span>
77 ))}
78 {ending}
79 </span>
80 ));
81}
82
83export function withEmbeddedScripts(
84 code: string,
85 lines: TokenLines,
86 embedded: ReadonlyArray<EmbeddedScript>,
87 tokenize: (text: string, language: string) => TokenLines,
88): TokenLines {
89 if (embedded.length === 0) return lines;
90 const styles = Array.from<SyntaxToken | undefined>({ length: code.length });
91 for (const token of lines.flat()) {
92 styles.fill(token, token.offset, token.offset + token.content.length);
93 }
94 for (const script of embedded) {
95 let scriptLines: TokenLines;
96 try {
97 scriptLines = tokenize(script.text, script.language);
98 } catch {
99 continue;
100 }
101 for (const token of scriptLines.flat()) {
102 if (token.content === "") continue;
103 const last = token.offset + token.content.length - 1;
104 styles.fill(token, script.starts[token.offset], script.ends[last]);
105 }
106 }
107 return restyledLines(code, styles);
108}
109
110function restyledLines(
111 code: string,
112 styles: ReadonlyArray<SyntaxToken | undefined>,
113): SyntaxToken[][] {
114 const lines: SyntaxToken[][] = [];
115 let start = 0;
116 for (const lineBreak of [...code.matchAll(/\r?\n/gu), undefined]) {
117 const end = lineBreak?.index ?? code.length;
118 const tokens: SyntaxToken[] = [];
119 for (let index = start; index < end;) {
120 const style = styles[index];
121 let next = index + 1;
122 while (
123 next < end &&
124 styles[next]?.color === style?.color &&
125 styles[next]?.fontStyle === style?.fontStyle
126 ) {
127 next += 1;
128 }
129 tokens.push({
130 content: code.slice(index, next),
131 offset: index,
132 ...(style?.color ? { color: style.color } : {}),
133 ...(style?.fontStyle ? { fontStyle: style.fontStyle } : {}),
134 });
135 index = next;
136 }
137 lines.push(tokens);
138 if (lineBreak) start = lineBreak.index + lineBreak[0].length;
139 }
140 return lines;
141}
142
143/**
144 * Shiki drops `\n` and `\r\n` from tokens alike, so CRLF has to come back from
145 * the source.
146 */
147export function keyedLines<Token extends SyntaxToken>(
148 code: string,
149 lines: ReadonlyArray<ReadonlyArray<Token>>,
150) {
151 const endings = code.match(/\r?\n/gu) ?? [];
152 let lineStart = 0;
153 return lines.map((tokens, index) => {
154 const text = tokens.map((token) => token.content).join("");
155 const key = `${lineStart}:${text}`;
156 const ending = endings[index] ?? "";
157 lineStart += text.length + ending.length;
158 return { key, tokens, ending };
159 });
160}
161
162interface Word {
163 readonly key: string;
164 readonly pieces: Array<{ key: string; text: string; token: SyntaxToken }>;
165}
166
167export function wordsOf(tokens: ReadonlyArray<SyntaxToken>): Array<string | Word> {
168 const parts: Array<string | Word> = [];
169 let word: Word | null = null;
170 for (const token of tokens) {
171 let offset = token.offset;
172 for (const text of token.content.split(/(\s+)/u)) {
173 if (text === "") continue;
174 if (/^\s/u.test(text)) {
175 parts.push(text);
176 word = null;
177 } else {
178 if (!word) {
179 word = { key: String(offset), pieces: [] };
180 parts.push(word);
181 }
182 word.pieces.push({ key: String(offset), text, token });
183 }
184 offset += text.length;
185 }
186 }
187 return parts;
188}