Skip to content

Commit 9e07d95

Browse files
committed
feat: createTheme CSS variable theming utility
1 parent 2c69ec6 commit 9e07d95

4 files changed

Lines changed: 213 additions & 1 deletion

File tree

‎.changeset/feat-create-theme.md‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
---
2+
'styled-components': minor
3+
---
4+
5+
Add `createTheme` utility for CSS variable theming that works across RSC and client components.
6+
7+
`createTheme` takes a default theme object and returns an object with the same shape where every leaf value is replaced with a `var(--prefix-path, fallback)` CSS string. This lets you use theme values in RSC styled components (which can't access React context) while keeping the same tokens as client components.
8+
9+
```ts
10+
import { createTheme } from 'styled-components';
11+
12+
const theme = createTheme({
13+
colors: { primary: '#0070f3', text: '#111' }
14+
});
15+
16+
// theme.colors.primary → "var(--sc-colors-primary, #0070f3)"
17+
// theme.colors.text → "var(--sc-colors-text, #111)"
18+
// theme.raw → { colors: { primary: '#0070f3', text: '#111' } }
19+
```
20+
21+
Pass the returned object to `ThemeProvider` so that `p.theme.colors.*` interpolations produce CSS variable references instead of literal values. This gives you stable class name hashing across themes (no hydration mismatches when switching light/dark) and lets CSS variables handle the actual theming.
22+
23+
**`theme.resolve(el?)`** — read the current computed CSS variable values from the DOM, returning an object with the same shape as the original theme but with resolved values. Useful for JS logic that needs the actual current color (e.g., canvas rendering, conditional branching). Client-only.
24+
25+
```ts
26+
const current = theme.resolve();
27+
// current.colors.primary → "#3b82f6" (dark mode value)
28+
// current.colors.text → "#f9fafb"
29+
30+
// Scoped to a specific element:
31+
const scoped = theme.resolve(myElement);
32+
```
33+
34+
Options:
35+
- `prefix` (default: `"sc"`) — namespace for CSS variable names
36+
- `selector` (default: `":root"`) — CSS selector for variable declarations, use `":host"` for Shadow DOM

‎packages/styled-components/package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,7 @@
135135
"files": [
136136
{
137137
"path": "./dist/styled-components.min.js",
138-
"maxSize": "12.41kB"
138+
"maxSize": "13.1kB"
139139
}
140140
]
141141
},

‎packages/styled-components/src/base.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
/* Import singletons */
22
import { SC_ATTR, SC_VERSION } from './constants';
33
import createGlobalStyle from './constructors/createGlobalStyle';
4+
import createTheme from './constructors/createTheme';
45
import css from './constructors/css';
56
import keyframes from './constructors/keyframes';
67
/* Import Higher Order Components */
@@ -67,6 +68,7 @@ export {
6768
ThemeContext,
6869
ThemeProvider,
6970
createGlobalStyle,
71+
createTheme,
7072
css,
7173
isStyledComponent,
7274
keyframes,
Lines changed: 174 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,174 @@
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

Comments
 (0)