镜像站点 · 本页由第三方 GitHub 只读镜像提供,非 GitHub 官方站点,不接受任何登录或凭据输入。前往 github.com
Skip to content

Commit 03a9d8d

Browse files
feat(theme): give colour tokens a mode axis
A theme colour was single-valued and inlined into the utility, so redefining a variable could not change what `bg-panel` painted. A nested record was only a shade scale, which made `panel.dark` a shade that happened to be called dark, reachable solely as `dark:bg-panel-dark` written by hand at every call site. `theme.modes` names the selector for each mode, and that declaration is what tells a mode token from a scale -- so a palette with a real `dark` shade keeps meaning exactly that until it opts in: modes: { dark: 'html.dark', marketing: 'html.marketing' }, colors: { panel: { light: '#fff', dark: '#18181b', marketing: '#fff7ed' } } emits `--color-panel` in `:root` and again under each selector, and `bg-panel` reads `var(--color-panel, #fff)`, so one override re-themes every utility built from it. Opacity keeps working through the variable. A mode need not be a colour scheme: `marketing` is a section of a site, which the `dark:` variant could never express. The token is flattened to its base value in a COPY of the colours record, not in place -- the theme a caller passes may be shared, and flattening it left a second generator built from the same config literal with a plain string where the token had been, its utilities silently no longer referencing the variable. Closes #23 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
1 parent 4c6146f commit 03a9d8d

3 files changed

Lines changed: 236 additions & 1 deletion

File tree

‎packages/toolkit/src/engine/generator.ts‎

Lines changed: 115 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,74 @@ const ANIMATION_MAP: Record<string, Record<string, string>> = {
179179
'animate-bounce': { animation: 'bounce 1s infinite' },
180180
}
181181

182+
/** A colour that varies by mode: the base value plus one per named mode. */
183+
interface ModeToken {
184+
name: string
185+
base: string
186+
byMode: Record<string, string>
187+
}
188+
189+
/**
190+
* Pull the mode tokens out of a theme's colours.
191+
*
192+
* A colour is a mode token when its value is an object whose every key is
193+
* `light` or a declared mode, and at least one is a mode. That test is what
194+
* keeps a shade legitimately named `dark` a shade: it only reads as a mode
195+
* once `theme.modes` says `dark` is one.
196+
*
197+
* Returns the tokens alongside a NEW colours record in which each is
198+
* flattened to its base value, so every existing path -- shade lookup,
199+
* opacity, arbitrary values -- resolves it as an ordinary colour and uses
200+
* that value as the variable's fallback.
201+
*
202+
* The record is rebuilt rather than written through, because the theme a
203+
* caller passes may be a shared object: flattening it in place left the
204+
* second generator built from the same config literal with a plain string
205+
* where the token had been, and its utilities silently stopped referencing
206+
* the variable.
207+
*/
208+
function extractModeTokens(
209+
colors: Record<string, string | Record<string, string>>,
210+
modes: Record<string, string>,
211+
): { tokens: ModeToken[], colors: Record<string, string | Record<string, string>> } {
212+
const modeNames = Object.keys(modes)
213+
if (modeNames.length === 0)
214+
return { tokens: [], colors }
215+
216+
const tokens: ModeToken[] = []
217+
for (const [name, value] of Object.entries(colors)) {
218+
if (typeof value !== 'object' || value === null)
219+
continue
220+
const keys = Object.keys(value)
221+
if (keys.length === 0)
222+
continue
223+
if (!keys.every(key => key === 'light' || modeNames.includes(key)))
224+
continue
225+
if (!keys.some(key => modeNames.includes(key)))
226+
continue
227+
228+
// `light` is the base when given; otherwise the first value is, so a
229+
// token written with only a mode still paints something unscoped.
230+
const base = typeof value.light === 'string' ? value.light : value[keys[0]]
231+
if (typeof base !== 'string')
232+
continue
233+
const byMode: Record<string, string> = {}
234+
for (const mode of modeNames) {
235+
const modeValue = value[mode]
236+
if (typeof modeValue === 'string')
237+
byMode[mode] = modeValue
238+
}
239+
tokens.push({ name, base, byMode })
240+
}
241+
if (tokens.length === 0)
242+
return { tokens, colors }
243+
244+
const flattened = { ...colors }
245+
for (const token of tokens)
246+
flattened[token.name] = token.base
247+
return { tokens, colors: flattened }
248+
}
249+
182250
/** The layer preflights land in: below everything an author writes. */
183251
const BASE_LAYER = 'tc-base'
184252
/** The layer utilities land in, but only once `layers` opts the sheet in. */
@@ -2113,6 +2181,8 @@ interface ProcessedConfig {
21132181
themeAnimations: Record<string, Record<string, string>>
21142182
/** Built-in @keyframes with the theme's merged over them, by name. */
21152183
keyframes: Record<string, string>
2184+
/** Colours that vary by mode, emitted as variables in toCSS. */
2185+
modeTokens: ModeToken[]
21162186
}
21172187

