@@ -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 }