Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

feat(theme): add expandColorScale — derive color tokens from accent hex (#1452)

Ernestb9bc38e325c8
diff --git a/packages/cli/src/commands/theme.mjs b/packages/cli/src/commands/theme.mjs
index b67e0a05fa..2333fe27bd 100644
--- a/packages/cli/src/commands/theme.mjs
+++ b/packages/cli/src/commands/theme.mjs
@@ -22,177 +22,6 @@ function isCancel(value) {
return value;
}
-// =============================================================================
-// Color utilities
-// =============================================================================
-
-/**
- * Parse a hex color to RGB components
- */
-function hexToRgb(hex) {
- const clean = hex.replace('#', '');
- const r = parseInt(clean.slice(0, 2), 16);
- const g = parseInt(clean.slice(2, 4), 16);
- const b = parseInt(clean.slice(4, 6), 16);
- return {r, g, b};
-}
-
-/**
- * Convert RGB to hex
- */
-function rgbToHex(r, g, b) {
- const clamp = (v) => Math.max(0, Math.min(255, Math.round(v)));
- return '#' + [r, g, b].map(v => clamp(v).toString(16).padStart(2, '0')).join('').toUpperCase();
-}
-
-/**
- * Mix two hex colors
- */
-function mixColors(hex1, hex2, weight = 0.5) {
- const c1 = hexToRgb(hex1);
- const c2 = hexToRgb(hex2);
- return rgbToHex(
- c1.r * (1 - weight) + c2.r * weight,
- c1.g * (1 - weight) + c2.g * weight,
- c1.b * (1 - weight) + c2.b * weight,
- );
-}
-
-/**
- * Add alpha to a hex color
- */
-function withAlpha(hex, alpha) {
- const alphaHex = Math.round(alpha * 255).toString(16).padStart(2, '0').toUpperCase();
- return hex + alphaHex;
-}
-
-/**
- * Derive a full color palette from a few key colors.
- *
- * @param {object} opts
- * @param {string} opts.accent - Primary accent color (hex)
- * @param {string} opts.positive - Success color (hex, optional)
- * @param {string} opts.negative - Error color (hex, optional)
- * @param {string} opts.warning - Warning color (hex, optional)
- * @param {'light'|'dark'|'both'} opts.mode - Color mode
- */
-function deriveColorPalette({accent, positive, negative, warning, mode}) {
- positive = positive || '#0D8626';
- negative = negative || '#E3193B';
- warning = warning || '#E9AF08';
-
- const accentRgb = hexToRgb(accent);
- // Create a lighter version for dark mode accent
- const accentLight = rgbToHex(
- Math.min(255, accentRgb.r + 60),
- Math.min(255, accentRgb.g + 60),
- Math.min(255, accentRgb.b + 60),
- );
- const accentDark = accent;
-
- // Derive accent text (darker in light, lighter in dark)
- const accentTextLight = mixColors(accent, '#000000', 0.3);
- const accentTextDark = mixColors(accent, '#FFFFFF', 0.4);
-
- const ld = (light, dark) => {
- if (mode === 'light') return light;
- if (mode === 'dark') return dark;
- return `light-dark(${light}, ${dark})`;
- };
-
- return {
- // Core semantic
- '--color-accent': ld(accentDark, accentLight),
- '--color-accent-muted': ld(withAlpha(accent, 0.2), withAlpha(accent, 0.25)),
- '--color-neutral': ld('rgba(5, 54, 89, 0.1)', 'rgba(223, 226, 229, 0.2)'),
- '--color-text-accent': ld(accentTextLight, accentTextDark),
- '--color-background-surface': ld('#FFFFFF', '#1F1F22'),
- '--color-background-body': ld('#F1F4F7', '#111112'),
- '--color-overlay': ld('#01122866', '#11111299'),
- '--color-overlay-hover': ld('#0536590C', '#FFFFFF0C'),
- '--color-overlay-pressed': ld('#05365919', '#FFFFFF19'),
- '--color-accent': ld(accentTextLight, accentTextDark),
- '--color-background-muted': ld('#0536590C', '#1111127F'),
-
- // Text
- '--color-text-primary': ld('#0A1317', '#DFE2E5'),
- '--color-text-secondary': ld('#4E606F', '#AAAFB5'),
- '--color-text-disabled': ld('#A4B0BC', '#6F747C'),
- '--color-text-accent': ld(accentDark, accentLight),
- '--color-text-secondary': ld('#4E606F', '#AAAFB5'),
- '--color-on-dark': ld('#FFFFFF', '#FFFFFF'),
-
- // Icon
- '--color-icon-primary': ld('#0A1317', '#DFE2E5'),
- '--color-icon-secondary': ld('#4E606F', '#AAAFB5'),
- '--color-icon-secondary': ld('#748695', '#8C939B'),
- '--color-icon-disabled': ld('#A4B0BC', '#6F747C'),
-
- // Surface variants
- '--color-background-card': ld('#FFFFFF', '#1F1F22'),
- '--color-background-popover': ld('#FFFFFF', '#28292C'),
-
- // Status
- '--color-success': ld(positive, positive),
- '--color-success-muted': ld(withAlpha(positive, 0.2), withAlpha(positive, 0.25)),
- '--color-error': ld(negative, mixColors(negative, '#FF6666', 0.3)),
- '--color-error-muted': ld(withAlpha(negative, 0.2), withAlpha(negative, 0.25)),
- '--color-warning': ld(warning, mixColors(warning, '#FFCC00', 0.3)),
- '--color-warning-muted': ld(withAlpha(warning, 0.2), withAlpha(warning, 0.25)),
-
- // Divider
- '--color-border': ld('#05365919', '#F2F4F619'),
- '--color-border-emphasized': ld('#647685', '#6F747C'),
- '--color-border-emphasized': ld('#CCD3DB', '#494D53'),
-
- // Effects
- '--color-skeleton': ld('#CCD3DB', '#5A5E66'),
- '--color-shadow': ld('rgba(5, 54, 89, 0.1)', 'rgba(0, 0, 0, 0.3)'),
- '--color-tint-hover': ld('black', 'white'),
-
- // Literal color sets
- '--color-background-blue': ld('#0171E333', '#0171E333'),
- '--color-border-blue': ld('#0171E3', '#4BA9FE'),
- '--color-icon-blue': ld('#0064E0', '#2694FE'),
- '--color-text-blue': ld('#042F97', '#AFD7FF'),
- '--color-background-cyan': ld('#00BCD433', '#00BCD433'),
- '--color-border-cyan': ld('#00BCD4', '#4DD0E1'),
- '--color-icon-cyan': ld('#00ACC1', '#26C6DA'),
- '--color-text-cyan': ld('#006064', '#B2EBF2'),
- '--color-background-gray': ld('#0A131733', '#666A724C'),
- '--color-border-gray': ld('#647685', '#8C939B'),
- '--color-icon-gray': ld('#4E606F', '#AAAFB5'),
- '--color-text-gray': ld('#0A1317', '#E7EAED'),
- '--color-background-green': ld('#24BB5E33', '#24BB5E33'),
- '--color-border-green': ld('#24BB5E', '#4CD964'),
- '--color-icon-green': ld('#0D8626', '#26A756'),
- '--color-text-green': ld('#09441F', '#A5F690'),
- '--color-background-orange': ld('#F2790233', '#F2790233'),
- '--color-border-orange': ld('#F27902', '#FFA040'),
- '--color-icon-orange': ld('#E9690B', '#FB8C00'),
- '--color-text-orange': ld('#6B2203', '#FDB876'),
- '--color-background-pink': ld('#E91E6333', '#E91E6333'),
- '--color-border-pink': ld('#E91E63', '#F48FB1'),
- '--color-icon-pink': ld('#C2185B', '#EC407A'),
- '--color-text-pink': ld('#880E4F', '#F8BBD0'),
- '--color-background-purple': ld('#7952FF33', '#7952FF33'),
- '--color-border-purple': ld('#7952FF', '#9575CD'),
- '--color-icon-purple': ld('#5B08D8', '#7952FF'),
- '--color-text-purple': ld('#3E0697', '#B3B0FE'),
- '--color-background-red': ld('#E3193B33', '#E3193B33'),
- '--color-border-red': ld('#E3193B', '#F5394F'),
- '--color-icon-red': ld('#D31130', '#E3193B'),
- '--color-text-red': ld('#7B0210', '#FFB2B8'),
- '--color-background-teal': ld('#0DB7AF33', '#0DB7AF33'),
- '--color-border-teal': ld('#0DB7AF', '#4DB6AC'),
- '--color-icon-teal': ld('#009688', '#26A69A'),
- '--color-text-teal': ld('#083943', '#40DCCD'),
- '--color-background-yellow': ld('#FFEB3B33', '#FFEB3B33'),
- '--color-border-yellow': ld('#FFEB3B', '#FFF176'),
- '--color-icon-yellow': ld('#FBC02D', '#FFEE58'),
- '--color-text-yellow': ld('#753F07', '#FBCE03'),
- };
-}
// =============================================================================
// Theme file generation
@@ -201,148 +30,45 @@ function deriveColorPalette({accent, positive, negative, warning, mode}) {
/**
* Generate the theme file content
*/
-function generateThemeFile({name, exportName, colors, includeComponentOverrides, mode}) {
- const modeComment = mode === 'both'
- ? 'Uses CSS light-dark() for automatic light/dark mode switching.'
- : mode === 'dark'
- ? 'Designed for dark mode. Use with <XDSTheme mode="dark">.'
- : 'Designed for light mode. Use with <XDSTheme mode="light">.';
-
- const componentOverrideSection = includeComponentOverrides
+function generateThemeFile({name, exportName, accent, includeComponentOverrides}) {
+ const componentsComment = includeComponentOverrides
? `
-// =============================================================================
-// Component Style Overrides (optional)
-// =============================================================================
-// Uncomment and customize any section below.
-// Each component reads its overrides from theme.components.<name>.
-//
-// To discover what's themeable for a component, run:
-// ${getRunPrefix()} xds --detail compact component <Name>
-// and look for the "Theme Overrides" section.
-
-// --- Button ---
-// const buttonVariants = stylex.create({
-// secondary: {
-// backgroundColor: 'light-dark(rgba(0, 0, 0, 0.06), rgba(255, 255, 255, 0.1))',
-// },
-// });
-
-// --- Card ---
-// const cardOverrides = stylex.create({
-// container: {
-// borderRadius: radiusVars['--radius-container'],
-// // gradient border: set a gradient background + padding, inner content covers it
-// // background: 'linear-gradient(135deg, ...)',
-// },
-// content: {
-// backgroundColor: colorVars['--color-background-card'],
-// },
-// });
-
-// --- Heading ---
-// const headingStyles = stylex.create({
-// h1: {
-// fontFamily: typographyVars['--font-family-heading'],
-// fontSize: textSizeVars['--font-size-2xl'],
-// fontWeight: fontWeightVars['--font-weight-semibold'],
-// lineHeight: 1.2,
-// color: colorVars['--color-text-primary'],
-// margin: 0,
-// },
-// // h2, h3, h4, h5, h6...
-// });
-
-// --- Text ---
-// const textStyles = stylex.create({
-// body: {
-// fontFamily: typographyVars['--font-family-body'],
-// fontSize: textSizeVars['--font-size-base'],
-// fontWeight: fontWeightVars['--font-weight-normal'],
-// lineHeight: typeScaleVars['--text-body-leading'],
-// color: colorVars['--color-text-primary'],
-// margin: 0,
-// },
-// // large, label, supporting, code...
-// });
-`
- : '';
-
- const componentsField = includeComponentOverrides
- ? ` // Uncomment to apply component overrides:
+ // Uncomment to apply component overrides:
// components: {
- // button: { variants: buttonVariants },
- // card: { container: cardOverrides.container, content: cardOverrides.content },
- // heading: { styles: headingStyles },
- // text: { styles: textStyles },
- // } as Theme['components'],`
+ // button: {
+ // base: { borderRadius: '9999px' },
+ // },
+ // card: {
+ // base: { borderWidth: '2px', borderStyle: 'solid' },
+ // },
+ // },`
: '';
- // Format colors as source code
- const colorEntries = Object.entries(colors)
- .map(([key, value]) => ` '${key}': '${value}',`)
- .join('\n');
-
return `/**
* ${name} Theme
*
- * ${modeComment}
- *
* Generated by \`${getRunPrefix()} xds theme\`.
- * Customize the values below, then import in your app.
+ * Uses defineTheme with the color config — all color tokens are
+ * derived from the accent color via the HCT perceptual color model.
*
- * Only override token groups you want to change — omitted groups
- * automatically use the defineVars defaults from @xds/core.
+ * Customize the config below, then import in your app.
*/
-import * as stylex from '@stylexjs/stylex';
-import type {ThemeType as Theme} from '@xds/core/theme';
-import {
- colorVars,
- colorDefaults,
-} from '@xds/core/theme/tokens.stylex';
+import {defineTheme} from '@xds/core/theme';
-// =============================================================================
-// Colors
-// =============================================================================
-// Edit these values to change your theme's color palette.
-// Use light-dark(lightValue, darkValue) for automatic light/dark support.
-
-const colorOverrides = {
-${colorEntries}
-} as const;
+export const ${exportName} = defineTheme({
+ name: '${name.toLowerCase().replace(/\s+/g, '-')}',
-// =============================================================================
-// createTheme calls
-// =============================================================================
-// Only create themes for token groups you want to override.
-// Omitted groups (spacing, size, radius, shadow, transition, typography,
-// textSize, lineHeight, fontWeight) use the defineVars defaults automatically.
-
-const colorTheme = stylex.createTheme(
- colorVars,
- colorOverrides as unknown as typeof colorDefaults,
-);
-
-// Uncomment and customize to override other token groups:
-// import { radiusVars, shadowVars, typographyVars, ... } from '@xds/core/theme/tokens.stylex';
-// const radiusTheme = stylex.createTheme(radiusVars, { '--radius-container': '16px', ... });
-${componentOverrideSection}
-// =============================================================================
-// Theme Export
-// =============================================================================
+ // Accent color — all color tokens derive from this via HCT.
+ // Change the hex to update the entire palette.
+ color: {accent: '${accent}'},
-export const ${exportName}: Theme = {
- name: '${name.toLowerCase().replace(/\s+/g, '-')}',
- styles: {
- colors: colorTheme,
- // Add overridden token groups here:
- // radius: radiusTheme,
- },
- raw: {
- colors: colorOverrides,
- },
-${componentsField}
-};
+ // Uncomment to customize:
+ // radius: {base: 4, multiplier: 1},
+ // typography: {body: {family: 'Inter', fallbacks: 'sans-serif'}},
+ // tokens: { '--color-on-accent': ['#FFFFFF', '#FFFFFF'] },
+${componentsComment}
+});
`;
}
@@ -465,17 +191,12 @@ export function registerTheme(program) {
// Non-interactive: preset name provided directly
if (preset && PRESETS[preset]) {
- const colors = deriveColorPalette({
- accent: PRESETS[preset].accent,
- mode: 'both',
- });
const exportName = `${preset}Theme`;
const content = generateThemeFile({
name: preset.charAt(0).toUpperCase() + preset.slice(1),
exportName,
- colors,
+ accent: PRESETS[preset].accent,
includeComponentOverrides: false,
- mode: 'both',
});
const outputPath = path.resolve(process.cwd(), options.output);
@@ -505,9 +226,8 @@ export function registerTheme(program) {
}),
);
- let colors;
+ let accent;
let themeName;
- let mode = 'both';
if (startingPoint === 'brand') {
// Step 2a: Brand color
@@ -521,59 +241,9 @@ export function registerTheme(program) {
},
}),
);
- const accent = normalizeHex(accentInput);
-
- // Step 2b: Color mode
- mode = isCancel(
- await p.select({
- message: 'Color mode',
- options: [
- {value: 'both', label: 'Light + Dark', hint: 'Automatic via light-dark() — recommended'},
- {value: 'light', label: 'Light only'},
- {value: 'dark', label: 'Dark only'},
- ],
- }),
- );
-
- // Step 2c: Status colors
- const customizeStatus = isCancel(
- await p.confirm({
- message: 'Customize status colors (positive/negative/warning)?',
- initialValue: false,
- }),
- );
-
- let positive, negative, warning;
- if (customizeStatus) {
- positive = normalizeHex(isCancel(
- await p.text({
- message: 'Positive/success color',
- placeholder: '#0D8626',
- initialValue: '#0D8626',
- validate: (v) => { if (!isValidHex(v)) return 'Enter a valid hex color'; },
- }),
- ));
- negative = normalizeHex(isCancel(
- await p.text({
- message: 'Negative/error color',
- placeholder: '#E3193B',
- initialValue: '#E3193B',
- validate: (v) => { if (!isValidHex(v)) return 'Enter a valid hex color'; },
- }),
- ));
- warning = normalizeHex(isCancel(
- await p.text({
- message: 'Warning color',
- placeholder: '#E9AF08',
- initialValue: '#E9AF08',
- validate: (v) => { if (!isValidHex(v)) return 'Enter a valid hex color'; },
- }),
- ));
- }
-
- colors = deriveColorPalette({accent, positive, negative, warning, mode});
+ accent = normalizeHex(accentInput);
- // Step 2d: Theme name
+ // Step 2b: Theme name
themeName = isCancel(
await p.text({
message: 'Theme name',
@@ -586,10 +256,7 @@ export function registerTheme(program) {
);
} else if (startingPoint === 'default' || startingPoint === 'neutral') {
- colors = deriveColorPalette({
- accent: PRESETS[startingPoint].accent,
- mode: 'both',
- });
+ accent = PRESETS[startingPoint].accent;
themeName = isCancel(
await p.text({
message: 'Theme name',
@@ -601,8 +268,8 @@ export function registerTheme(program) {
}),
);
} else {
- // Minimal — use default colors as placeholder
- colors = deriveColorPalette({accent: '#0064E0', mode: 'both'});
+ // Minimal — use default accent as placeholder
+ accent = '#0064E0';
themeName = isCancel(
await p.text({
message: 'Theme name',
@@ -638,9 +305,8 @@ export function registerTheme(program) {
const content = generateThemeFile({
name: themeName.charAt(0).toUpperCase() + themeName.slice(1),
exportName,
- colors,
+ accent,
includeComponentOverrides,
- mode,
});
const resolvedPath = path.resolve(process.cwd(), outputPath);
@@ -650,31 +316,20 @@ export function registerTheme(program) {
p.log.success(`Generated ${path.relative(process.cwd(), resolvedPath)}`);
// Step 5: Setup instructions
- const modeAttr = mode === 'dark' ? ' mode="dark"' : mode === 'light' ? ' mode="light"' : '';
-
p.note(
`import {XDSTheme} from '@xds/core';\n` +
- `import {${exportName}} from './${path.relative(path.resolve(process.cwd(), 'src'), resolvedPath).replace('.stylex.ts', '')}';\n` +
+ `import {${exportName}} from './${path.relative(path.resolve(process.cwd(), 'src'), resolvedPath).replace('.ts', '')}';\n` +
`\n` +
- `<XDSTheme theme={${exportName}}${modeAttr}>\n` +
+ `<XDSTheme theme={${exportName}}>\n` +
` <App />\n` +
`</XDSTheme>`,
'Add to your root layout',
);
- if (mode !== 'both') {
- p.log.info(
- `Your theme is ${mode}-mode only. Make sure to set mode="${mode}" on XDSTheme.`,
- );
- }
-
p.note(
- 'Edit the colorOverrides object to change colors.\n' +
- 'Add createTheme calls for other token groups you want to override.\n' +
- 'Omitted groups use the defineVars defaults automatically.\n' +
- (includeComponentOverrides
- ? 'Uncomment sections in "Component Style Overrides" to customize components.\n'
- : `Run \`${getRunPrefix()} xds theme\` again with component overrides to customize components.\n`) +
+ 'Edit the color.accent hex to change the entire palette.\n' +
+ 'Add radius, typography, or tokens config to customize further.\n' +
+ 'Omitted config uses the defineVars defaults automatically.\n' +
`\nRun \`${getRunPrefix()} xds docs tokens\` to see all available tokens.`,
'Next steps',
);
diff --git a/packages/core/src/theme/defineTheme.ts b/packages/core/src/theme/defineTheme.ts
index 6a638c022c..8b9ddfa6af 100644
--- a/packages/core/src/theme/defineTheme.ts
+++ b/packages/core/src/theme/defineTheme.ts
@@ -63,6 +63,7 @@ import {
expandRadiusScale,
type XDSRadiusScaleConfig,
} from './expandRadiusScale';
+import {expandColorScale, type XDSColorScaleConfig} from './expandColorScale';
import type {DomainTokenName} from './domainTokens';
import {domainTokenDefaults} from './domainTokens';
@@ -214,6 +215,20 @@ export interface XDSDefineThemeInput {
* ```
*/
radius?: XDSRadiusScaleConfig;
+ /**
+ * Color scale configuration. Generates color token overrides from a
+ * single accent color using the HCT perceptual color model.
+ *
+ * Only generates tokens derivable from the accent — status colors,
+ * categorical hues, and fixed tokens (on-dark/on-light) use defaults.
+ * Explicit `tokens` entries always take precedence.
+ *
+ * @example
+ * ```tsx
+ * color: { accent: '#0064E0', neutralStyle: 'cool', contrast: 'standard' }
+ * ```
+ */
+ color?: XDSColorScaleConfig;
/** 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. */
@@ -481,7 +496,15 @@ export function defineTheme(input: XDSDefineThemeInput): XDSDefinedTheme {
};
}
- // 1. Apply typeScale-generated tokens first (lowest precedence)
+ // 1. Apply color-generated tokens (lowest precedence for colors)
+ if (input.color) {
+ const colorTokens = expandColorScale(input.color);
+ for (const [key, value] of Object.entries(colorTokens)) {
+ tokens[key] = value;
+ }
+ }
+
+ // 1a. Apply typeScale-generated tokens (lowest precedence for type)
if (typeScaleConfig) {
const typeScaleTokens = expandTypeScale(typeScaleConfig);
for (const [key, value] of Object.entries(typeScaleTokens)) {
diff --git a/packages/core/src/theme/expandColorScale.test.ts b/packages/core/src/theme/expandColorScale.test.ts
new file mode 100644
index 0000000000..ed8450568b
--- /dev/null
+++ b/packages/core/src/theme/expandColorScale.test.ts
@@ -0,0 +1,81 @@
+import {describe, it, expect} from 'vitest';
+import {expandColorScale} from './expandColorScale';
+import {defineTheme} from './defineTheme';
+
+describe('expandColorScale', () => {
+ it('produces all expected token keys', () => {
+ const tokens = expandColorScale({accent: '#0064E0'});
+ const expectedKeys = [
+ '--color-accent',
+ '--color-accent-muted',
+ '--color-on-accent',
+ '--color-neutral',
+ '--color-background-surface',
+ '--color-background-body',
+ '--color-overlay',
+ '--color-overlay-hover',
+ '--color-overlay-pressed',
+ '--color-background-muted',
+ '--color-text-primary',
+ '--color-text-secondary',
+ '--color-text-disabled',
+ '--color-text-accent',
+ '--color-icon-accent',
+ '--color-icon-primary',
+ '--color-icon-secondary',
+ '--color-icon-disabled',
+ '--color-background-card',
+ '--color-background-popover',
+ '--color-background-inverted',
+ '--color-border',
+ '--color-border-emphasized',
+ '--color-skeleton',
+ '--color-shadow',
+ '--color-tint-hover',
+ ];
+ for (const key of expectedKeys) {
+ expect(tokens).toHaveProperty(key);
+ }
+ });
+
+ it('all values are strings', () => {
+ const tokens = expandColorScale({accent: '#0064E0'});
+ for (const value of Object.values(tokens)) {
+ expect(typeof value).toBe('string');
+ }
+ });
+
+ it('neutralStyle variants produce different --color-neutral values', () => {
+ const warm = expandColorScale({accent: '#0064E0', neutralStyle: 'warm'});
+ const cool = expandColorScale({accent: '#0064E0', neutralStyle: 'cool'});
+ const neutral = expandColorScale({
+ accent: '#0064E0',
+ neutralStyle: 'neutral',
+ });
+ expect(warm['--color-neutral']).not.toBe(cool['--color-neutral']);
+ expect(cool['--color-neutral']).not.toBe(neutral['--color-neutral']);
+ expect(warm['--color-neutral']).not.toBe(neutral['--color-neutral']);
+ });
+
+ it('contrast high produces different --color-text-primary than standard', () => {
+ const standard = expandColorScale({
+ accent: '#0064E0',
+ contrast: 'standard',
+ });
+ const high = expandColorScale({accent: '#0064E0', contrast: 'high'});
+ expect(high['--color-text-primary']).not.toBe(
+ standard['--color-text-primary'],
+ );
+ });
+});
+
+describe('expandColorScale + defineTheme integration', () => {
+ it('explicit token overrides win over generated values', () => {
+ const theme = defineTheme({
+ name: 'test-override',
+ color: {accent: '#0064E0'},
+ tokens: {'--color-accent': 'red'},
+ });
+ expect(theme.tokens['--color-accent']).toBe('red');
+ });
+});
diff --git a/packages/core/src/theme/expandColorScale.ts b/packages/core/src/theme/expandColorScale.ts
new file mode 100644
index 0000000000..ae2d87aa30
--- /dev/null
+++ b/packages/core/src/theme/expandColorScale.ts
@@ -0,0 +1,172 @@
+/**
+ * @file expandColorScale.ts
+ * @input Color scale configuration { accent, neutralStyle?, contrast? }
+ * @output Token overrides for derivable color tokens
+ * @position Theme utility; consumed by defineTheme.ts
+ *
+ * Generates color token overrides from a single accent color using the
+ * HCT perceptual color model. Only produces tokens that meaningfully
+ * derive from the accent — status colors, categorical hues, and fixed
+ * tokens (on-dark/on-light) fall through to colorDefaults.
+ *
+ * SYNC: When modified, update:
+ * - /packages/core/src/theme/defineTheme.ts
+ */
+
+import {hexToHct, tonalPalette, hexWithAlpha} from './hct';
+
+// =============================================================================
+// Types
+// =============================================================================
+
+/**
+ * Color scale configuration.
+ *
+ * @example
+ * ```
+ * // Minimal — just a seed color
+ * { accent: '#0064E0' }
+ *
+ * // With customization
+ * { accent: '#B7410E', neutralStyle: 'warm', contrast: 'high' }
+ * ```
+ */
+export interface XDSColorScaleConfig {
+ /** Seed accent color as hex (#RRGGBB). Everything derives from this. */
+ accent: string;
+
+ /**
+ * Neutral tone warmth. Controls how much of the seed's hue bleeds
+ * into neutral/background colors.
+ * @default 'cool'
+ */
+ neutralStyle?: 'warm' | 'cool' | 'neutral';
+
+ /**
+ * Contrast level. Affects tone assignments for text and UI elements.
+ * @default 'standard'
+ */
+ contrast?: 'standard' | 'high';
+}
+
+export type ColorScaleTokens = Record<string, string>;
+
+// =============================================================================
+// Neutral chroma by style
+// =============================================================================
+
+const NEUTRAL_CHROMA: Record<string, number> = {
+ warm: 7,
+ cool: 5,
+ neutral: 3,
+};
+
+const NEUTRAL_VARIANT_CHROMA: Record<string, number> = {
+ warm: 10,
+ cool: 8,
+ neutral: 6,
+};
+
+// =============================================================================
+// Computation
+// =============================================================================
+
+function ld(light: string, dark: string): string {
+ return `light-dark(${light}, ${dark})`;
+}
+
+/**
+ * Expand a color scale config into XDS color token overrides.
+ *
+ * Only generates tokens that meaningfully derive from the accent color.
+ * Tokens that are convention-bound (status colors, categorical hues,
+ * --color-on-dark/on-light) are NOT generated — they fall through
+ * to colorDefaults.
+ *
+ * @example
+ * ```
+ * const tokens = expandColorScale({ accent: '#0064E0' });
+ * // tokens['--color-accent'] === 'light-dark(#..., #...)'
+ * ```
+ */
+export function expandColorScale(
+ config: XDSColorScaleConfig,
+): ColorScaleTokens {
+ const {accent, neutralStyle = 'cool', contrast = 'standard'} = config;
+
+ const seed = hexToHct(accent);
+ const seedHue = seed.hue;
+
+ const primaryChroma = Math.max(seed.chroma, 48);
+ const neutralChroma = NEUTRAL_CHROMA[neutralStyle] ?? 5;
+ const neutralVariantChroma = NEUTRAL_VARIANT_CHROMA[neutralStyle] ?? 8;
+
+ const P = tonalPalette(seedHue, primaryChroma);
+ const N = tonalPalette(seedHue, neutralChroma);
+ const NV = tonalPalette(seedHue, neutralVariantChroma);
+
+ const isHigh = contrast === 'high';
+
+ const textPrimaryLightTone = isHigh ? 0 : 10;
+ const textPrimaryDarkTone = isHigh ? 99 : 90;
+ const textSecondaryLightTone = isHigh ? 20 : 30;
+ const textSecondaryDarkTone = isHigh ? 80 : 70;
+
+ return {
+ // Core semantic
+ '--color-accent': ld(P[40], P[80]),
+ '--color-accent-muted': ld(
+ hexWithAlpha(P[40], 0.2),
+ hexWithAlpha(P[80], 0.25),
+ ),
+ '--color-on-accent': ld(P[100], P[20]),
+ '--color-neutral': ld(hexWithAlpha(N[10], 0.1), hexWithAlpha(N[90], 0.2)),
+ '--color-background-surface': ld(N[99], N[10]),
+ '--color-background-body': ld(N[95], N[5]),
+ '--color-overlay': ld(hexWithAlpha(N[10], 0.4), hexWithAlpha(N[10], 0.6)),
+ '--color-overlay-hover': ld(
+ hexWithAlpha(N[10], 0.05),
+ hexWithAlpha(N[100], 0.05),
+ ),
+ '--color-overlay-pressed': ld(
+ hexWithAlpha(N[10], 0.1),
+ hexWithAlpha(N[100], 0.1),
+ ),
+ '--color-background-muted': ld(
+ hexWithAlpha(N[10], 0.05),
+ hexWithAlpha(N[10], 0.5),
+ ),
+
+ // Text
+ '--color-text-primary': ld(N[textPrimaryLightTone], N[textPrimaryDarkTone]),
+ '--color-text-secondary': ld(
+ NV[textSecondaryLightTone],
+ NV[textSecondaryDarkTone],
+ ),
+ '--color-text-disabled': ld(NV[60], NV[40]),
+ '--color-text-accent': ld(P[30], P[80]),
+
+ // Icon
+ '--color-icon-accent': ld(P[40], P[80]),
+ '--color-icon-primary': ld(N[textPrimaryLightTone], N[textPrimaryDarkTone]),
+ '--color-icon-secondary': ld(
+ NV[textSecondaryLightTone],
+ NV[textSecondaryDarkTone],
+ ),
+ '--color-icon-disabled': ld(NV[60], NV[40]),
+
+ // Surface variants
+ '--color-background-card': ld(N[99], N[10]),
+ '--color-background-popover': ld(N[99], N[20]),
+ '--color-background-inverted': ld(N[10], N[99]),
+
+ // Border
+ '--color-border': ld(hexWithAlpha(N[10], 0.1), hexWithAlpha(N[95], 0.1)),
+ '--color-border-emphasized': ld(NV[70], NV[30]),
+
+ // Effects
+ '--color-skeleton': ld(NV[70], NV[30]),
+ '--color-shadow': ld(hexWithAlpha(N[0], 0.1), hexWithAlpha(N[0], 0.3)),
+ '--color-tint-hover': ld('black', 'white'),
+ };
+}
diff --git a/packages/core/src/theme/hct.test.ts b/packages/core/src/theme/hct.test.ts
new file mode 100644
index 0000000000..bc9a585582
--- /dev/null
+++ b/packages/core/src/theme/hct.test.ts
@@ -0,0 +1,91 @@
+import {describe, it, expect} from 'vitest';
+import {hexToHct, hctToHex, tonalPalette, hexWithAlpha} from './hct';
+
+function hexToRgb(hex: string): [number, number, number] {
+ const h = hex.replace('#', '');
+ return [
+ parseInt(h.slice(0, 2), 16),
+ parseInt(h.slice(2, 4), 16),
+ parseInt(h.slice(4, 6), 16),
+ ];
+}
+
+describe('hexToHct / hctToHex roundtrip', () => {
+ const cases = [
+ '#FF0000',
+ '#00FF00',
+ '#0000FF',
+ '#000000',
+ '#FFFFFF',
+ '#808080',
+ '#0064E0',
+ ];
+
+ for (const hex of cases) {
+ it(`roundtrips ${hex}`, () => {
+ const hct = hexToHct(hex);
+ const result = hctToHex(hct);
+ const [r1, g1, b1] = hexToRgb(hex);
+ const [r2, g2, b2] = hexToRgb(result);
+ expect(Math.abs(r1 - r2)).toBeLessThanOrEqual(1);
+ expect(Math.abs(g1 - g2)).toBeLessThanOrEqual(1);
+ expect(Math.abs(b1 - b2)).toBeLessThanOrEqual(1);
+ });
+ }
+});
+
+describe('hexToHct ranges', () => {
+ const cases = ['#FF0000', '#00FF00', '#0000FF', '#808080', '#0064E0'];
+
+ for (const hex of cases) {
+ it(`${hex} produces valid HCT ranges`, () => {
+ const {hue, chroma, tone} = hexToHct(hex);
+ expect(hue).toBeGreaterThanOrEqual(0);
+ expect(hue).toBeLessThanOrEqual(360);
+ expect(chroma).toBeGreaterThanOrEqual(0);
+ expect(tone).toBeGreaterThanOrEqual(0);
+ expect(tone).toBeLessThanOrEqual(100);
+ });
+ }
+
+ it('black has tone ≈ 0', () => {
+ const {tone} = hexToHct('#000000');
+ expect(tone).toBeCloseTo(0, 0);
+ });
+
+ it('white has tone ≈ 100', () => {
+ const {tone} = hexToHct('#FFFFFF');
+ expect(tone).toBeCloseTo(100, 0);
+ });
+});
+
+describe('tonalPalette', () => {
+ it('produces entries for all standard tones', () => {
+ const palette = tonalPalette(220, 48);
+ const expectedTones = [
+ 0, 5, 10, 20, 30, 40, 50, 60, 70, 80, 90, 95, 99, 100,
+ ];
+ for (const tone of expectedTones) {
+ expect(palette[tone]).toBeDefined();
+ expect(palette[tone]).toMatch(/^#[0-9A-F]{6}$/);
+ }
+ });
+});
+
+describe('hexWithAlpha', () => {
+ it('appends correct alpha hex for 1.0', () => {
+ expect(hexWithAlpha('#FF0000', 1)).toBe('#FF0000FF');
+ });
+
+ it('appends correct alpha hex for 0.5', () => {
+ expect(hexWithAlpha('#FF0000', 0.5)).toBe('#FF000080');
+ });
+
+ it('appends correct alpha hex for 0', () => {
+ expect(hexWithAlpha('#FF0000', 0)).toBe('#FF000000');
+ });
+
+ it('appends correct alpha hex for 0.2', () => {
+ expect(hexWithAlpha('#ABCDEF', 0.2)).toBe('#ABCDEF33');
+ });
+});
diff --git a/packages/core/src/theme/hct.ts b/packages/core/src/theme/hct.ts
new file mode 100644
index 0000000000..b05019afd0
--- /dev/null
+++ b/packages/core/src/theme/hct.ts
@@ -0,0 +1,273 @@
+/**
+ * @file hct.ts
+ * @input Hex color string (#RRGGBB)
+ * @output HCT color representation (Hue, Chroma, Tone)
+ * @position Theme utility; consumed by expandColorScale.ts
+ *
+ * Minimal HCT (Hue, Chroma, Tone) color space implementation.
+ * Ported from Google's material-color-utilities (Apache-2.0).
+ * Zero runtime dependencies — all math is self-contained.
+ *
+ * HCT combines:
+ * - Hue from CIELab (perceptually uniform hue)
+ * - Chroma approximated via CIELab C*ab (colorfulness)
+ * - Tone from L* (CIE Lightness, 0=black, 100=white)
+ */
+
+// =============================================================================
+// Types
+// =============================================================================
+
+export interface HCT {
+ hue: number;
+ chroma: number;
+ tone: number;
+}
+
+// =============================================================================
+// sRGB <-> Linear RGB
+// =============================================================================
+
+function srgbToLinear(c: number): number {
+ const s = c / 255;
+ return s <= 0.04045 ? s / 12.92 : Math.pow((s + 0.055) / 1.055, 2.4);
+}
+
+function linearToSrgb(c: number): number {
+ const s = c <= 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 1 / 2.4) - 0.055;
+ return Math.round(Math.min(255, Math.max(0, s * 255)));
+}
+
+// =============================================================================
+// Linear RGB <-> XYZ (D65 illuminant)
+// =============================================================================
+
+function linearRgbToXyz(
+ r: number,
+ g: number,
+ b: number,
+): [number, number, number] {
+ return [
+ 0.4124564 * r + 0.3575761 * g + 0.1804375 * b,
+ 0.2126729 * r + 0.7151522 * g + 0.072175 * b,
+ 0.0193339 * r + 0.119192 * g + 0.9503041 * b,
+ ];
+}
+
+function xyzToLinearRgb(
+ x: number,
+ y: number,
+ z: number,
+): [number, number, number] {
+ return [
+ 3.2404542 * x - 1.5371385 * y - 0.4985314 * z,
+ -0.969266 * x + 1.8760108 * y + 0.041556 * z,
+ 0.0556434 * x - 0.2040259 * y + 1.0572252 * z,
+ ];
+}
+
+// =============================================================================
+// XYZ <-> L*a*b*
+// =============================================================================
+
+const D65_WHITE: [number, number, number] = [0.95047, 1.0, 1.08883];
+
+function labF(t: number): number {
+ const delta = 6 / 29;
+ return t > delta * delta * delta
+ ? Math.cbrt(t)
+ : t / (3 * delta * delta) + 4 / 29;
+}
+
+function labFInv(t: number): number {
+ const delta = 6 / 29;
+ return t > delta ? t * t * t : 3 * delta * delta * (t - 4 / 29);
+}
+
+function xyzToLab(x: number, y: number, z: number): [number, number, number] {
+ const fx = labF(x / D65_WHITE[0]);
+ const fy = labF(y / D65_WHITE[1]);
+ const fz = labF(z / D65_WHITE[2]);
+ return [116 * fy - 16, 500 * (fx - fy), 200 * (fy - fz)];
+}
+
+function labToXyz(L: number, a: number, b: number): [number, number, number] {
+ const fy = (L + 16) / 116;
+ const fx = a / 500 + fy;
+ const fz = fy - b / 200;
+ return [
+ labFInv(fx) * D65_WHITE[0],
+ labFInv(fy) * D65_WHITE[1],
+ labFInv(fz) * D65_WHITE[2],
+ ];
+}
+
+// =============================================================================
+// Tone <-> Y (CIE Luminance)
+// =============================================================================
+
+export function toneToY(tone: number): number {
+ return labFInv((tone + 16) / 116);
+}
+
+export function yToTone(y: number): number {
+ return 116 * labF(y) - 16;
+}
+
+// =============================================================================
+// Hex <-> RGB
+// =============================================================================
+
+function hexToRgb(hex: string): [number, number, number] {
+ const h = hex.replace('#', '');
+ const full =
+ h.length === 3 ? h[0] + h[0] + h[1] + h[1] + h[2] + h[2] : h.slice(0, 6);
+ const n = parseInt(full, 16);
+ return [(n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff];
+}
+
+function rgbToHex(r: number, g: number, b: number): string {
+ return (
+ '#' +
+ [r, g, b]
+ .map(c => c.toString(16).padStart(2, '0'))
+ .join('')
+ .toUpperCase()
+ );
+}
+
+// =============================================================================
+// Core: Hex <-> HCT
+// =============================================================================
+
+/**
+ * Convert a hex color to HCT.
+ * Hue: 0-360, Chroma: 0-~120, Tone: 0-100.
+ */
+export function hexToHct(hex: string): HCT {
+ const [r, g, b] = hexToRgb(hex);
+ const lr = srgbToLinear(r);
+ const lg = srgbToLinear(g);
+ const lb = srgbToLinear(b);
+ const [x, y, z] = linearRgbToXyz(lr, lg, lb);
+ const [L, a, bLab] = xyzToLab(x, y, z);
+
+ const hueRad = Math.atan2(bLab, a);
+ let hue = (hueRad * 180) / Math.PI;
+ if (hue < 0) hue += 360;
+
+ const chroma = Math.sqrt(a * a + bLab * bLab);
+ const tone = L;
+
+ return {hue, chroma, tone: Math.max(0, Math.min(100, tone))};
+}
+
+/**
+ * Convert HCT to hex, with gamut mapping.
+ * Uses chroma reduction to find the closest in-gamut sRGB color.
+ */
+export function hctToHex(hct: HCT): string {
+ const {hue, chroma, tone} = hct;
+
+ if (tone <= 0) return '#000000';
+ if (tone >= 100) return '#FFFFFF';
+ if (chroma < 0.5) {
+ const gray = toneToGray(tone);
+ return rgbToHex(gray, gray, gray);
+ }
+
+ let lo = 0;
+ let hi = chroma;
+ let bestHex = '#000000';
+
+ for (let i = 0; i < 16; i++) {
+ const mid = (lo + hi) / 2;
+ const candidate = hctComponentToHex(hue, mid, tone);
+ if (candidate !== null) {
+ bestHex = candidate;
+ lo = mid;
+ } else {
+ hi = mid;
+ }
+ }
+
+ return bestHex;
+}
+
+function toneToGray(tone: number): number {
+ const y = toneToY(tone);
+ return linearToSrgb(y);
+}
+
+function hctComponentToHex(
+ hue: number,
+ chroma: number,
+ tone: number,
+): string | null {
+ const hueRad = (hue * Math.PI) / 180;
+ const a = Math.cos(hueRad) * chroma;
+ const b = Math.sin(hueRad) * chroma;
+ const L = tone;
+
+ const [x, y, z] = labToXyz(L, a, b);
+ const [lr, lg, lb] = xyzToLinearRgb(x, y, z);
+
+ const r = linearToSrgb(lr);
+ const g = linearToSrgb(lg);
+ const bVal = linearToSrgb(lb);
+
+ const rLin = srgbToLinear(r);
+ const gLin = srgbToLinear(g);
+ const bLin = srgbToLinear(bVal);
+
+ const tolerance = 0.02;
+ if (
+ Math.abs(rLin - lr) > tolerance ||
+ Math.abs(gLin - lg) > tolerance ||
+ Math.abs(bLin - lb) > tolerance
+ ) {
+ return null;
+ }
+
+ if (r < 0 || r > 255 || g < 0 || g > 255 || bVal < 0 || bVal > 255) {
+ return null;
+ }
+
+ return rgbToHex(r, g, bVal);
+}
+
+// =============================================================================
+// Tonal Palette
+// =============================================================================
+
+const PALETTE_TONES = [0, 5, 10, 20, 30, 40, 50, 60, 70, 80, 90, 95, 99, 100];
+
+/**
+ * Generate a tonal palette: hex colors at standard tones
+ * for a given hue and chroma.
+ */
+export function tonalPalette(
+ hue: number,
+ chroma: number,
+): Record<number, string> {
+ const result: Record<number, string> = {};
+ for (const tone of PALETTE_TONES) {
+ result[tone] = hctToHex({hue, chroma, tone});
+ }
+ return result;
+}
+
+// =============================================================================
+// Utility: hex with alpha
+// =============================================================================
+
+/**
+ * Append alpha (0-1) to a hex color as a 2-digit hex suffix.
+ */
+export function hexWithAlpha(hex: string, alpha: number): string {
+ const alphaHex = Math.round(alpha * 255)
+ .toString(16)
+ .padStart(2, '0')
+ .toUpperCase();
+ return hex + alphaHex;
+}
diff --git a/packages/core/src/theme/index.ts b/packages/core/src/theme/index.ts
index f742132dec..8f9925f2b1 100644
--- a/packages/core/src/theme/index.ts
+++ b/packages/core/src/theme/index.ts
@@ -74,6 +74,9 @@ export type {
RadiusScaleTokens,
} from './expandRadiusScale';
+export {expandColorScale} from './expandColorScale';
+export type {XDSColorScaleConfig, ColorScaleTokens} from './expandColorScale';
+
export {expandMotionScale} from './expandMotionScale';
export type {
XDSMotionScaleConfig,
diff --git a/packages/themes/brutalist/src/brutalistTheme.ts b/packages/themes/brutalist/src/brutalistTheme.ts
index 5e7878ad05..0c10c8b8bb 100644
--- a/packages/themes/brutalist/src/brutalistTheme.ts
+++ b/packages/themes/brutalist/src/brutalistTheme.ts
@@ -11,6 +11,9 @@ import {defineTheme} from '@xds/core/theme';
export const brutalistTheme = defineTheme({
name: 'brutalist',
+ // Hot pink accent — derives accent, background, text, border tokens via HCT
+ color: {accent: '#FF1493'},
+
// Monospace everything — body sets Courier, heading inherits
typography: {
body: {family: 'Courier New', fallbacks: '"Courier", monospace'},
@@ -26,12 +29,6 @@ export const brutalistTheme = defineTheme({
motion: {fast: 65, medium: 150, slow: 350, ratio: 0.75, easing: 'linear'},
tokens: {
- // Colors — high contrast, no subtlety
- '--color-accent': ['#FF1493', '#FF69B4'],
- '--color-accent-muted': ['#FF149333', '#FF69B43F'],
- '--color-background-surface': ['#FFFFFF', '#000000'],
- '--color-background-body': ['#F5F5F5', '#111111'],
- '--color-background-card': ['#FFFFFF', '#000000'],
// Contrast on hot pink accent — white in both modes
'--color-on-accent': ['#FFFFFF', '#FFFFFF'],
'--color-on-success': ['#FFFFFF', '#FFFFFF'],