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