An open source design system that's fully customizable and agent ready
TypeScript
feat(theme): defineTheme API — flat token map with component overrides (#507)
Cindy Zhang8473c10c51ef
diff --git a/packages/core/src/theme/defineTheme.test.ts b/packages/core/src/theme/defineTheme.test.tsnew file mode 100644index 0000000000..cf7d0445a0--- /dev/null+++ b/packages/core/src/theme/defineTheme.test.ts@@ -0,0 +1,239 @@+import {describe, it, expect, vi} from 'vitest';+import {defineTheme, generateThemeCSS, isDefinedTheme} from './defineTheme';++describe('defineTheme', () => {+ it('creates a theme with name', () => {+ const theme = defineTheme({name: 'test'});+ expect(theme.name).toBe('test');+ });++ it('merges overrides with defaults', () => {+ const theme = defineTheme({+ name: 'custom',+ tokens: {+ '--color-accent': '#FF0000',+ },+ });+ // Override should be present+ expect(theme.tokens['--color-accent']).toBe('#FF0000');+ expect(theme.overrides['--color-accent']).toBe('#FF0000');+ // Defaults should still be present+ expect(theme.tokens['--color-surface']).toBeDefined();+ // Defaults should NOT be in overrides+ expect(theme.overrides['--color-surface']).toBeUndefined();+ });++ it('converts [light, dark] tuples to light-dark()', () => {+ const theme = defineTheme({+ name: 'tuple-test',+ tokens: {+ '--color-accent': ['#0077B6', '#48CAE4'],+ },+ });+ expect(theme.tokens['--color-accent']).toBe('light-dark(#0077B6, #48CAE4)');+ expect(theme.overrides['--color-accent']).toBe(+ 'light-dark(#0077B6, #48CAE4)',+ );+ });++ it('passes through string values as-is', () => {+ const theme = defineTheme({+ name: 'string-test',+ tokens: {+ '--radius-container': '16px',+ },+ });+ expect(theme.tokens['--radius-container']).toBe('16px');+ });++ it('mixes tuples and strings', () => {+ const theme = defineTheme({+ name: 'mixed',+ tokens: {+ '--color-accent': ['#0077B6', '#48CAE4'],+ '--radius-container': '16px',+ '--font-heading': '"Georgia", serif',+ },+ });+ expect(theme.overrides['--color-accent']).toBe(+ 'light-dark(#0077B6, #48CAE4)',+ );+ expect(theme.overrides['--radius-container']).toBe('16px');+ expect(theme.overrides['--font-heading']).toBe('"Georgia", serif');+ });++ it('warns on unknown token names', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ defineTheme({+ name: 'bad',+ tokens: {+ // @ts-expect-error testing unknown token+ '--color-does-not-exist': '#FF0000',+ },+ });+ expect(warn).toHaveBeenCalledWith(+ expect.stringContaining('unknown token "--color-does-not-exist"'),+ );+ warn.mockRestore();+ });++ it('includes icons in the theme', () => {+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ const icons = {close: 'X'} as any;+ const theme = defineTheme({name: 'icons', icons});+ expect(theme.icons).toBe(icons);+ });++ it('works with no tokens (defaults only)', () => {+ const theme = defineTheme({name: 'bare'});+ expect(Object.keys(theme.overrides)).toHaveLength(0);+ expect(Object.keys(theme.tokens).length).toBeGreaterThan(100);+ });+});++describe('generateThemeCSS', () => {+ it('generates CSS with only overrides', () => {+ const theme = defineTheme({+ name: 'ocean',+ tokens: {+ '--color-accent': ['#0077B6', '#48CAE4'],+ '--radius-container': '16px',+ },+ });+ const css = generateThemeCSS(theme);+ expect(css).toContain('@scope');+ expect(css).toContain('--color-accent: light-dark(#0077B6, #48CAE4)');+ expect(css).toContain('--radius-container: 16px');+ // Should NOT contain non-overridden tokens+ expect(css).not.toContain('--color-surface');+ });++ it('returns empty string for no overrides', () => {+ const theme = defineTheme({name: 'empty'});+ expect(generateThemeCSS(theme)).toBe('');+ });+});++describe('isDefinedTheme', () => {+ it('returns true for defineTheme output', () => {+ const theme = defineTheme({name: 'test'});+ expect(isDefinedTheme(theme)).toBe(true);+ });++ it('returns false for legacy theme objects', () => {+ const legacy = {name: 'old', styles: {}, icons: undefined};+ expect(isDefinedTheme(legacy)).toBe(false);+ });++ it('returns false for null/undefined', () => {+ expect(isDefinedTheme(null)).toBe(false);+ expect(isDefinedTheme(undefined)).toBe(false);+ });+});++describe('component overrides', () => {+ it('passes components through to the theme', () => {+ const theme = defineTheme({+ name: 'styled',+ components: {+ card: {+ base: {borderWidth: '2px', borderColor: 'var(--color-accent)'},+ },+ button: {+ base: {borderRadius: '999px'},+ },+ },+ });+ expect(theme.components?.card?.base).toEqual({+ borderWidth: '2px',+ borderColor: 'var(--color-accent)',+ });+ expect(theme.components?.button?.base).toEqual({borderRadius: '999px'});+ });+});++describe('generateThemeCSS with components', () => {+ it('generates scoped CSS for base component overrides', () => {+ const theme = defineTheme({+ name: 'ocean',+ tokens: {+ '--color-accent': ['#0077B6', '#48CAE4'],+ },+ components: {+ card: {+ base: {borderWidth: '2px', borderColor: 'var(--color-accent)'},+ },+ button: {+ base: {borderRadius: '999px'},+ },+ },+ });+ const css = generateThemeCSS(theme);+ expect(css).toContain('.xds-card {');+ expect(css).toContain('border-width: 2px');+ expect(css).toContain('border-color: var(--color-accent)');+ expect(css).toContain('.xds-button {');+ expect(css).toContain('border-radius: 999px');+ });++ it('generates variant selectors from prop:value keys', () => {+ const theme = defineTheme({+ name: 'test',+ components: {+ button: {+ 'variant:secondary': {+ backgroundColor: 'rgba(0,0,0,0.06)',+ },+ },+ },+ });+ const css = generateThemeCSS(theme);+ expect(css).toContain('.xds-button.secondary');+ expect(css).toContain('background-color: rgba(0,0,0,0.06)');+ });++ it('generates compound selectors from prop:value+prop:value keys', () => {+ const theme = defineTheme({+ name: 'test',+ components: {+ button: {+ 'variant:destructive+size:sm': {+ padding: '2px 6px',+ },+ },+ },+ });+ const css = generateThemeCSS(theme);+ expect(css).toContain('.xds-button.destructive.sm');+ expect(css).toContain('padding: 2px 6px');+ });++ it('converts camelCase to kebab-case', () => {+ const theme = defineTheme({+ name: 'test',+ components: {+ heading: {+ base: {fontFamily: '"Playfair Display", serif'},+ },+ },+ });+ const css = generateThemeCSS(theme);+ expect(css).toContain('font-family: "Playfair Display", serif');+ expect(css).not.toContain('fontFamily');+ });++ it('combines tokens and components', () => {+ const theme = defineTheme({+ name: 'combo',+ tokens: {'--radius-container': '20px'},+ components: {+ card: {base: {borderWidth: '1px'}},+ },+ });+ const css = generateThemeCSS(theme);+ expect(css).toContain('@scope');+ expect(css).toContain('--radius-container: 20px');+ expect(css).toContain('.xds-card {');+ expect(css).toContain('border-width: 1px');+ });+});diff --git a/packages/core/src/theme/defineTheme.ts b/packages/core/src/theme/defineTheme.tsnew file mode 100644index 0000000000..af4c24cc29--- /dev/null+++ b/packages/core/src/theme/defineTheme.ts@@ -0,0 +1,286 @@+/**+ * defineTheme — Create an XDS theme from a flat token map.+ *+ * Two distribution modes:+ * - Unbuilt: XDSTheme generates CSS and injects a <style> tag at runtime+ * - Built: `npx xds build-theme` pre-compiles to a CSS file; XDSTheme just+ * sets the data-xds-theme attribute+ *+ * Token values can be:+ * - A string: used as-is for both light and dark modes+ * - A [light, dark] tuple: converted to light-dark(light, dark)+ *+ * @example+ * ```tsx+ * const oceanTheme = defineTheme({+ * name: 'ocean',+ * tokens: {+ * '--color-accent': ['#0077B6', '#48CAE4'], // [light, dark]+ * '--color-surface': ['#F0F8FF', '#0A1628'],+ * '--radius-container': '16px', // same in both modes+ * },+ * icons: oceanIcons,+ * });+ *+ * <XDSTheme theme={oceanTheme}>+ * <App />+ * </XDSTheme>+ * ```+ */++import type {XDSIconRegistry} from '../Icon/IconRegistry';+import {parseStyleKey} from '../utils/parseStyleKey';+import {+ colorDefaults,+ spacingDefaults,+ sizeDefaults,+ radiusDefaults,+ elevationDefaults,+ transitionDefaults,+ typographyDefaults,+ textSizeDefaults,+ lineHeightDefaults,+ fontWeightDefaults,+} from './tokens.stylex';++// =============================================================================+// Types+// =============================================================================++/** All valid XDS token names */+export type XDSTokenName =+ | keyof typeof colorDefaults+ | keyof typeof spacingDefaults+ | keyof typeof sizeDefaults+ | keyof typeof radiusDefaults+ | keyof typeof elevationDefaults+ | keyof typeof transitionDefaults+ | keyof typeof typographyDefaults+ | keyof typeof textSizeDefaults+ | keyof typeof lineHeightDefaults+ | keyof typeof fontWeightDefaults;++/**+ * Token value — either a single string or a [light, dark] tuple.+ * Tuples are converted to CSS light-dark() at theme creation time.+ */+export type XDSTokenValue = string | [light: string, dark: string];++/**+ * CSS property values for a style rule.+ * Keys are camelCase CSS properties, values are CSS strings.+ */+export type XDSStyleOverrides = Record<string, string>;++/**+ * Component style overrides.+ *+ * Each top-level key is a component name (lowercase). Values are objects+ * mapping style keys to CSS property overrides:+ * - `base` — styles applied to all instances of the component+ * - `prop:value` — styles when a visual prop matches (e.g. `variant:secondary`)+ * - `prop:value+prop:value` — intersection of multiple props+ *+ * The `base` key is optional — omit it to only override specific variants.+ *+ * @example+ * ```tsx+ * components: {+ * button: {+ * base: { fontWeight: '600' },+ * 'variant:secondary': { backgroundColor: 'rgba(0,0,0,0.06)' },+ * 'variant:destructive+size:sm': { padding: '2px 6px' },+ * },+ * badge: {+ * 'variant:ghost': { border: '1px solid var(--color-divider)' },+ * },+ * }+ * ```+ */+export type XDSComponentStyleMap = Record<+ string,+ Record<string, XDSStyleOverrides>+>;++/** Input to defineTheme */+export interface XDSDefineThemeInput {+ /** Theme name — used for data-xds-theme attribute and identification */+ name: string;+ /** Token overrides — flat map of CSS custom property names to values.+ * Values can be a string or [light, dark] tuple.+ * Only include tokens you want to override; defaults fill the rest. */+ tokens?: Partial<Record<XDSTokenName, XDSTokenValue>>;+ /**+ * Component style overrides — keyed by component name (lowercase).+ * Each entry maps style keys to CSS property overrides, scoped under+ * the theme's data-xds-theme attribute via @scope.+ *+ * @example+ * ```tsx+ * components: {+ * button: {+ * base: { fontWeight: '600' },+ * 'variant:secondary': { backgroundColor: '...' },+ * },+ * }+ * // Generates:+ * // @scope ([data-xds-theme="ocean"]) to ([data-xds-theme]) {+ * // .xds-button { font-weight: 600; }+ * // .xds-button.secondary { background-color: ...; }+ * // }+ * ```+ */+ components?: XDSComponentStyleMap;+ /** Icon registry — maps semantic icon names to React nodes */+ icons?: Partial<XDSIconRegistry>;+}++/** A defined theme — ready to pass to <XDSTheme> */+export interface XDSDefinedTheme {+ /** Theme name */+ name: string;+ /** Resolved token values (overrides merged with defaults) */+ tokens: Record<string, string>;+ /** Only the overridden tokens (for CSS generation) */+ overrides: Record<string, string>;+ /** Component style overrides */+ components?: XDSComponentStyleMap;+ /** Icon registry */+ icons?: Partial<XDSIconRegistry>;+ /** Whether this theme has been pre-compiled by build-theme CLI */+ __built?: true;+}++// =============================================================================+// All defaults merged into a single flat map+// =============================================================================++const allDefaults: Record<string, string> = {+ ...colorDefaults,+ ...spacingDefaults,+ ...sizeDefaults,+ ...radiusDefaults,+ ...elevationDefaults,+ ...transitionDefaults,+ ...typographyDefaults,+ ...textSizeDefaults,+ ...lineHeightDefaults,+ ...fontWeightDefaults,+};++// =============================================================================+// defineTheme+// =============================================================================++/**+ * Resolve a token value to a CSS string.+ * - String values pass through as-is+ * - [light, dark] tuples become light-dark(light, dark)+ */+function resolveTokenValue(value: XDSTokenValue): string {+ if (Array.isArray(value)) {+ return `light-dark(${value[0]}, ${value[1]})`;+ }+ return value;+}++/**+ * Create an XDS theme.+ *+ * Pass only the tokens you want to override — everything else+ * inherits from the XDS defaults.+ */+export function defineTheme(input: XDSDefineThemeInput): XDSDefinedTheme {+ const overrides: Record<string, string> = {};++ if (input.tokens) {+ for (const [key, value] of Object.entries(input.tokens)) {+ if (value !== undefined) {+ if (!(key in allDefaults)) {+ console.warn(+ `[XDS] defineTheme("${input.name}"): unknown token "${key}". ` ++ `Run "npx xds docs tokens" to see valid token names.`,+ );+ }+ overrides[key] = resolveTokenValue(value);+ }+ }+ }++ // Merge: defaults + overrides+ const tokens = {...allDefaults, ...overrides};++ return {+ name: input.name,+ tokens,+ overrides,+ components: input.components,+ icons: input.icons,+ };+}++// =============================================================================+// CSS generation (used by XDSTheme for unbuilt themes)+// =============================================================================++/**+ * Convert camelCase to kebab-case for CSS property names.+ * e.g. borderRadius → border-radius, backgroundColor → background-color+ */+function toKebabCase(str: string): string {+ return str.replace(/[A-Z]/g, m => `-${m.toLowerCase()}`);+}++/**+ * Generate CSS rules for a defined theme.+ * Includes token overrides and component style overrides.+ */+export function generateThemeCSS(theme: XDSDefinedTheme): string {+ const parts: string[] = [];+ const scopeSelector = `[data-xds-theme="${theme.name}"]`;++ // Token overrides — applied to the scope root itself+ const tokenEntries = Object.entries(theme.overrides);+ if (tokenEntries.length > 0) {+ const declarations = tokenEntries+ .map(([prop, value]) => ` ${prop}: ${value};`)+ .join('\n');+ parts.push(` :scope {\n${declarations}\n }`);+ }++ // Component overrides+ if (theme.components) {+ for (const [component, rules] of Object.entries(theme.components)) {+ for (const [key, styles] of Object.entries(rules)) {+ const entries = Object.entries(styles);+ if (entries.length > 0) {+ const suffix = parseStyleKey(key);+ const declarations = entries+ .map(([prop, value]) => ` ${toKebabCase(prop)}: ${value};`)+ .join('\n');+ parts.push(` .xds-${component}${suffix} {\n${declarations}\n }`);+ }+ }+ }+ }++ if (parts.length === 0) return '';++ const inner = parts.join('\n\n');+ return `@scope (${scopeSelector}) to ([data-xds-theme]) {\n${inner}\n}`;+}++// =============================================================================+// Type guard+// =============================================================================++/** Check if a theme object was created with defineTheme */+export function isDefinedTheme(theme: unknown): theme is XDSDefinedTheme {+ return (+ typeof theme === 'object' &&+ theme !== null &&+ 'name' in theme &&+ 'tokens' in theme &&+ 'overrides' in theme+ );+}diff --git a/packages/core/src/theme/index.ts b/packages/core/src/theme/index.tsindex 954cb772fb..6368e12a40 100644--- a/packages/core/src/theme/index.ts+++ b/packages/core/src/theme/index.ts@@ -12,6 +12,15 @@*/export {XDSTheme, useXDSTheme, Theme, useTheme} from './XDSTheme';+export {defineTheme, generateThemeCSS, isDefinedTheme} from './defineTheme';+export type {+ XDSDefineThemeInput,+ XDSDefinedTheme,+ XDSTokenName,+ XDSTokenValue,+ XDSComponentStyleMap,+ XDSStyleOverrides,+} from './defineTheme';// Export token defaults and vars for use in custom components and themesexport {diff --git a/packages/core/src/utils/index.ts b/packages/core/src/utils/index.tsindex 6513369f14..3de5057a0c 100644--- a/packages/core/src/utils/index.ts+++ b/packages/core/src/utils/index.ts@@ -28,3 +28,5 @@ export {createISOTimeString,} from './timeParser';export type {ISOTimeString, ParsedTime} from './timeParser';++export {parseStyleKey} from './parseStyleKey';diff --git a/packages/core/src/utils/parseStyleKey.test.ts b/packages/core/src/utils/parseStyleKey.test.tsnew file mode 100644index 0000000000..a0516cd4b2--- /dev/null+++ b/packages/core/src/utils/parseStyleKey.test.ts@@ -0,0 +1,26 @@+import {describe, it, expect} from 'vitest';+import {parseStyleKey} from './parseStyleKey';++describe('parseStyleKey', () => {+ it('returns empty string for base', () => {+ expect(parseStyleKey('base')).toBe('');+ });++ it('converts variant:value to .value', () => {+ expect(parseStyleKey('variant:secondary')).toBe('.secondary');+ });++ it('prefixes numeric values with prop name', () => {+ expect(parseStyleKey('level:1')).toBe('.level-1');+ });++ it('handles compound keys', () => {+ expect(parseStyleKey('variant:destructive+size:sm')).toBe(+ '.destructive.sm',+ );+ });++ it('handles compound with numeric value', () => {+ expect(parseStyleKey('variant:primary+level:2')).toBe('.primary.level-2');+ });+});diff --git a/packages/core/src/utils/parseStyleKey.ts b/packages/core/src/utils/parseStyleKey.tsnew file mode 100644index 0000000000..3cf8dd379c--- /dev/null+++ b/packages/core/src/utils/parseStyleKey.ts@@ -0,0 +1,35 @@+/**+ * Parse a component style key into a CSS selector suffix.+ *+ * Used by both defineTheme (CSS generation) and components (class name rendering)+ * to ensure the same convention is applied consistently.+ *+ * Uses class names for visual prop values — shorter HTML, easier to inspect.+ * The component class (e.g. .xds-button) disambiguates any value overlaps.+ *+ * Values starting with a digit get prefixed with the prop name since+ * CSS class names can't start with a number.+ *+ * @example+ * ```ts+ * parseStyleKey('base') // ''+ * parseStyleKey('variant:secondary') // '.secondary'+ * parseStyleKey('level:1') // '.level-1'+ * parseStyleKey('variant:destructive+size:sm') // '.destructive.sm'+ * ```+ */+export function parseStyleKey(key: string): string {+ if (key === 'base') return '';++ return key+ .split('+')+ .map(part => {+ const [prop, value] = part.split(':');+ // CSS classes can't start with a digit — prefix with prop name+ if (/^\d/.test(value)) {+ return `.${prop}-${value}`;+ }+ return `.${value}`;+ })+ .join('');+}