xonecas.io
70160
Ce

cel-tui / commit d4e7188

feat(components): add themed wrapped syntax highlight

xonecas2026-04-10 d4e7188328a22ac51c3a3b347ff1477486b58c46 parent 19e5301

4 files changed

examples/syntax-highlight.ts+114−12
@@ -8,7 +8,12 @@
88 */
99
1010 import { cel, VStack, HStack, Text, ProcessTerminal } from "@cel-tui/core";
11-import { Divider, Spacer, SyntaxHighlight } from "@cel-tui/components";
11+import {
12+ Divider,
13+ Spacer,
14+ SyntaxHighlight,
15+ type SyntaxHighlightTheme,
16+} from "@cel-tui/components";
1217
1318 const LANGUAGE = "typescript";
1419 const MIN_COLS = 52;
@@ -16,6 +21,69 @@ const MIN_ROWS = 16;
1621 const CHUNK_SIZE = 3;
1722 const TICK_MS = 18;
1823
24+const CUSTOM_THEME: SyntaxHighlightTheme = {
25+ name: "cel-demo-sunset",
26+ type: "dark",
27+ fg: "#f8f8f2",
28+ bg: "#1f2335",
29+ tokenColors: [
30+ { settings: { foreground: "#f8f8f2" } },
31+ {
32+ scope: ["comment", "string.quoted.docstring.multi"],
33+ settings: { foreground: "#7f849c", fontStyle: "italic" },
34+ },
35+ {
36+ scope: ["keyword", "storage", "entity.name.operator"],
37+ settings: { foreground: "#ff79c6" },
38+ },
39+ {
40+ scope: ["string", "markup.inline"],
41+ settings: { foreground: "#f1fa8c" },
42+ },
43+ {
44+ scope: ["constant.numeric", "constant.language", "constant.character"],
45+ settings: { foreground: "#ffb86c" },
46+ },
47+ {
48+ scope: ["entity.name.function", "support.function", "meta.function-call"],
49+ settings: { foreground: "#50fa7b" },
50+ },
51+ {
52+ scope: [
53+ "entity.name.type",
54+ "support.type",
55+ "support.class",
56+ "entity.other.inherited-class",
57+ ],
58+ settings: { foreground: "#8be9fd" },
59+ },
60+ {
61+ scope: [
62+ "variable.parameter",
63+ "meta.object-literal.key",
64+ "meta.property-name",
65+ ],
66+ settings: { foreground: "#bd93f9" },
67+ },
68+ ],
69+};
70+
71+const THEME_OPTIONS: ReadonlyArray<{
72+ label: string;
73+ help: string;
74+ theme?: SyntaxHighlightTheme;
75+}> = [
76+ {
77+ label: "terminal ansi16",
78+ help: "Default theme follows terminal defaults plus ANSI slots.",
79+ },
80+ {
81+ label: "custom sunset",
82+ help: "Custom Shiki theme remapped onto cel ANSI slots.",
83+ theme: CUSTOM_THEME,
84+ },
85+];
86+
1987 const FULL_CODE = [
2088 "/**",
2189 " * Streaming syntax highlight demo.",
@@ -38,10 +106,12 @@ const FULL_CODE = [
38106 "for (const user of users) {",
39107 " console.log(greet(user));",
40108 "}",
109+ "Long ass line to see the wrapping behaviuour on the example.Long ass line to see the wrapping behaviuour on the example.Long ass line to see the wrapping behaviuour on the example.Long ass line to see the wrapping behaviuour on the example.Long ass line to see the wrapping behaviuour on the example.Long ass line to see the wrapping behaviuour on the example.",
41110 ].join("\n");
42111
43112 let content = "";
44113 let paused = false;
114+let themeIndex = 0;
45115 let streamTimer: ReturnType<typeof setTimeout> | null = null;
46116
47117 function quit() {
@@ -100,6 +170,11 @@ function togglePause() {
100170 cel.render();
101171 }
102172
173+function toggleTheme() {
174+ themeIndex = (themeIndex + 1) % THEME_OPTIONS.length;
175+ cel.render();
176+}
177+
103178 startStreaming();
104179
105180 cel.init(new ProcessTerminal());
@@ -135,6 +210,7 @@ cel.viewport(() => {
135210
136211 const status = isDone() ? "done" : paused ? "paused" : "streaming";
137212 const statusColor = isDone() ? "color02" : paused ? "color03" : "color06";
213+ const theme = THEME_OPTIONS[themeIndex]!;
138214
139215 return VStack(
140216 {
@@ -143,12 +219,14 @@ cel.viewport(() => {
143219 if (key === "ctrl+q" || key === "ctrl+c") quit();
144220 if (key === "ctrl+r") restart();
145221 if (key === "ctrl+p") togglePause();
222+ if (key === "ctrl+t") toggleTheme();
146223 },
147224 },
148225 [
149- HStack({ padding: { x: 1 } }, [
226+ HStack({ padding: { x: 1 }, gap: 2 }, [
150227 Text("SyntaxHighlight Demo", { bold: true, fgColor: "color06" }),
151228 Spacer(),
229+ Text(`theme: ${theme.label}`, { fgColor: "color03" }),
152230 Text(LANGUAGE, { fgColor: "color08" }),
153231 ]),
154232 Divider({ fgColor: "color08" }),
@@ -159,7 +237,7 @@ cel.viewport(() => {
159237 }),
160238 ]),
161239 HStack({ padding: { x: 1 } }, [
162- Text("Shiki loads lazily. Colors appear after first render.", {
240+ Text(theme.help, {
163241 fgColor: "color08",
164242 italic: true,
165243 }),
@@ -172,17 +250,41 @@ cel.viewport(() => {
172250 scrollbar: true,
173251 padding: { x: 1 },
174252 },
175- [SyntaxHighlight(content, LANGUAGE)],
253+ [SyntaxHighlight(content, LANGUAGE, { theme: theme.theme })],
176254 ),
177255 Divider({ fgColor: "color08" }),
178- HStack({ padding: { x: 1 }, gap: 1 }, [
179- Text("Ctrl+R", { fgColor: "color07", bgColor: "color08", bold: true }),
180- Text("restart", { fgColor: "color08" }),
181- Text(" "),
182- Text("Ctrl+P", { fgColor: "color07", bgColor: "color08", bold: true }),
183- Text("pause/resume", { fgColor: "color08" }),
184- Spacer(),
185- Text("Ctrl+Q quit", { fgColor: "color08" }),
256+ VStack({ padding: { x: 1 } }, [
257+ HStack({ gap: 1 }, [
258+ Text("Ctrl+R", {
259+ fgColor: "color07",
260+ bgColor: "color08",
261+ bold: true,
262+ }),
263+ Text("restart", { fgColor: "color08" }),
264+ Text(" "),
265+ Text("Ctrl+P", {
266+ fgColor: "color07",
267+ bgColor: "color08",
268+ bold: true,
269+ }),
270+ Text("pause", { fgColor: "color08" }),
271+ Text(" "),
272+ Text("Ctrl+T", {
273+ fgColor: "color07",
274+ bgColor: "color08",
275+ bold: true,
276+ }),
277+ Text("theme", { fgColor: "color08" }),
278+ ]),
279+ HStack({ gap: 1 }, [
280+ Spacer(),
281+ Text("Ctrl+Q", {
282+ fgColor: "color07",
283+ bgColor: "color08",
284+ bold: true,
285+ }),
286+ Text("quit", { fgColor: "color08" }),
287+ ]),
186288 ]),
187289 ],
188290 );
packages/components/src/index.ts+5−1
@@ -34,4 +34,8 @@ export {
3434 type BlockToken,
3535 type InlineSpan,
3636 } from "./markdown.js";
37-export { SyntaxHighlight } from "./syntax-highlight.js";
37+export {
38+ SyntaxHighlight,
39+ type SyntaxHighlightProps,
40+ type SyntaxHighlightTheme,
41+} from "./syntax-highlight.js";
packages/components/src/syntax-highlight.test.ts+91−2
@@ -1,6 +1,10 @@
11 import { describe, expect, test } from "bun:test";
2+import { measureContentHeight } from "@cel-tui/core";
23 import type { ContainerNode, Node, TextNode } from "@cel-tui/types";
3-import { SyntaxHighlight } from "./syntax-highlight.js";
4+import {
5+ SyntaxHighlight,
6+ type SyntaxHighlightProps,
7+} from "./syntax-highlight.js";
48
59 function asContainer(node: Node): ContainerNode {
610 expect(node.type === "vstack" || node.type === "hstack").toBe(true);
@@ -22,6 +26,29 @@ function firstText(line: Node): TextNode {
2226 return asText(container.children[0]!);
2327 }
2428
29+function textNodes(node: ContainerNode): TextNode[] {
30+ return node.children.flatMap((line) => {
31+ const container = asContainer(line);
32+ return container.children.map((child) => asText(child));
33+ });
34+}
35+
36+function findText(node: ContainerNode, content: string): TextNode {
37+ const text = textNodes(node).find((token) => token.content === content);
38+ if (!text) {
39+ throw new Error(`Missing token: ${content}`);
40+ }
41+ return text;
42+}
43+
44+function findTextContaining(node: ContainerNode, content: string): TextNode {
45+ const text = textNodes(node).find((token) => token.content.includes(content));
46+ if (!text) {
47+ throw new Error(`Missing token containing: ${content}`);
48+ }
49+ return text;
50+}
51+
2552 function hasStyledText(node: ContainerNode): boolean {
2653 return node.children.some((line) => {
2754 const container = asContainer(line);
@@ -41,11 +68,12 @@ function hasStyledText(node: ContainerNode): boolean {
4168 async function waitForHighlight(
4269 content: string,
4370 language: string,
71+ props?: SyntaxHighlightProps,
4472 ): Promise<ContainerNode> {
4573 const deadline = Date.now() + 10_000;
4674
4775 while (true) {
48- const node = SyntaxHighlight(content, language);
76+ const node = SyntaxHighlight(content, language, props);
4977 if (hasStyledText(node)) {
5078 return node;
5179 }
@@ -76,10 +104,71 @@ describe("SyntaxHighlight", () => {
76104
77105 const firstLine = asContainer(node.children[0]!);
78106 const firstToken = asText(firstLine.children[0]!);
107+ expect(firstLine.props.flexWrap).toBe("wrap");
79108 expect(firstToken.content).toBe("const");
80109 expect(firstToken.props.fgColor).toBeDefined();
81110 });
82111
112+ test("wraps plain fallback content by default", () => {
113+ const node = SyntaxHighlight(
114+ "alpha beta gamma delta epsilon",
115+ "definitely-not-real",
116+ );
117+
118+ expect(measureContentHeight(node, { width: 10 })).toBeGreaterThan(1);
119+ });
120+
121+ test("wraps highlighted content by default", async () => {
122+ const node = await waitForHighlight(
123+ "const alpha beta gamma delta epsilon = 42",
124+ "javascript",
125+ );
126+
127+ expect(measureContentHeight(node, { width: 12 })).toBeGreaterThan(1);
128+ });
129+
130+ test("default ansi16 theme uses terminal defaults for base text", async () => {
131+ const node = await waitForHighlight("let value = 42", "javascript");
132+
133+ expect(findText(node, "let").props.fgColor).toBe("color05");
134+ expect(findTextContaining(node, "value").props.fgColor).toBeUndefined();
135+ expect(findText(node, "42").props.fgColor).toBe("color03");
136+ });
137+
138+ test("custom theme object overrides default colors", async () => {
139+ const node = await waitForHighlight(
140+ 'const message = "hello"',
141+ "javascript",
142+ {
143+ theme: {
144+ name: "syntax-highlight-test-theme",
145+ type: "dark",
146+ fg: "#e5e5e5",
147+ bg: "#000000",
148+ tokenColors: [
149+ { settings: { foreground: "#e5e5e5" } },
150+ {
151+ scope: ["keyword", "storage"],
152+ settings: { foreground: "#cd3131" },
153+ },
154+ { scope: "string", settings: { foreground: "#0dbc79" } },
155+ ],
156+ },
157+ },
158+ );
159+
160+ expect(findText(node, "const").props.fgColor).toBe("color01");
161+ expect(findTextContaining(node, "hello").props.fgColor).toBe("color02");
162+ });
163+
164+ test("bundled shiki theme names load on demand", async () => {
165+ const node = await waitForHighlight("const value = 42", "javascript", {
166+ theme: "dark-plus",
167+ });
168+
169+ expect(findText(node, "const").props.fgColor).toBeDefined();
170+ });
171+
83172 test("keeps one rendered child per source line", async () => {
84173 await waitForHighlight("const first = 1", "javascript");
85174 const node = SyntaxHighlight(
packages/components/src/syntax-highlight.ts+324−57
@@ -1,13 +1,19 @@
11 import type { Color, ContainerNode, Node, StyleProps } from "@cel-tui/types";
22 import { cel, HStack, Text, VStack } from "@cel-tui/core";
3-import type { BuiltinLanguage, Highlighter, ThemedToken } from "shiki";
3+import type {
4+ BuiltinLanguage,
5+ BuiltinTheme,
6+ Highlighter,
7+ ThemeRegistration,
8+ ThemedToken,
9+} from "shiki";
410 import type {
511 ShikiStreamTokenizer,
612 ShikiStreamTokenizerEnqueueResult,
713 } from "shiki-stream";
814
9-const INTERNAL_THEME = "min-dark";
10-const MAX_STATES_PER_LANGUAGE = 4;
15+const DEFAULT_THEME_NAME = "cel-ansi16";
16+const MAX_STATES_PER_KEY = 4;
1117
1218 const FONT_STYLE_ITALIC = 1;
1319 const FONT_STYLE_BOLD = 2;
@@ -31,6 +37,20 @@ const ANSI_SLOT_HEX: ReadonlyArray<readonly [Color, string]> = [
3137 ["color14", "#29b8db"],
3238 ["color15", "#ffffff"],
3339 ];
40+const ANSI_SLOT_HEX_BY_COLOR = new Map<Color, string>(ANSI_SLOT_HEX);
41+
42+export type SyntaxHighlightTheme = BuiltinTheme | ThemeRegistration;
43+
44+/** Props for the {@link SyntaxHighlight} component. */
45+export interface SyntaxHighlightProps {
46+ /**
47+ * Optional Shiki theme override.
48+ *
49+ * Pass either a bundled Shiki theme name (for example `"dark-plus"`)
50+ * or a custom Shiki theme registration object.
51+ */
52+ theme?: SyntaxHighlightTheme;
53+}
3454
3555 type SyntaxHighlightStatus = "ready" | "loading" | "error" | "unsupported";
3656
@@ -40,12 +60,128 @@ interface SyntaxHighlightRuntime {
4060 ShikiStreamTokenizer: (typeof import("shiki-stream"))["ShikiStreamTokenizer"];
4161 }
4262
63+interface ResolvedSyntaxHighlightTheme {
64+ cacheKey: string;
65+ loadableTheme: SyntaxHighlightTheme;
66+ themeName: string;
67+ defaultFg?: string;
68+ defaultBg?: string;
69+ useTerminalDefaults: boolean;
70+}
71+
72+const DEFAULT_THEME: ThemeRegistration = {
73+ name: DEFAULT_THEME_NAME,
74+ displayName: "cel ANSI 16",
75+ type: "dark",
76+ fg: ansiHex("color07"),
77+ bg: ansiHex("color00"),
78+ colors: {
79+ foreground: ansiHex("color07"),
80+ "editor.foreground": ansiHex("color07"),
81+ "editor.background": ansiHex("color00"),
82+ "terminal.ansiBlack": ansiHex("color00"),
83+ "terminal.ansiRed": ansiHex("color01"),
84+ "terminal.ansiGreen": ansiHex("color02"),
85+ "terminal.ansiYellow": ansiHex("color03"),
86+ "terminal.ansiBlue": ansiHex("color04"),
87+ "terminal.ansiMagenta": ansiHex("color05"),
88+ "terminal.ansiCyan": ansiHex("color06"),
89+ "terminal.ansiWhite": ansiHex("color07"),
90+ "terminal.ansiBrightBlack": ansiHex("color08"),
91+ "terminal.ansiBrightRed": ansiHex("color09"),
92+ "terminal.ansiBrightGreen": ansiHex("color10"),
93+ "terminal.ansiBrightYellow": ansiHex("color11"),
94+ "terminal.ansiBrightBlue": ansiHex("color12"),
95+ "terminal.ansiBrightMagenta": ansiHex("color13"),
96+ "terminal.ansiBrightCyan": ansiHex("color14"),
97+ "terminal.ansiBrightWhite": ansiHex("color15"),
98+ },
99+ tokenColors: [
100+ { settings: { foreground: ansiHex("color07") } },
101+ {
102+ scope: ["comment", "string.quoted.docstring.multi"],
103+ settings: { foreground: ansiHex("color08"), fontStyle: "italic" },
104+ },
105+ {
106+ scope: ["string", "markup.inline"],
107+ settings: { foreground: ansiHex("color02") },
108+ },
109+ {
110+ scope: [
111+ "constant.numeric",
112+ "constant.language",
113+ "constant.character",
114+ "constant.other.placeholder",
115+ ],
116+ settings: { foreground: ansiHex("color03") },
117+ },
118+ {
119+ scope: ["keyword", "storage", "entity.name.operator"],
120+ settings: { foreground: ansiHex("color05") },
121+ },
122+ {
123+ scope: ["entity.name.function", "support.function", "meta.function-call"],
124+ settings: { foreground: ansiHex("color04") },
125+ },
126+ {
127+ scope: [
128+ "entity.name.type",
129+ "support.type",
130+ "support.class",
131+ "entity.other.inherited-class",
132+ ],
133+ settings: { foreground: ansiHex("color06") },
134+ },
135+ {
136+ scope: ["variable.parameter"],
137+ settings: { foreground: ansiHex("color11") },
138+ },
139+ {
140+ scope: [
141+ "entity.other.attribute-name",
142+ "meta.object-literal.key",
143+ "meta.property-name",
144+ "support.type.property-name",
145+ ],
146+ settings: { foreground: ansiHex("color06") },
147+ },
148+ {
149+ scope: ["entity.name.tag", "string.regexp", "invalid"],
150+ settings: { foreground: ansiHex("color01") },
151+ },
152+ {
153+ scope: ["markup.bold", "strong", "markup.heading"],
154+ settings: { fontStyle: "bold", foreground: ansiHex("color09") },
155+ },
156+ {
157+ scope: ["markup.italic", "emphasis"],
158+ settings: { fontStyle: "italic" },
159+ },
160+ {
161+ scope: ["markup.underline", "meta.link.inline.markdown"],
162+ settings: { foreground: ansiHex("color04"), fontStyle: "underline" },
163+ },
164+ ],
165+};
166+
167+const DEFAULT_RESOLVED_THEME: ResolvedSyntaxHighlightTheme = {
168+ cacheKey: DEFAULT_THEME_NAME,
169+ loadableTheme: DEFAULT_THEME,
170+ themeName: DEFAULT_THEME_NAME,
171+ defaultFg: normalizeHex(DEFAULT_THEME.fg ?? ansiHex("color07")),
172+ defaultBg: normalizeHex(DEFAULT_THEME.bg ?? ansiHex("color00")),
173+ useTerminalDefaults: true,
174+};
175+
43176 const rgbCache = new Map<string, readonly [number, number, number]>();
44177 const colorSlotCache = new Map<string, Color>();
45178 const loadedLanguages = new Set<string>();
46179 const loadingLanguages = new Map<string, Promise<void>>();
47180 const languageErrors = new Map<string, Error>();
48-const statesByLanguage = new Map<string, SyntaxHighlightState[]>();
181+const loadedThemes = new Set<string>();
182+const loadingThemes = new Map<string, Promise<void>>();
183+const themeErrors = new Map<string, Error>();
184+const statesByKey = new Map<string, SyntaxHighlightState[]>();
49185
50186 let runtimePromise: Promise<SyntaxHighlightRuntime> | null = null;
51187 let runtimeInstance: SyntaxHighlightRuntime | null = null;
@@ -58,6 +194,7 @@ interface SyntaxHighlightState {
58194 lastContent: string;
59195 tokenizer: ShikiStreamTokenizer;
60196 lastNode: ContainerNode | null;
197+ theme: ResolvedSyntaxHighlightTheme;
61198 }
62199
63200 interface HighlightRun {
@@ -65,10 +202,66 @@ interface HighlightRun {
65202 style: StyleProps;
66203 }
67204
205+function ansiHex(color: Color): string {
206+ const hex = ANSI_SLOT_HEX_BY_COLOR.get(color);
207+ if (!hex) {
208+ throw new Error(`Unknown ANSI slot: ${color}`);
209+ }
210+ return hex;
211+}
212+
68213 function normalizeError(error: unknown): Error {
69214 return error instanceof Error ? error : new Error(String(error));
70215 }
71216
217+function hashString(input: string): string {
218+ let hash = 2166136261;
219+ for (let i = 0; i < input.length; i++) {
220+ hash = Math.imul(hash ^ input.charCodeAt(i), 16777619);
221+ }
222+ return (hash >>> 0).toString(36);
223+}
224+
225+function resolveTheme(
226+ theme?: SyntaxHighlightTheme,
227+): ResolvedSyntaxHighlightTheme {
228+ if (!theme) {
229+ return DEFAULT_RESOLVED_THEME;
230+ }
231+
232+ if (typeof theme === "string") {
233+ return {
234+ cacheKey: `builtin:${theme}`,
235+ loadableTheme: theme,
236+ themeName: theme,
237+ useTerminalDefaults: false,
238+ };
239+ }
240+
241+ const serialized = JSON.stringify(theme);
242+ const cacheHash = hashString(serialized);
243+ const themeName =
244+ typeof theme.name === "string" && theme.name.length > 0
245+ ? theme.name
246+ : `cel-syntax-${cacheHash}`;
247+ const loadableTheme =
248+ themeName === theme.name ? theme : { ...theme, name: themeName };
249+
250+ return {
251+ cacheKey: `custom:${cacheHash}`,
252+ loadableTheme,
253+ themeName,
254+ useTerminalDefaults: false,
255+ };
256+}
257+
258+function stateKey(
259+ language: string,
260+ theme: ResolvedSyntaxHighlightTheme,
261+): string {
262+ return `${language}\u0000${theme.cacheKey}`;
263+}
264+
72265 function getRuntimePromise(): Promise<SyntaxHighlightRuntime> {
73266 if (runtimeError) {
74267 return Promise.reject(runtimeError);
@@ -105,12 +298,13 @@ function getHighlighterPromise(): Promise<Highlighter> {
105298 highlighterPromise = getRuntimePromise()
106299 .then((runtime) =>
107300 runtime.createHighlighter({
108- themes: [INTERNAL_THEME],
301+ themes: [DEFAULT_THEME],
109302 langs: [],
110303 }),
111304 )
112305 .then((highlighter) => {
113306 highlighterInstance = highlighter;
307+ loadedThemes.add(DEFAULT_RESOLVED_THEME.cacheKey);
114308 return highlighter;
115309 })
116310 .catch((error) => {
@@ -132,8 +326,16 @@ function hasBundledLanguage(
132326 return Object.hasOwn(runtime.bundledLanguages, language);
133327 }
134328
135-function ensureLanguageReady(language: string): SyntaxHighlightStatus {
136- if (runtimeError || highlighterError || languageErrors.has(language)) {
329+function ensureHighlightReady(
330+ language: string,
331+ theme: ResolvedSyntaxHighlightTheme,
332+): SyntaxHighlightStatus {
333+ if (
334+ runtimeError ||
335+ highlighterError ||
336+ languageErrors.has(language) ||
337+ themeErrors.has(theme.cacheKey)
338+ ) {
137339 return "error";
138340 }
139341
@@ -146,58 +348,86 @@ function ensureLanguageReady(language: string): SyntaxHighlightStatus {
146348 return "unsupported";
147349 }
148350
149- if (loadedLanguages.has(language) && highlighterInstance) {
150- return "ready";
351+ if (!highlighterInstance) {
352+ void getHighlighterPromise();
353+ return "loading";
151354 }
152355
153- if (!loadingLanguages.has(language)) {
154- const promise = getHighlighterPromise()
155- .then((highlighter) =>
156- highlighter.loadLanguage(language as BuiltinLanguage),
157- )
158- .then(() => {
159- loadedLanguages.add(language);
160- })
161- .catch((error) => {
162- languageErrors.set(language, normalizeError(error));
163- })
164- .finally(() => {
165- loadingLanguages.delete(language);
166- cel.render();
167- });
356+ let pending = false;
357+
358+ if (!loadedThemes.has(theme.cacheKey)) {
359+ pending = true;
360+
361+ if (!loadingThemes.has(theme.cacheKey)) {
362+ const promise = getHighlighterPromise()
363+ .then((highlighter) => highlighter.loadTheme(theme.loadableTheme))
364+ .then(() => {
365+ loadedThemes.add(theme.cacheKey);
366+ })
367+ .catch((error) => {
368+ themeErrors.set(theme.cacheKey, normalizeError(error));
369+ })
370+ .finally(() => {
371+ loadingThemes.delete(theme.cacheKey);
372+ cel.render();
373+ });
374+
375+ loadingThemes.set(theme.cacheKey, promise);
376+ }
377+ }
168378
169- loadingLanguages.set(language, promise);
379+ if (!loadedLanguages.has(language)) {
380+ pending = true;
381+
382+ if (!loadingLanguages.has(language)) {
383+ const promise = getHighlighterPromise()
384+ .then((highlighter) =>
385+ highlighter.loadLanguage(language as BuiltinLanguage),
386+ )
387+ .then(() => {
388+ loadedLanguages.add(language);
389+ })
390+ .catch((error) => {
391+ languageErrors.set(language, normalizeError(error));
392+ })
393+ .finally(() => {
394+ loadingLanguages.delete(language);
395+ cel.render();
396+ });
397+
398+ loadingLanguages.set(language, promise);
399+ }
170400 }
171401
172- return "loading";
402+ return pending ? "loading" : "ready";
173403 }
174404
175-function getStates(language: string): SyntaxHighlightState[] {
176- let states = statesByLanguage.get(language);
405+function getStates(key: string): SyntaxHighlightState[] {
406+ let states = statesByKey.get(key);
177407 if (!states) {
178408 states = [];
179- statesByLanguage.set(language, states);
409+ statesByKey.set(key, states);
180410 }
181411 return states;
182412 }
183413
184-function touchState(language: string, state: SyntaxHighlightState): void {
185- const states = getStates(language);
414+function touchState(key: string, state: SyntaxHighlightState): void {
415+ const states = getStates(key);
186416 const index = states.indexOf(state);
187417 if (index !== -1) {
188418 states.splice(index, 1);
189419 }
190420 states.push(state);
191- if (states.length > MAX_STATES_PER_LANGUAGE) {
421+ if (states.length > MAX_STATES_PER_KEY) {
192422 states.shift();
193423 }
194424 }
195425
196426 function findState(
197- language: string,
427+ key: string,
198428 content: string,
199429 ): SyntaxHighlightState | undefined {
200- const states = getStates(language);
430+ const states = getStates(key);
201431
202432 for (let i = states.length - 1; i >= 0; i--) {
203433 const state = states[i]!;
@@ -225,6 +455,7 @@ function findState(
225455
226456 function createState(
227457 language: string,
458+ theme: ResolvedSyntaxHighlightTheme,
228459 highlighter: Highlighter,
229460 runtime: SyntaxHighlightRuntime,
230461 ): SyntaxHighlightState {
@@ -233,9 +464,10 @@ function createState(
233464 tokenizer: new runtime.ShikiStreamTokenizer({
234465 highlighter,
235466 lang: language,
236- theme: INTERNAL_THEME,
467+ theme: theme.themeName,
237468 }),
238469 lastNode: null,
470+ theme,
239471 };
240472 }
241473
@@ -361,15 +593,26 @@ function colorToSlot(color: string | undefined): Color | undefined {
361593 return best;
362594 }
363595
364-function tokenToStyle(token: ThemedToken): StyleProps {
596+function tokenToStyle(
597+ token: ThemedToken,
598+ theme: ResolvedSyntaxHighlightTheme,
599+): StyleProps {
365600 const fontStyle =
366601 typeof token.fontStyle === "number" && token.fontStyle > 0
367602 ? token.fontStyle
368603 : 0;
604+ const tokenFg = token.color ? normalizeHex(token.color) : undefined;
605+ const tokenBg = token.bgColor ? normalizeHex(token.bgColor) : undefined;
369606
370607 return {
371- fgColor: colorToSlot(token.color),
372- bgColor: colorToSlot(token.bgColor),
608+ fgColor:
609+ theme.useTerminalDefaults && tokenFg === theme.defaultFg
610+ ? undefined
611+ : colorToSlot(tokenFg),
612+ bgColor:
613+ theme.useTerminalDefaults && tokenBg === theme.defaultBg
614+ ? undefined
615+ : colorToSlot(tokenBg),
373616 italic: (fontStyle & FONT_STYLE_ITALIC) !== 0 || undefined,
374617 bold: (fontStyle & FONT_STYLE_BOLD) !== 0 || undefined,
375618 underline: (fontStyle & FONT_STYLE_UNDERLINE) !== 0 || undefined,
@@ -404,11 +647,14 @@ function pushRun(
404647 line.push({ content, style });
405648 }
406649
407-function tokensToLines(tokens: readonly ThemedToken[]): HighlightRun[][] {
650+function tokensToLines(
651+ tokens: readonly ThemedToken[],
652+ theme: ResolvedSyntaxHighlightTheme,
653+): HighlightRun[][] {
408654 const lines: HighlightRun[][] = [[]];
409655
410656 for (const token of tokens) {
411- const style = tokenToStyle(token);
657+ const style = tokenToStyle(token, theme);
412658 const pieces = token.content.split("\n");
413659
414660 for (let i = 0; i < pieces.length; i++) {
@@ -423,14 +669,21 @@ function tokensToLines(tokens: readonly ThemedToken[]): HighlightRun[][] {
423669 return lines;
424670 }
425671
426-function lineToNode(line: HighlightRun[]): Node {
427- if (line.length === 0) {
428- return HStack({}, [Text("")]);
672+function runToNodes(run: HighlightRun): Node[] {
673+ const pieces = run.content.match(/\S+|\s+/g);
674+ if (!pieces) {
675+ return [];
429676 }
430677
678+ return pieces.map((piece) => Text(piece, run.style));
679+}
680+
681+function lineToNode(line: HighlightRun[]): Node {
682+ const children = line.flatMap(runToNodes);
683+
431684 return HStack(
432- {},
433- line.map((run) => Text(run.content, run.style)),
685+ { flexWrap: "wrap" },
686+ children.length > 0 ? children : [Text("")],
434687 );
435688 }
436689
@@ -438,7 +691,9 @@ function renderPlainContent(content: string): ContainerNode {
438691 const lines = content.split("\n");
439692 return VStack(
440693 {},
441- lines.map((line) => HStack({}, [Text(line)])),
694+ lines.map((line) =>
695+ lineToNode(line.length > 0 ? [{ content: line, style: {} }] : []),
696+ ),
442697 );
443698 }
444699
@@ -447,10 +702,10 @@ function renderHighlightedState(state: SyntaxHighlightState): ContainerNode {
447702 return state.lastNode;
448703 }
449704
450- const lines = tokensToLines([
451- ...state.tokenizer.tokensStable,
452- ...state.tokenizer.tokensUnstable,
453- ]);
705+ const lines = tokensToLines(
706+ [...state.tokenizer.tokensStable, ...state.tokenizer.tokensUnstable],
707+ state.theme,
708+ );
454709
455710 state.lastNode = VStack({}, lines.map(lineToNode));
456711 return state.lastNode;
@@ -465,12 +720,18 @@ function renderHighlightedState(state: SyntaxHighlightState): ContainerNode {
465720 * edits fall back to a full re-highlight of that snippet.
466721 *
467722 * Shiki runtime code loads lazily on first use. Until the requested
468- * language is ready, or if loading fails, the component renders plain
469- * text and schedules a re-render. Unknown language ids also render plain
470- * text.
723+ * language and theme are ready, or if loading fails, the component
724+ * renders plain text and schedules a re-render. Unknown language ids
725+ * also render plain text.
726+ *
727+ * By default, the component uses a terminal-friendly ANSI 16 fallback
728+ * theme. Base foreground/background colors fall through to the terminal
729+ * defaults, while syntax scopes map onto the ANSI palette slots used by
730+ * cel-tui. Highlighted output also word-wraps by default.
471731 *
472732 * @param content - Source code to render.
473733 * @param language - Shiki bundled language id or alias.
734+ * @param props - Optional theme override.
474735 * @returns A `VStack` containing one highlighted line per child.
475736 *
476737 * @example
@@ -481,6 +742,9 @@ function renderHighlightedState(state: SyntaxHighlightState): ContainerNode {
481742 * ])
482743 *
483744 * @example
745+ * SyntaxHighlight(code, "typescript", { theme: "dark-plus" })
746+ *
747+ * @example
484748 * let code = "";
485749 * onChunk((chunk) => {
486750 * code += chunk;
@@ -494,16 +758,19 @@ function renderHighlightedState(state: SyntaxHighlightState): ContainerNode {
494758 export function SyntaxHighlight(
495759 content: string,
496760 language: string,
761+ props?: SyntaxHighlightProps,
497762 ): ContainerNode {
498- const status = ensureLanguageReady(language);
763+ const theme = resolveTheme(props?.theme);
764+ const status = ensureHighlightReady(language, theme);
499765 if (status !== "ready" || !highlighterInstance || !runtimeInstance) {
500766 return renderPlainContent(content);
501767 }
502768
769+ const key = stateKey(language, theme);
503770 const state =
504- findState(language, content) ??
505- createState(language, highlighterInstance, runtimeInstance);
771+ findState(key, content) ??
772+ createState(language, theme, highlighterInstance, runtimeInstance);
506773 updateState(state, content);
507- touchState(language, state);
774+ touchState(key, state);
508775 return renderHighlightedState(state);
509776 }