Open History to see the last commit
1import { use, 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 themeName = resolveDiffThemeName(theme);
48 const tokenize = (text: string, lang: string) =>
49 highlighter.codeToTokens(text, { lang, theme: themeName }).tokens;
50 const lines = keyedLines(
51 code,
52 withEmbeddedScripts(code, tokenize(code, language), embedded, tokenize),
53 );
54
55 // A fragment, not the bare array: the compiler only treats this as a component when it
56 // returns JSX, since `use` alone does not count as a hook call for that inference.
57 return (
58 <>
59 {lines.map(({ key, tokens, ending }) => (
60 <span key={key}>
61 {wordClassName
62 ? wordsOf(tokens).map((part) =>
63 typeof part === "string" ? (
64 part
65 ) : (
66 <span key={part.key} className={wordClassName}>
67 {part.pieces.map((piece) => (
68 <span key={piece.key} style={syntaxTokenStyle(piece.token)}>
69 {piece.text}
70 </span>
71 ))}
72 </span>
73 ),
74 )
75 : tokens.map((token) => (
76 <span key={`${token.offset}:${token.content}`} style={syntaxTokenStyle(token)}>
77 {token.content}
78 </span>
79 ))}
80 {ending}
81 </span>
82 ))}
83 </>
84 );
85}
86
87export function withEmbeddedScripts(
88 code: string,
89 lines: TokenLines,
90 embedded: ReadonlyArray<EmbeddedScript>,
91 tokenize: (text: string, language: string) => TokenLines,
92): TokenLines {
93 if (embedded.length === 0) return lines;
94 const styles = Array.from<SyntaxToken | undefined>({ length: code.length });
95 for (const token of lines.flat()) {
96 styles.fill(token, token.offset, token.offset + token.content.length);
97 }
98 for (const script of embedded) {
99 let scriptLines: TokenLines;
100 try {
101 scriptLines = tokenize(script.text, script.language);
102 } catch {
103 continue;
104 }
105 for (const token of scriptLines.flat()) {
106 if (token.content === "") continue;
107 const last = token.offset + token.content.length - 1;
108 styles.fill(token, script.starts[token.offset], script.ends[last]);
109 }
110 }
111 return restyledLines(code, styles);
112}
113
114function restyledLines(
115 code: string,
116 styles: ReadonlyArray<SyntaxToken | undefined>,
117): SyntaxToken[][] {
118 const lines: SyntaxToken[][] = [];
119 let start = 0;
120 for (const lineBreak of [...code.matchAll(/\r?\n/gu), undefined]) {
121 const end = lineBreak?.index ?? code.length;
122 const tokens: SyntaxToken[] = [];
123 for (let index = start; index < end;) {
124 const style = styles[index];
125 let next = index + 1;
126 while (
127 next < end &&
128 styles[next]?.color === style?.color &&
129 styles[next]?.fontStyle === style?.fontStyle
130 ) {
131 next += 1;
132 }
133 tokens.push({
134 content: code.slice(index, next),
135 offset: index,
136 ...(style?.color ? { color: style.color } : {}),
137 ...(style?.fontStyle ? { fontStyle: style.fontStyle } : {}),
138 });
139 index = next;
140 }
141 lines.push(tokens);
142 if (lineBreak) start = lineBreak.index + lineBreak[0].length;
143 }
144 return lines;
145}
146
147/**
148 * Shiki drops `\n` and `\r\n` from tokens alike, so CRLF has to come back from
149 * the source.
150 */
151export function keyedLines<Token extends SyntaxToken>(
152 code: string,
153 lines: ReadonlyArray<ReadonlyArray<Token>>,
154) {
155 const endings = code.match(/\r?\n/gu) ?? [];
156 let lineStart = 0;
157 return lines.map((tokens, index) => {
158 const text = tokens.map((token) => token.content).join("");
159 const key = `${lineStart}:${text}`;
160 const ending = endings[index] ?? "";
161 lineStart += text.length + ending.length;
162 return { key, tokens, ending };
163 });
164}
165
166interface Word {
167 readonly key: string;
168 readonly pieces: Array<{ key: string; text: string; token: SyntaxToken }>;
169}
170
171export function wordsOf(tokens: ReadonlyArray<SyntaxToken>): Array<string | Word> {
172 const parts: Array<string | Word> = [];
173 let word: Word | null = null;
174 for (const token of tokens) {
175 let offset = token.offset;
176 for (const text of token.content.split(/(\s+)/u)) {
177 if (text === "") continue;
178 if (/^\s/u.test(text)) {
179 parts.push(text);
180 word = null;
181 } else {
182 if (!word) {
183 word = { key: String(offset), pieces: [] };
184 parts.push(word);
185 }
186 word.pieces.push({ key: String(offset), text, token });
187 }
188 offset += text.length;
189 }
190 }
191 return parts;
192}