21182188
function processConfig(config: CssConfig): ProcessedConfig {
@@ -2144,7 +2214,7 @@ function processConfig(config: CssConfig): ProcessedConfig {
21442214
}
21452215

21462216
// Save extend colors before merging
2147-
const extendColors = config.theme.extend?.colors
2217+
let extendColors = config.theme.extend?.colors
21482218
? config.theme.extend.colors as Record<string, string | Record<string, string>>
21492219
: null
21502220

@@ -2156,6 +2226,28 @@ function processConfig(config: CssConfig): ProcessedConfig {
21562226
}
21572227
}
21582228

2229+
// Mode tokens are resolved before the colour tables below read the theme,
2230+
// since extracting one rewrites it to its base value. Their utilities must
2231+
// read the variable or the mode could never change what they paint, so the
2232+
// names join colorVariables rather than needing to be listed there by hand.
2233+
const extracted = extractModeTokens(
2234+
config.theme.colors as Record<string, string | Record<string, string>>,
2235+
config.theme.modes ?? {},
2236+
)
2237+
const modeTokens = extracted.tokens
2238+
if (modeTokens.length > 0) {
2239+
config.theme = { ...config.theme, colors: extracted.colors }
2240+
const names = modeTokens.map(token => token.name)
2241+
config.colorVariables = [...new Set([...(config.colorVariables ?? []), ...names])]
2242+
if (extendColors) {
2243+
extendColors = { ...extendColors }
2244+
for (const token of modeTokens) {
2245+
if (token.name in extendColors)
2246+
extendColors[token.name] = token.base
2247+
}
2248+
}
2249+
}
2250+
21592251
// Pre-compile blocklist patterns
21602252
const blocklistRegexCache: RegExp[] = []
21612253
const blocklistExact = new Set<string>()
@@ -2209,6 +2301,7 @@ function processConfig(config: CssConfig): ProcessedConfig {
22092301
hasShortcuts: Object.keys(config.shortcuts).length > 0,
22102302
themeAnimations,
22112303
keyframes,
2304+
modeTokens,
22122305
}
22132306

22142307
processedConfigCache.set(config, result)
@@ -3704,6 +3797,27 @@ export class CSSGenerator {
37043797
}
37053798
}
37063799

