|
| 1 | +import createGlobalStyle from './createGlobalStyle'; |
| 2 | + |
| 3 | +type ThemeLeaf = string | number; |
| 4 | + |
| 5 | +/** |
| 6 | + * Recursively maps a theme object so every leaf value becomes |
| 7 | + * a `var(--sc-path, fallback)` CSS string. |
| 8 | + */ |
| 9 | +type CSSVarTheme<T> = { |
| 10 | + [K in keyof T]: T[K] extends ThemeLeaf ? string : CSSVarTheme<T[K]>; |
| 11 | +}; |
| 12 | + |
| 13 | +/** |
| 14 | + * The object returned by `createTheme`. Same shape as the input theme but |
| 15 | + * every leaf is a CSS `var()` reference. Also carries a `GlobalStyle` |
| 16 | + * component and the original `raw` theme object. |
| 17 | + */ |
| 18 | +type ThemeContract<T> = CSSVarTheme<T> & { |
| 19 | + /** |
| 20 | + * A `createGlobalStyle` component that emits `:root` CSS custom properties |
| 21 | + * from the current ThemeProvider context. Mount this once at the root of |
| 22 | + * your app so RSC components can consume theme values via CSS variables. |
| 23 | + */ |
| 24 | + GlobalStyle: ReturnType<typeof createGlobalStyle>; |
| 25 | + /** The original theme object, for passing to `ThemeProvider`. */ |
| 26 | + raw: T; |
| 27 | + /** |
| 28 | + * Read the current resolved CSS variable values from the DOM and return |
| 29 | + * an object with the same shape as the original theme. Each leaf is the |
| 30 | + * computed value (e.g. `"#0070f3"`), not the `var()` reference. |
| 31 | + * |
| 32 | + * Optionally pass a target element to read scoped variables from |
| 33 | + * (defaults to `document.documentElement`). |
| 34 | + * |
| 35 | + * Client-only — throws if called on the server. |
| 36 | + */ |
| 37 | + resolve(el?: Element): T; |
| 38 | +}; |
| 39 | + |
| 40 | +/** Recursively build `var(--prefix-a-b, fallback)` accessor object */ |
| 41 | +function buildVars<T extends Record<string, any>>( |
| 42 | + obj: T, |
| 43 | + varPrefix: string, |
| 44 | + path?: string |
| 45 | +): CSSVarTheme<T> { |
| 46 | + const result: Record<string, any> = {}; |
| 47 | + for (const key in obj) { |
| 48 | + const val = obj[key]; |
| 49 | + const fullPath = path ? path + '-' + key : key; |
| 50 | + if (typeof val === 'object' && val !== null) { |
| 51 | + result[key] = buildVars(val as Record<string, any>, varPrefix, fullPath); |
| 52 | + } else { |
| 53 | + result[key] = 'var(--' + varPrefix + fullPath + ', ' + val + ')'; |
| 54 | + } |
| 55 | + } |
| 56 | + return result as CSSVarTheme<T>; |
| 57 | +} |
| 58 | + |
| 59 | +/** Recursively read computed CSS variable values from the DOM */ |
| 60 | +function resolveVars<T extends Record<string, any>>( |
| 61 | + obj: T, |
| 62 | + varPrefix: string, |
| 63 | + styles: CSSStyleDeclaration, |
| 64 | + path?: string |
| 65 | +): T { |
| 66 | + const result: Record<string, any> = {}; |
| 67 | + for (const key in obj) { |
| 68 | + const val = obj[key]; |
| 69 | + const fullPath = path ? path + '-' + key : key; |
| 70 | + if (typeof val === 'object' && val !== null) { |
| 71 | + result[key] = resolveVars(val as Record<string, any>, varPrefix, styles, fullPath); |
| 72 | + } else { |
| 73 | + const resolved = styles.getPropertyValue('--' + varPrefix + fullPath).trim(); |
| 74 | + result[key] = resolved || val; |
| 75 | + } |
| 76 | + } |
| 77 | + return result as T; |
| 78 | +} |
| 79 | + |
| 80 | +/** Recursively read from `theme` (ThemeProvider context) and emit CSS var declarations */ |
| 81 | +function emitVarDeclarations(theme: Record<string, any>, varPrefix: string, path?: string): string { |
| 82 | + let css = ''; |
| 83 | + for (const key in theme) { |
| 84 | + const val = theme[key]; |
| 85 | + const fullPath = path ? path + '-' + key : key; |
| 86 | + if (typeof val === 'object' && val !== null) { |
| 87 | + css += emitVarDeclarations(val as Record<string, any>, varPrefix, fullPath); |
| 88 | + } else { |
| 89 | + css += '--' + varPrefix + fullPath + ':' + val + ';'; |
| 90 | + } |
| 91 | + } |
| 92 | + return css; |
| 93 | +} |
| 94 | + |
| 95 | +interface CreateThemeOptions { |
| 96 | + /** |
| 97 | + * Prefix for CSS variable names. Defaults to `"sc"`. |
| 98 | + * Useful for isolation when multiple design systems or microfrontends |
| 99 | + * coexist on the same page. |
| 100 | + * |
| 101 | + * @example |
| 102 | + * createTheme(theme, { prefix: 'ds' }) |
| 103 | + * // → var(--ds-colors-primary, #0070f3) |
| 104 | + */ |
| 105 | + prefix?: string; |
| 106 | + |
| 107 | + /** |
| 108 | + * CSS selector for the variable declarations. Defaults to `":root"`. |
| 109 | + * Use `":host"` for web components / Shadow DOM, or a class selector |
| 110 | + * for scoped theming. |
| 111 | + * |
| 112 | + * @example |
| 113 | + * createTheme(theme, { selector: ':host' }) |
| 114 | + * // → :host { --sc-colors-primary: #0070f3; } |
| 115 | + */ |
| 116 | + selector?: string; |
| 117 | +} |
| 118 | + |
| 119 | +/** |
| 120 | + * Create a theme contract that bridges `ThemeProvider` and CSS custom properties. |
| 121 | + * |
| 122 | + * Returns an object with the same shape as the input theme, but every leaf value |
| 123 | + * is a `var(--prefix-*, fallback)` CSS string. Use these in styled component |
| 124 | + * templates — they work in both client and RSC contexts. |
| 125 | + * |
| 126 | + * Mount the returned `GlobalStyle` component inside your `ThemeProvider` to emit |
| 127 | + * the CSS variables. When the theme changes (e.g. light → dark), the variables |
| 128 | + * update automatically. |
| 129 | + * |
| 130 | + * @example |
| 131 | + * ```tsx |
| 132 | + * const theme = createTheme({ |
| 133 | + * colors: { primary: '#0070f3', text: '#111' }, |
| 134 | + * }); |
| 135 | + * |
| 136 | + * // Root layout (client): |
| 137 | + * <ThemeProvider theme={themes[preset]}> |
| 138 | + * <theme.GlobalStyle /> |
| 139 | + * {children} |
| 140 | + * </ThemeProvider> |
| 141 | + * |
| 142 | + * // Any RSC file: |
| 143 | + * const Card = styled.div` |
| 144 | + * color: ${theme.colors.primary}; |
| 145 | + * // → "var(--sc-colors-primary, #0070f3)" |
| 146 | + * `; |
| 147 | + * ``` |
| 148 | + */ |
| 149 | +export default function createTheme<T extends Record<string, any>>( |
| 150 | + defaultTheme: T, |
| 151 | + options?: CreateThemeOptions |
| 152 | +): ThemeContract<T> { |
| 153 | + const pfx = (options?.prefix ?? 'sc') + '-'; |
| 154 | + const sel = options?.selector ?? ':root'; |
| 155 | + const vars = buildVars(defaultTheme, pfx); |
| 156 | + |
| 157 | + const GlobalStyle = createGlobalStyle` |
| 158 | + ${sel} { |
| 159 | + ${(p: { theme: Record<string, any> }) => emitVarDeclarations(p.theme, pfx)} |
| 160 | + } |
| 161 | + `; |
| 162 | + |
| 163 | + return Object.assign(vars, { |
| 164 | + GlobalStyle, |
| 165 | + raw: defaultTheme, |
| 166 | + resolve(el?: Element): T { |
| 167 | + if (typeof document === 'undefined') { |
| 168 | + throw new Error('createTheme.resolve() is client-only'); |
| 169 | + } |
| 170 | + const target = el ?? document.documentElement; |
| 171 | + return resolveVars(defaultTheme, pfx, getComputedStyle(target)); |
| 172 | + }, |
| 173 | + }) as ThemeContract<T>; |
| 174 | +} |
0 commit comments