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/** Suspends during grammar loading; use plain text as the Suspense fallback. */
29export function HighlightedTokens({
30 code,
31 language,
32 embedded = NO_EMBEDDED_SCRIPTS,
33 theme,
34 wordClassName,
35}: {
36 code: string;
37 language: string;
38 embedded?: ReadonlyArray<EmbeddedScript>;
39 theme: "light" | "dark";
40 wordClassName?: string;
41}) {
42 const highlighter = use(getSyntaxHighlighterPromise(language));
43 for (const script of embedded) use(getSyntaxHighlighterPromise(script.language));
44 const themeName = resolveDiffThemeName(theme);
45 const tokenize = (text: string, lang: string) =>
46 highlighter.codeToTokens(text, { lang, theme: themeName }).tokens;
47 const lines = keyedLines(
48 code,
49 withEmbeddedScripts(code, tokenize(code, language), embedded, tokenize),
50 );
51
52 // The compiler requires JSX to recognize this component; `use` alone does not suffice.
53 return (
54 <>
55 {lines.map(({ key, tokens, ending }) => (
56 <span key={key}>
57 {wordClassName
58 ? wordsOf(tokens).map((part) =>
59 typeof part === "string" ? (
60 part
61 ) : (
62 <span key={part.key} className={wordClassName}>
63 {part.pieces.map((piece) => (
64 <span key={piece.key} style={syntaxTokenStyle(piece.token)}>
65 {piece.text}
66 </span>
67 ))}
68 </span>
69 ),
70 )
71 : tokens.map((token) => (
72 <span key={`${token.offset}:${token.content}`} style={syntaxTokenStyle(token)}>
73 {token.content}
74 </span>
75 ))}
76 {ending}
77 </span>
78 ))}
79 </>
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/** Restore CRLF from source; Shiki strips both line-ending forms. */
144export function keyedLines<Token extends SyntaxToken>(
145 code: string,
146 lines: ReadonlyArray<ReadonlyArray<Token>>,
147) {
148 const endings = code.match(/\r?\n/gu) ?? [];
149 let lineStart = 0;
150 return lines.map((tokens, index) => {
151 const text = tokens.map((token) => token.content).join("");
152 const key = `${lineStart}:${text}`;
153 const ending = endings[index] ?? "";
154 lineStart += text.length + ending.length;
155 return { key, tokens, ending };
156 });
157}
158
159interface Word {
160 readonly key: string;
161 readonly pieces: Array<{ key: string; text: string; token: SyntaxToken }>;
162}
163
164export function wordsOf(tokens: ReadonlyArray<SyntaxToken>): Array<string | Word> {
165 const parts: Array<string | Word> = [];
166 let word: Word | null = null;
167 for (const token of tokens) {
168 let offset = token.offset;
169 for (const text of token.content.split(/(\s+)/u)) {
170 if (text === "") continue;
171 if (/^\s/u.test(text)) {
172 parts.push(text);
173 word = null;
174 } else {
175 if (!word) {
176 word = { key: String(offset), pieces: [] };
177 parts.push(word);
178 }
179 word.pieces.push({ key: String(offset), text, token });
180 }
181 offset += text.length;
182 }
183 }
184 return parts;
185}