3800+
// Mode tokens: the base in :root, then one block per mode. Emitted
3801+
// whatever `cssVariables` says, because the utilities already reference
3802+
// these variables -- without the blocks they would fall back to the base
3803+
// in every mode, which is the bug rather than a smaller feature.
3804+
const modeTokens = this.processed.modeTokens
3805+
if (modeTokens.length > 0) {
3806+
const root = modeTokens.map(token => ` --color-${token.name}: ${token.base};`).join('\n')
3807+
const rootBlock = `:root {\n${root}\n}`
3808+
parts.push(minify ? minifyCSSBlock(rootBlock) : rootBlock)
3809+
3810+
for (const [mode, selector] of Object.entries(this.config.theme.modes ?? {})) {
3811+
const declarations = modeTokens
3812+
.filter(token => token.byMode[mode] !== undefined)
3813+
.map(token => ` --color-${token.name}: ${token.byMode[mode]};`)
3814+
if (declarations.length === 0)
3815+
continue
3816+
const block = `${selector} {\n${declarations.join('\n')}\n}`
3817+
parts.push(minify ? minifyCSSBlock(block) : block)
3818+
}
3819+
}
3820+
37073821
// Generate CSS variables from theme colors if enabled
37083822
if (this.config.cssVariables) {
37093823
const vars = this.generateCSSVariables()

‎packages/toolkit/src/engine/types.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,23 @@ export interface Theme {
179179
* composes with variants and is purged when unused.
180180
*/
181181
animation?: Record<string, string>
182+
/**
183+
* Named modes, as mode -> the selector that turns it on:
184+
* `{ dark: 'html.dark', marketing: 'html.marketing' }`.
185+
*
186+
* A colour whose value is an object keyed by `light` and these names is a
187+
* MODE TOKEN rather than a shade scale: it emits `--color-<name>` in
188+
* `:root` and again under each mode's selector, and its utilities read that
189+
* variable, so one override re-themes every utility built from it.
190+
*
191+
* Declaring the modes is what disambiguates the two, since `dark` is also a
192+
* perfectly good shade name -- a palette with a `dark` shade keeps meaning
193+
* exactly that unless `dark` is named here.
194+
*
195+
* A mode need not be a colour scheme; a named section of a site works the
196+
* same way, which `dark:` could never express.
197+
*/
198+
modes?: Record<string, string>
182199
/** Extend theme values without replacing defaults */
183200
extend?: Partial<Omit<Theme, 'extend'>>
184201
}
Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
/**
2+
* Mode tokens.
3+
*
4+
* A theme colour was single-valued and inlined into the utility, so
5+
* redefining a variable could not change what `bg-panel` painted, and the
6+
* only mode axis was the `dark:` variant written by hand at every call site.
7+
* A nested record was just a shade scale, so `panel.dark` was a shade that
8+
* happened to be called dark.
9+
*
10+
* `theme.modes` names the selector for each mode, and that declaration is
11+
* what makes a colour keyed by those names a mode token rather than a scale --
12+
* so a palette with a genuine `dark` shade is unaffected until it opts in.
13+
*/
14+
import { describe, expect, it } from 'bun:test'
15+
import { defaultConfig } from '../../src/engine/config'
16+
import { CSSGenerator } from '../../src/engine/generator'
17+
18+
const PANEL = {
19+
modes: { dark: 'html.dark', marketing: 'html.marketing' },
20+
extend: { colors: { panel: { light: '#ffffff', dark: '#18181b', marketing: '#fff7ed' } } },
21+
}
22+
23+
function themed(theme: Record<string, unknown>): CSSGenerator {
24+
return new CSSGenerator({ ...defaultConfig, theme: { ...defaultConfig.theme, ...theme } } as typeof defaultConfig)
25+
}
26+
27+
describe('Theme modes', () => {
28+
it('should emit the base value in :root', () => {
29+
const gen = themed(PANEL)
30+
gen.generate('bg-panel')
31+
expect(gen.toCSS(false)).toContain('--color-panel: #ffffff;')
32+
})
33+
34+
it('should emit a block per mode, under its selector', () => {
35+
const gen = themed(PANEL)
36+
gen.generate('bg-panel')
37+
const css = gen.toCSS(false)
38+
expect(css).toMatch(/html\.dark \{\s*--color-panel: #18181b;/)
39+
expect(css).toMatch(/html\.marketing \{\s*--color-panel: #fff7ed;/)
40+
})
41+
42+
/** Inlining the literal is what made the override impossible. */
43+
it('should make the utility reference the variable', () => {
44+
const gen = themed(PANEL)
45+
gen.generateBatch(['bg-panel', 'text-panel'])
46+
const css = gen.toCSS(false)
47+
expect(css).toContain('background-color: var(--color-panel, #ffffff)')
48+
expect(css).toContain('color: var(--color-panel, #ffffff)')
49+
})
50+
51+
it('should keep opacity working through the variable', () => {
52+
const gen = themed(PANEL)
53+
gen.generate('bg-panel/40')
54+
expect(gen.toCSS(false)).toContain('color-mix(in srgb, var(--color-panel, #ffffff) 40%, transparent)')
55+
})
56+
57+
/**
58+
* The named-scope case matters as much as light/dark: a section of a site
59+
* is not a colour scheme and `dark:` cannot express it at all.
60+
*/
61+
it('should support a mode that is not a colour scheme', () => {
62+
const gen = themed(PANEL)
63+
gen.generate('bg-panel')
64+
expect(gen.toCSS(false)).toContain('html.marketing')
65+
})
66+
67+
describe('disambiguation', () => {
68+
it('should leave a shade named dark a shade when no modes are declared', () => {
69+
const gen = themed({ extend: { colors: { surface: { base: '#ecfdf5', dark: '#064e3b' } } } })
70+
gen.generate('bg-surface-dark')
71+
const css = gen.toCSS(false)
72+
expect(css).toContain('background-color: #064e3b')
73+
expect(css).not.toContain('--color-surface')
74+
})
75+
76+
/** A scale carrying shades beyond the mode names is still a scale. */
77+
it('should leave a scale alone even with modes declared', () => {
78+
const gen = themed({
79+
modes: { dark: 'html.dark' },
80+
extend: { colors: { brand: { 100: '#eee', dark: '#111' } } },
81+
})
82+
gen.generate('bg-brand-100')
83+
const css = gen.toCSS(false)
84+
expect(css).toContain('background-color: #eee')
85+
expect(css).not.toContain('--color-brand:')
86+
})
87+
})
88+
89+
it('should fall back to the first value when light is absent', () => {
90+
const gen = themed({ modes: { dark: 'html.dark' }, extend: { colors: { ink: { dark: '#eeeeee' } } } })
91+
gen.generate('bg-ink')
92+
const css = gen.toCSS(false)
93+
expect(css).toContain('--color-ink: #eeeeee;')
94+
expect(css).toMatch(/html\.dark \{\s*--color-ink: #eeeeee;/)
95+
})
96+
97+
it('should emit nothing extra when no modes are configured', () => {
98+
const gen = themed({ extend: { colors: { panel: '#ffffff' } } })
99+
gen.generate('bg-panel')
100+
const css = gen.toCSS(false)
101+
expect(css).toContain('background-color: #ffffff')
102+
expect(css).not.toContain(':root')
103+
})
104+
})

0 commit comments

Comments
 (0)