[lexical-code-shiki] Feature: Multi-theme / CSS-variable color mode
Description
Issue #8108 has two complaints:
- Shiki output puts theme colors in each token's inline
styleasrgb(...), so a runtime dark/light toggle requires re-tokenizing. - HTML exported from Lexical carries the original scheme's colors and can't be reskinned at the consuming page.
The issue suggests "use vars instead of rgb values," which is exactly what Shiki's multi-theme mode emits when given a themes map. This PR exposes that mode through CodeShikiExtension config.
Config
configExtension(CodeShikiExtension, {
themes: {light: 'one-light', dark: 'one-dark-pro'},
defaultColor: 'light',
});
CodeShikiConfig gains:
themes: Record<string, string> | null— multi-theme map.nullkeeps the existing single-theme behavior.defaultColor: string | false | undefined— forwarded to Shiki'scodeToTokens({themes, defaultColor}):- a key from
themes: that theme renders inline as the fallback; the others become--shiki-{name}/--shiki-{name}-bgvariables. 'light-dark()': CSS-nativelight-dark(...)fallback (Baseline 2024). Requireslight+darkkeys.false: emit only CSS variables, no inline color. The page's CSS owns the active scheme.- omitted: defers to Shiki's own default of
'light'(Shiki throws ifthemeslacks alightkey).
- a key from
Per-node CodeNode.__theme, Tokenizer.defaultTheme, and a custom tokenizer.$tokenize are skipped in multi-theme mode. Themes are a Shiki-specific feature with no equivalent in the generic Tokenizer abstraction, so the multi-theme path goes straight to Shiki's codeToTokens.
Backwards compatibility
registerCodeHighlightingsignature unchanged.- The Extension's
registereffect calls the existing internalregisterHighlightingOnlydirectly withthemes/defaultColor. The legacy export doesn't gain athemesparameter. Tokenizerinterface unchanged.
Playground
CodeHighlightExtension (the playground aggregator) configures CodeShikiExtension with themes: {light: 'one-light', dark: 'one-dark-pro'}, defaultColor: 'light', so QA in Shiki mode shows the feature directly.
Design notes
A few alternatives I considered, easy to swap if you'd prefer a different shape:
themes/defaultColoronCodeShikiExtension.config(this PR) vs. extendingTokenizer. Putting them on the highlighter-level config seemed cleaner since themes are Shiki-specific, but aTokenizer.themesfield is also workable.- Multi-theme bypasses
Tokenizer.$tokenizeentirely; a custom Tokenizer is consulted only in single-theme mode. The alternative is extendingTokenizer.$tokenizeto take theme args. The bypass keeps the generic interface unchanged at the cost of leaving custom tokenizers single-theme-only. - The playground demo defaults to
defaultColor: 'light'so the feature is visible without any extra CSS.false(vars-only) would force every consumer to add CSS rules — verified to work but felt rough as a default.
Closes #8108
Test plan
- [x]
pnpm vitest run --project unit -t "Shiki multi-theme"— 4 cases pass:- Single-theme mode keeps inline rgb color (BC)
defaultColor: 'dark'selects the inline theme; the other becomes a CSS variabledefaultColor: falseemits only CSS variables, no inline color- Multi-theme mode ignores per-node
setTheme
- [x] Tests exercise behavior through
CodeShikiExtensionconfig (extension scenario), not the internal helper. - [x] Full unit suite (2450 tests) passes.
- [x] tsc / flow / prettier / eslint clean.
- [x] Manual playground (Shiki mode,
defaultColor: 'light'):<code>has inlinebackground-color: rgb(...)(light) +--shiki-dark-bg: #.... Each token has inlinecolor: rgb(...)(light) +--shiki-dark: #....- In DevTools:
document.querySelectorAll('code, code span').forEach(el => el.style.color = 'var(--shiki-dark)')flips colors to the dark scheme without re-tokenizing. - "Convert to HTML" preserves the inline
styleincluding CSS variables.
- [x] Manual playground with
defaultColor: false(temporary swap):<code>and each token carry only--shiki-light(-bg)and--shiki-dark(-bg)variables. No inlinecolor:/background-color:declarations.
Example CSS for runtime toggle
/* defaultColor: 'light' — light is inline, dark is exposed as variable */
[data-theme="dark"] code {
background-color: var(--shiki-dark-bg);
color: var(--shiki-dark);
}
[data-theme="dark"] code span {
color: var(--shiki-dark);
}
The latest updates on your projects. Learn more about Vercel for GitHub.
| Project | Deployment | Actions | Updated (UTC) |
|---|---|---|---|
| lexical | Preview, Comment | Jul 15, 2026 9:48am | |
| lexical-playground | Preview, Comment | Jul 15, 2026 9:48am |
It probably makes sense for the default configuration of CodeShikiExtension to continue working without extra CSS, but it's completely fine for the playground configuration to require custom CSS. The playground is more of a demonstration of complex configuration, and more importantly a host for the e2e test suite (which would be better served by variables rather than rgb values, like the classes in the prism highlighter).
That said the playground doesn't currently have any light/dark toggle so having CodeNodes not match the rest of the editor might be a bit awkward looking.
Playground is now defaultThemeName: null (vars-only); PlaygroundEditorTheme.css reads --shiki-light(-bg) with rgb(240, 242, 245) as the off/Prism-mode fallback. Default config still has themes: null, so single-theme users get inline rgb with no CSS work.
Looking at the playground we still have the theme pulldown for code blocks when shiki is enabled, would be nice to make that do something?
Confirmed — data-theme gets written but $getHighlightNodes doesn't read it, so the dropdown is dead in shiki mode.
Playground runs defaultThemeName: null (vars-only, system light/dark via light-dark()). If someone picks dark-plus from the dropdown, should that one block break out of vars-only and use inline colors, or should it switch the editor-wide theme?
I think we should probably take a closer look at the Shiki interface to see if it needs to change more substantially than this. Tokenizer isn't really a generic abstraction, it already has a Shiki-only shape, the Prism one is different.
Agreed — Tokenizer is leaky. defaultTheme and $tokenize are both bypassed in multi-theme mode (the JSDoc admits as much), and Prism's Tokenizer is a different shape.
Direction we're leaning, unless you have a different read: deprecate Tokenizer as a type alias (keeping it exported for BC), flatten defaultLanguage / $tokenize onto CodeShikiConfig, and change $tokenize to (codeNode, lang, themeContext) => LexicalNode[] so the transform's multi-theme branch dissolves into the default $tokenize. registerCodeHighlighting and CodeHighlighterShikiExtension keep their signatures and forward Tokenizer fields into the new flat config.
Two open calls if that direction lands:
-
Deprecated alias vs clean break on
Tokenizer? Leaning deprecated to honor BC on legacy exports. -
How to model single-theme in the new config — (a) as a 1-key multi case (
themes: {only: '...'}, defaultThemeName: 'only'), or (b) a flatdefaultThemefield alongsidethemes/defaultThemeName?
Per-block override (the dropdown wiring) falls out naturally on either path. Open to a different shape entirely if you had something else in mind.
I think we can add extra arguments to $tokenize without breaking backwards compatibility so long as the first arguments match, and maybe just deprecate the defaults in that data structure (or at least have them as lower priority than the values in top-level config). Almost no use cases will override tokenizer once the themes are taken out of it.
-
Generally we lean towards backwards compatibility whenever feasible
-
Will have to think about this more, especially in the context of code nodes being able to individually choose a theme. Other options in the solution space allow for the data type to be string or some kind of object and dispatch accordingly, which solves some precedence confusion.
additionally we should think about making some or most of this be reconfigurable or extensible at runtime via output signals and/or functions.
BC route works — Tokenizer deprecated alias, $tokenize third arg, Tokenizer defaults below top-level. Starting on those.
On the string-or-object dispatch — reading it as: collapse themes + defaultThemeName into one field that's either a string (single theme name) or an object with the themes map + inline default. Type encodes the mode, precedence question dissolves. Extending the same shape to per-node __theme. Let me know if that's off; otherwise going with it.
I think the per-node __theme being an object is where I don't like that particular design and it might need more thought. Except in the specific case of something like {light: string, dark: string} there's no reason to have __theme be a non-string, and as far as usage goes it would be better keep it as a string and have a configuration table in the extension for the names to light/dark mappings. I don't have a concrete proposal for exactly how it should work, requires a bit more focus than I have right now. Only feedback I can really give is that I don't quite think we've uncovered the ideal structure yet.
Took your registry sketch and worked through it. Two designs I'd consider:
Common base:
type ShikiThemeDef = string | {light: string; dark: string};
type ShikiThemeSpec = ShikiThemeDef | ((codeNode: CodeNode) => ShikiThemeDef);
interface CodeShikiConfig {
defaultLanguage: string;
$tokenize: (codeNode, lang, themeContext) => LexicalNode[];
themes: Record<string, ShikiThemeSpec>;
defaultTheme: string;
}
Default stays single-theme inline ({default: 'one-light'}) so a bare configExtension(CodeShikiExtension) works without CSS. setTheme(key) looks up registry first, falls back to single-theme with the raw id if the key is a known Shiki theme (BC for setTheme('one-light') legacy use), with a dev warn nudging toward registry. Function form on the registry value covers the runtime extensibility you flagged.
The split is where inline policy lives (inline policy = which of light/dark renders inline; null = vars-only):
A) Root field
inlineDefault: 'light' | 'dark' | null;
Single field at config root, applies to every multi-theme entry. Closest to your "names to light/dark mappings" sketch literally. Cost: when all entries are single-theme strings, inlineDefault is dead config — JSDoc'd as only meaningful for {light, dark} entries.
B) Per-entry
type ShikiThemeDef = string | {light: string; dark: string; inline: 'light' | 'dark' | null};
Inline policy inside each multi entry. Type self-contained — entry says how it renders. Cost: site with uniform policy across N multi entries repeats inline: null N times (DRY-able with a helper).
Both keep __theme as string per your earlier point — the split is just where inline lives.
That's what I came up with. Moving the PR to draft for now.
What does the inlineDefault / inline policy actually do?
Both options control the same thing — which theme's colors get baked into the style attribute (the rest get exposed as --shiki-{name} CSS variables). Values:
'light'→ light inline, dark asvar(--shiki-dark)'dark'→ dark inline, light as varnull→ both as vars only, no inline color. Page CSS picks the active scheme vialight-dark(), class toggle, etc.
It's the defaultColor field renamed (since you flagged that name in round 1).
What would be the use case for setting {light: 'lightTheme', dark: 'darkTheme', inline: 'light' | 'dark'} instead of using 'lightTheme' or 'darkTheme' directly as a string? I'm having a hard time coming up with a reason you wouldn't always want the behavior to be equivalent to {light: 'lightTheme', dark: 'darkTheme', inline: null}
Fair point. Honestly we got a bit tunnel-visioned on the existing design through these review rounds — tried to find a real use case for the inline mode and couldn't. Progressive enhancement (inline fallback + vars for capable browsers) was the theoretical motivation, but if you want inline-only you'd just use a single-theme string, and if you want vars you'd own the CSS anyway.
Going to simplify — {light, dark} always means vars-only, no inline field.
type ShikiThemeDef = string | {light: string; dark: string};
type ShikiThemeSpec = ShikiThemeDef | ((codeNode: CodeNode) => ShikiThemeDef);
interface CodeShikiConfig {
defaultLanguage: string;
$tokenize: (codeNode, lang, themeContext) => LexicalNode[];
themes: Record<string, ShikiThemeSpec>;
defaultTheme: string;
}
Resolves the naming question too — no field, no name.