Skip to content

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

TypeScript

feat(theme): defineTheme variants field + CLI theme resolution (#790)

Cindy Zhangd2bfbb0bada2
diff --git a/packages/cli/src/commands/build-theme.mjs b/packages/cli/src/commands/build-theme.mjs
index 55be4c25aa..0bee6c91af 100644
--- a/packages/cli/src/commands/build-theme.mjs
+++ b/packages/cli/src/commands/build-theme.mjs
@@ -42,6 +42,55 @@ function toIdentifier(name) {
return name.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
}
+/**
+ * Convert a kebab-case component name to PascalCase.
+ * e.g. 'button' → 'Button', 'progress-bar' → 'ProgressBar', 'avatar-status-dot' → 'AvatarStatusDot'
+ */
+function toPascalCase(name) {
+ return name
+ .split('-')
+ .map(part => part.charAt(0).toUpperCase() + part.slice(1))
+ .join('');
+}
+
+/**
+ * Generate TypeScript declaration file with module augmentation for theme variants.
+ *
+ * Maps component names from the theme's `variants` field to their module paths
+ * and augments the corresponding XDS{Component}VariantMap interfaces.
+ *
+ * @param {object} themeDef - Theme definition with variants
+ * @returns {string|null} TypeScript declaration content, or null if no variants
+ */
+function generateVariantDeclarations(themeDef) {
+ if (!themeDef.variants || Object.keys(themeDef.variants).length === 0) {
+ return null;
+ }
+
+ const sections = ['// Generated by xds theme build', ''];
+
+ for (const [componentKey, variantNames] of Object.entries(themeDef.variants)) {
+ if (!variantNames || variantNames.length === 0) continue;
+
+ const pascal = toPascalCase(componentKey);
+ const modulePath = `@xds/core/${pascal}`;
+ const interfaceName = `XDS${pascal}VariantMap`;
+
+ const entries = variantNames
+ .map(v => ` '${v}': true;`)
+ .join('\n');
+
+ sections.push(`declare module '${modulePath}' {`);
+ sections.push(` interface ${interfaceName} {`);
+ sections.push(...variantNames.map(v => ` '${v}': true;`));
+ sections.push(' }');
+ sections.push('}');
+ sections.push('');
+ }
+
+ return sections.join('\n');
+}
+
/**
* Resolve a token value — [light, dark] tuple becomes light-dark()
*/
@@ -616,6 +665,16 @@ export function registerTheme(program) {
console.log(`✓ ${path.relative(process.cwd(), jsPath)}`);
console.log(`✓ ${path.relative(process.cwd(), dtsPath)}`);
+ // Generate variant augmentation .d.ts if theme has custom variants
+ const variantDecl = generateVariantDeclarations(themeDef);
+ if (variantDecl) {
+ const variantDtsPath = path.join(outDir, `${baseName}.variants.d.ts`);
+ fs.writeFileSync(variantDtsPath, variantDecl);
+ const variantCount = Object.values(themeDef.variants)
+ .reduce((sum, v) => sum + v.length, 0);
+ console.log(`✓ ${path.relative(process.cwd(), variantDtsPath)} (${variantCount} variant augmentations)`);
+ }
+
// Print install instructions
const relDir = path.relative(process.cwd(), outDir);
const exportName = `${toIdentifier(baseName)}Theme`;
diff --git a/packages/cli/src/commands/component/index.mjs b/packages/cli/src/commands/component/index.mjs
index 72caa62569..14fef2b7b2 100644
--- a/packages/cli/src/commands/component/index.mjs
+++ b/packages/cli/src/commands/component/index.mjs
@@ -29,6 +29,7 @@ import {
extractProps,
} from '../../lib/component-legacy.mjs';
import {findClosestComponents} from '../../lib/string-utils.mjs';
+import {resolveTheme} from '../../lib/resolve-theme.mjs';
export function registerComponent(program) {
program
@@ -60,6 +61,9 @@ export function registerComponent(program) {
process.exit(1);
}
+ // Resolve active theme for variant merging
+ const themeData = resolveTheme(process.cwd());
+
if (options.category || options.list || !name) {
const components = discoverComponents(coreDir);
@@ -84,7 +88,7 @@ export function registerComponent(program) {
try {
const docs = await loadDocs(readme, {zh, lang});
const importHint = resolveImportPath(coreDir, comp);
- console.log(formatBrief(docs, comp, importHint));
+ console.log(formatBrief(docs, comp, importHint, { themeData }));
} catch {
console.log(` ${comp}`);
}
@@ -105,7 +109,7 @@ export function registerComponent(program) {
// --list or no name: show all components
if (detail === 'brief') {
// Brief list: brief summaries of ALL components
- console.log(await formatBriefAll(coreDir, {zh, lang}));
+ console.log(await formatBriefAll(coreDir, {zh, lang, themeData}));
} else {
console.log('');
for (const [category, comps] of Object.entries(components)) {
@@ -171,11 +175,11 @@ export function registerComponent(program) {
if (options.props) {
console.log(formatProps(docs, resolvedName));
} else if (detail === 'brief') {
- console.log(formatBrief(docs, resolvedName, importHint));
+ console.log(formatBrief(docs, resolvedName, importHint, { themeData }));
} else if (detail === 'compact') {
console.log(formatCompact(docs, resolvedName, importHint));
} else {
- console.log(formatFull(docs));
+ console.log(formatFull(docs, { themeData }));
}
} else {
// Legacy path for README.md files
diff --git a/packages/cli/src/lib/component-format.mjs b/packages/cli/src/lib/component-format.mjs
index b7d19a627c..b6dc425e14 100644
--- a/packages/cli/src/lib/component-format.mjs
+++ b/packages/cli/src/lib/component-format.mjs
@@ -20,10 +20,85 @@ function formatPropsTable(props) {
return lines.join('\n');
}
+/**
+ * Get the variant values for a given theming target, extracting them from
+ * the visualProps and the variant prop in the component's props list.
+ * Returns an array of variant strings from the `variant` prop type,
+ * or the variants from target visualProps.
+ */
+function getTargetVariants(target, docs) {
+ if (!target.visualProps?.length) return [];
+
+ // If variant is a visualProp, try to resolve the actual variant values from props
+ if (target.visualProps.includes('variant')) {
+ const allProps = docs.props || (docs.components?.[0]?.props) || [];
+ const variantProp = allProps.find(p => p.name === 'variant');
+ if (variantProp && variantProp.type.includes('|')) {
+ return variantProp.type
+ .replace(/['"]/g, '')
+ .split('|')
+ .map(v => v.trim())
+ .filter(Boolean);
+ }
+ }
+
+ // Return all visualProps as-is (size, orientation, etc.)
+ return target.visualProps;
+}
+
+/**
+ * Get the state classes for a theming target from the states field.
+ */
+function getTargetStates(target) {
+ return target.states || [];
+}
+
+/**
+ * Format the theming targets table, merging in theme variants if available.
+ *
+ * @param {object} docs - Component doc object
+ * @param {object|null} themeData - Resolved theme data with variants
+ * @returns {string} Markdown table
+ */
+function formatTargetsTable(docs, themeData) {
+ if (!docs.theming?.targets?.length) return '';
+
+ const lines = [];
+ lines.push('| Class | Variants | States |');
+ lines.push('|-------|----------|--------|');
+
+ for (const target of docs.theming.targets) {
+ const coreVariants = getTargetVariants(target, docs);
+ const states = getTargetStates(target);
+
+ // Merge theme variants — keyed by component name derived from class
+ // e.g. className 'xds-button' → component key 'button'
+ const componentKey = target.className.replace(/^xds-/, '');
+ const themeVariants = themeData?.variants?.[componentKey] || [];
+
+ // Build variant display: core variants plain, theme variants with * suffix
+ const variantParts = [
+ ...coreVariants,
+ ...themeVariants.map(v => `${v}*`),
+ ];
+
+ const variantsStr = variantParts.length > 0 ? variantParts.join(', ') : '—';
+ const statesStr = states.length > 0 ? states.join(', ') : '—';
+
+ lines.push(`| \`${target.className}\` | ${variantsStr} | ${statesStr} |`);
+ }
+
+ return lines.join('\n');
+}
+
/**
* Format full component docs (default mode, replaces cleanReadme).
+ *
+ * @param {object} docs - Component doc object
+ * @param {object} [options] - Options
+ * @param {object|null} [options.themeData] - Resolved theme data
*/
-export function formatFull(docs) {
+export function formatFull(docs, options = {}) {
const sections = [];
sections.push(`# ${docs.name}\n`);
@@ -65,20 +140,21 @@ export function formatFull(docs) {
}
if (docs.theming) {
+ const { themeData = null } = options;
sections.push('## Theming\n');
- const componentKey = docs.name.toLowerCase();
-
- // Targets table
+// Targets table with theme variant merging
if (docs.theming.targets?.length) {
- const targetLines = [];
- targetLines.push('| Class | Variants | States |');
- targetLines.push('|-------|---------|--------|');
- for (const t of docs.theming.targets) {
- const variants = t.visualProps?.length ? t.visualProps.join(', ') : '—';
- const states = t.states?.length ? t.states.join(', ') : '—';
- targetLines.push(`| \`${t.className}\` | ${variants} | ${states} |`);
+ const targetsTable = formatTargetsTable(docs, themeData);
+ sections.push(targetsTable + '\n');
+
+ // Note about theme variants if any are present
+ if (themeData?.variants) {
+ const componentKeys = docs.theming.targets.map(t => t.className.replace(/^xds-/, ''));
+ const hasThemeVariants = componentKeys.some(k => themeData.variants[k]?.length > 0);
+ if (hasThemeVariants) {
+ sections.push(`_\\* = custom variant from ${themeData.name || 'active'} theme_\n`);
+ }
}
- sections.push(targetLines.join('\n') + '\n');
// Generate defineTheme example with class targeting
const exampleLines = ['Override in defineTheme:\n```ts\ncomponents: {'];
@@ -111,15 +187,12 @@ export function formatFull(docs) {
sections.push(exampleLines.join('\n'));
}
- if (docs.theming.surfaces?.length) {
- const surfaceLines = [];
- surfaceLines.push('| Surface | Description |');
- surfaceLines.push('|---------|-------------|');
- for (const s of docs.theming.surfaces) {
- surfaceLines.push(`| \`${s.name}\` | ${s.description} |`);
- }
- sections.push(surfaceLines.join('\n') + '\n');
+ // Legacy componentKey (for backward compatibility)
+ if (docs.theming.componentKey) {
+ sections.push(`Component key: \`${docs.theming.componentKey}\`\n`);
}
+
+ // Component CSS vars
if (docs.theming?.vars?.length) {
const varLines = [];
varLines.push('| CSS Variable | Default | Description |');
@@ -230,7 +303,7 @@ export function formatCompact(docs, componentName, importHint) {
*
* For multi-component docs, extracts the entry matching componentName.
*/
-export function formatBrief(docs, componentName, importHint) {
+export function formatBrief(docs, componentName, importHint, options = {}) {
const displayName = componentName.startsWith('XDS')
? componentName
: `XDS${componentName}`;
@@ -300,12 +373,17 @@ export function formatBrief(docs, componentName, importHint) {
}
}
- // Theme targets (class names, variants, states)
+// Theme targets (class names, variants, states) with theme variant merging
if (docs.theming?.targets?.length) {
+ const { themeData = null } = options;
const targetParts = docs.theming.targets.map(t => {
const parts = [t.className];
if (t.visualProps?.length) parts.push(`variants: ${t.visualProps.join(', ')}`);
if (t.states?.length) parts.push(`states: ${t.states.join(', ')}`);
+ // Merge theme variants
+ const componentKey = t.className.replace(/^xds-/, '');
+ const themeVars = themeData?.variants?.[componentKey];
+ if (themeVars?.length) parts.push(`theme: ${themeVars.map(v => v + '*').join(', ')}`);
return parts.join(' ');
});
output.push(` Targets: ${targetParts.join(' | ')}`);
@@ -351,7 +429,7 @@ export function formatProps(docs, componentName) {
/**
* Format brief summaries for ALL components in one output.
*/
-export async function formatBriefAll(coreDir, {zh = false, lang} = {}) {
+export async function formatBriefAll(coreDir, {zh = false, lang, themeData = null} = {}) {
const components = discoverComponents(coreDir);
const output = [];
@@ -362,7 +440,7 @@ export async function formatBriefAll(coreDir, {zh = false, lang} = {}) {
if (readmePath && readmePath.endsWith('.doc.mjs')) {
const docs = await loadDocs(readmePath, {zh, lang});
const importPath = resolveImportPath(coreDir, comp);
- output.push(formatBrief(docs, comp, importPath));
+ output.push(formatBrief(docs, comp, importPath, { themeData }));
} else if (readmePath) {
// Legacy README.md path
const content = fs.readFileSync(readmePath, 'utf-8');
diff --git a/packages/cli/src/lib/resolve-theme.mjs b/packages/cli/src/lib/resolve-theme.mjs
new file mode 100644
index 0000000000..012bf3808d
--- /dev/null
+++ b/packages/cli/src/lib/resolve-theme.mjs
@@ -0,0 +1,145 @@
+/**
+ * @file Theme resolution — resolve a theme from config or environment
+ *
+ * Resolution sources (in priority order):
+ * 1. XDS_THEME environment variable
+ * 2. xds.theme field in package.json
+ *
+ * Resolution strategy for the value:
+ * - Starts with `.` or `/` → file path relative to cwd
+ * - Starts with `@` → npm package (require/import)
+ * - Otherwise → try `@xds/theme-{name}`, then try as bare package name
+ *
+ * Returns the theme object's `variants` and `fonts` if available,
+ * or null if no theme is configured or found.
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {createRequire} from 'node:module';
+
+const _require = createRequire(import.meta.url);
+
+/**
+ * Try to load a module, returning the default export or the module itself.
+ * Returns null if the module cannot be found.
+ */
+function tryLoadModule(specifier, cwd) {
+ // For relative/absolute paths, resolve against cwd
+ if (specifier.startsWith('.') || specifier.startsWith('/')) {
+ const resolved = path.resolve(cwd, specifier);
+ try {
+ return _require(resolved);
+ } catch {
+ return null;
+ }
+ }
+
+ // For package specifiers, try require
+ try {
+ return _require(specifier);
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Extract theme data from a loaded module.
+ * Handles both `module.default` and direct `module` patterns,
+ * as well as named exports like `module.theme` or `module.{name}Theme`.
+ */
+function extractTheme(mod) {
+ if (!mod || typeof mod !== 'object') return null;
+
+ // Check default export
+ const obj = mod.default || mod;
+
+ // If it looks like a theme (has name + tokens or variants), use it directly
+ if (obj.name && (obj.tokens || obj.variants)) {
+ return obj;
+ }
+
+ // Check for a `theme` named export
+ if (mod.theme && typeof mod.theme === 'object' && mod.theme.name) {
+ return mod.theme;
+ }
+
+ // Check for any export ending in 'Theme'
+ for (const key of Object.keys(mod)) {
+ if (key.endsWith('Theme') && typeof mod[key] === 'object' && mod[key]?.name) {
+ return mod[key];
+ }
+ }
+
+ return null;
+}
+
+/**
+ * Resolve the active XDS theme from config and environment.
+ *
+ * @param {string} [cwd] - Working directory (defaults to process.cwd())
+ * @returns {{ variants?: Record<string, string[]>, fonts?: Record<string, string>, name?: string } | null}
+ */
+export function resolveTheme(cwd = process.cwd()) {
+ // 1. Determine theme specifier
+ let specifier = process.env.XDS_THEME || null;
+
+ if (!specifier) {
+ // Read from package.json
+ const pkgPath = path.join(cwd, 'package.json');
+ if (fs.existsSync(pkgPath)) {
+ try {
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
+ specifier = pkg.xds?.theme || null;
+ } catch {
+ // Ignore parse errors
+ }
+ }
+ }
+
+ if (!specifier) {
+ return null;
+ }
+
+ // 2. Resolve the specifier to a module
+ let mod = null;
+
+ if (specifier.startsWith('.') || specifier.startsWith('/')) {
+ // File path
+ mod = tryLoadModule(specifier, cwd);
+ if (!mod) {
+ console.warn(`⚠ XDS theme: could not resolve file "${specifier}" from ${cwd}`);
+ return null;
+ }
+ } else if (specifier.startsWith('@')) {
+ // Scoped package
+ mod = tryLoadModule(specifier, cwd);
+ if (!mod) {
+ console.warn(`⚠ XDS theme: could not resolve package "${specifier}"`);
+ return null;
+ }
+ } else {
+ // Convention: try @xds/theme-{name} first, then bare package
+ mod = tryLoadModule(`@xds/theme-${specifier}`, cwd);
+ if (!mod) {
+ mod = tryLoadModule(specifier, cwd);
+ }
+ if (!mod) {
+ console.warn(`⚠ XDS theme: could not resolve "${specifier}" (tried @xds/theme-${specifier} and ${specifier})`);
+ return null;
+ }
+ }
+
+ // 3. Extract theme data
+ const theme = extractTheme(mod);
+ if (!theme) {
+ console.warn(`⚠ XDS theme: loaded "${specifier}" but could not find a theme object`);
+ return null;
+ }
+
+ return {
+ name: theme.name || null,
+ variants: theme.variants || null,
+ fonts: theme.fonts || null,
+ };
+}
diff --git a/packages/core/src/AppShell/XDSAppShell.tsx b/packages/core/src/AppShell/XDSAppShell.tsx
index f65aeb3871..e95e548843 100644
--- a/packages/core/src/AppShell/XDSAppShell.tsx
+++ b/packages/core/src/AppShell/XDSAppShell.tsx
@@ -759,7 +759,6 @@ export function XDSAppShell({
<div
ref={setShellRef}
data-testid={dataTestId}
- data-variant={variant}
{...mergeProps(
xdsClassName('app-shell', {height, variant}),
stylex.props(
diff --git a/packages/core/src/Avatar/XDSAvatarStatusDot.tsx b/packages/core/src/Avatar/XDSAvatarStatusDot.tsx
index f6dc904758..9a7bb165c9 100644
--- a/packages/core/src/Avatar/XDSAvatarStatusDot.tsx
+++ b/packages/core/src/Avatar/XDSAvatarStatusDot.tsx
@@ -188,7 +188,6 @@ export function XDSAvatarStatusDot({
return (
<div
{...(label ? {'aria-label': label} : undefined)}
- data-variant={variant}
{...mergeProps(
xdsClassName('avatar-status-dot', {variant}),
stylex.props(
diff --git a/packages/core/src/Badge/XDSBadge.tsx b/packages/core/src/Badge/XDSBadge.tsx
index 0ee35ac1c8..4fa02061c1 100644
--- a/packages/core/src/Badge/XDSBadge.tsx
+++ b/packages/core/src/Badge/XDSBadge.tsx
@@ -152,7 +152,6 @@ export function XDSBadge({
return (
<span
ref={ref}
- data-variant={variant}
{...mergeProps(
xdsClassName('badge', {variant}),
stylex.props(
diff --git a/packages/core/src/Banner/XDSBanner.tsx b/packages/core/src/Banner/XDSBanner.tsx
index 8e5219c840..cdb3b394e0 100644
--- a/packages/core/src/Banner/XDSBanner.tsx
+++ b/packages/core/src/Banner/XDSBanner.tsx
@@ -404,7 +404,6 @@ export function XDSBanner({
ref={ref}
role={role}
data-testid={testId}
- data-variant={variant}
{...mergeProps(
xdsClassName('banner', {variant}),
stylex.props(
diff --git a/packages/core/src/Breadcrumbs/XDSBreadcrumbs.tsx b/packages/core/src/Breadcrumbs/XDSBreadcrumbs.tsx
index 56c5f7ee6f..18a1493d05 100644
--- a/packages/core/src/Breadcrumbs/XDSBreadcrumbs.tsx
+++ b/packages/core/src/Breadcrumbs/XDSBreadcrumbs.tsx
@@ -246,7 +246,6 @@ export function XDSBreadcrumbs({
ref={ref}
aria-label={label}
data-testid={testId}
- data-variant={variant}
{...mergeProps(
xdsClassName('breadcrumbs', {variant}),
stylex.props(navStyles.root, xstyle),
diff --git a/packages/core/src/Button/XDSButton.tsx b/packages/core/src/Button/XDSButton.tsx
index bda50de087..03a3c7b744 100644
--- a/packages/core/src/Button/XDSButton.tsx
+++ b/packages/core/src/Button/XDSButton.tsx
@@ -393,7 +393,6 @@ export function XDSButton({
disabled={buttonDisabled}
aria-label={isIconOnly ? label : undefined}
aria-busy={isLoadingState || undefined}
- data-variant={variant}
{...mergeProps(
xdsClassName('button', {variant, size}),
stylex.props(
diff --git a/packages/core/src/Dialog/XDSDialog.tsx b/packages/core/src/Dialog/XDSDialog.tsx
index d9e852a69a..c9b74b1fba 100644
--- a/packages/core/src/Dialog/XDSDialog.tsx
+++ b/packages/core/src/Dialog/XDSDialog.tsx
@@ -345,7 +345,6 @@ export function XDSDialog({
onClick={handleClick}
onCancel={handleCancel}
aria-modal="true"
- data-variant={variant}
{...mergeProps(
xdsClassName('dialog', {variant}),
stylex.props(
diff --git a/packages/core/src/Divider/XDSDivider.tsx b/packages/core/src/Divider/XDSDivider.tsx
index e697c5ad5b..e286946c6d 100644
--- a/packages/core/src/Divider/XDSDivider.tsx
+++ b/packages/core/src/Divider/XDSDivider.tsx
@@ -190,7 +190,6 @@ export function XDSDivider({
ref={ref as React.Ref<HTMLDivElement>}
role="separator"
aria-orientation={orientation}
- data-variant={variant}
{...mergeProps(
xdsClassName('divider', {variant, orientation}),
stylex.props(
diff --git a/packages/core/src/Field/XDSFieldStatus.tsx b/packages/core/src/Field/XDSFieldStatus.tsx
index 055c65782a..ebe5239466 100644
--- a/packages/core/src/Field/XDSFieldStatus.tsx
+++ b/packages/core/src/Field/XDSFieldStatus.tsx
@@ -128,7 +128,6 @@ export function XDSFieldStatus({
return (
<div
id={id}
- data-variant={variant}
{...mergeProps(
xdsClassName('field-status', {type, variant}),
stylex.props(
diff --git a/packages/core/src/Pagination/XDSPagination.tsx b/packages/core/src/Pagination/XDSPagination.tsx
index b6be638cd3..861d53c350 100644
--- a/packages/core/src/Pagination/XDSPagination.tsx
+++ b/packages/core/src/Pagination/XDSPagination.tsx
@@ -526,7 +526,6 @@ export function XDSPagination({
ref={ref}
aria-label={label}
data-testid={testId}
- data-variant={variant}
{...mergeProps(
xdsClassName('pagination', {variant, size}),
stylex.props(styles.root, xstyle),
diff --git a/packages/core/src/ProgressBar/XDSProgressBar.tsx b/packages/core/src/ProgressBar/XDSProgressBar.tsx
index b892029288..835cb11509 100644
--- a/packages/core/src/ProgressBar/XDSProgressBar.tsx
+++ b/packages/core/src/ProgressBar/XDSProgressBar.tsx
@@ -296,7 +296,6 @@ export function XDSProgressBar({
return (
<div
ref={ref}
- data-variant={variant}
{...mergeProps(
xdsClassName('progressbar', {variant, size}),
stylex.props(styles.container, xstyle),
diff --git a/packages/core/src/Section/XDSSection.tsx b/packages/core/src/Section/XDSSection.tsx
index 7d948dd35a..1d3c050ff7 100644
--- a/packages/core/src/Section/XDSSection.tsx
+++ b/packages/core/src/Section/XDSSection.tsx
@@ -242,7 +242,6 @@ export function XDSSection({
return (
<div
ref={ref as React.Ref<HTMLDivElement>}
- data-variant={variant}
{...mergeProps(
xdsClassName('section', {variant}),
stylex.props(
diff --git a/packages/core/src/StatusDot/XDSStatusDot.tsx b/packages/core/src/StatusDot/XDSStatusDot.tsx
index ed597c0eac..96808fd54c 100644
--- a/packages/core/src/StatusDot/XDSStatusDot.tsx
+++ b/packages/core/src/StatusDot/XDSStatusDot.tsx
@@ -192,7 +192,6 @@ export function XDSStatusDot({
ref={ref}
role="img"
aria-label={label}
- data-variant={variant}
{...mergeProps(
xdsClassName('statusdot', {variant, size}),
stylex.props(
diff --git a/packages/core/src/theme/defineTheme.test.ts b/packages/core/src/theme/defineTheme.test.ts
index afda940b69..60566a64e7 100644
--- a/packages/core/src/theme/defineTheme.test.ts
+++ b/packages/core/src/theme/defineTheme.test.ts
@@ -432,3 +432,36 @@ describe('radiusScale', () => {
expect(theme.tokens['--radius-2']).toBe('8px');
});
});
+
+describe('variants', () => {
+ it('passes through variants from input to output', () => {
+ const theme = defineTheme({
+ name: 'custom',
+ variants: {
+ button: ['primary-muted', 'primary-outline'],
+ badge: ['info-subtle'],
+ },
+ });
+ expect(theme.variants).toEqual({
+ button: ['primary-muted', 'primary-outline'],
+ badge: ['info-subtle'],
+ });
+ });
+
+ it('returns undefined variants when not provided', () => {
+ const theme = defineTheme({name: 'bare'});
+ expect(theme.variants).toBeUndefined();
+ });
+
+ it('combines variants with tokens and components', () => {
+ const theme = defineTheme({
+ name: 'combo',
+ tokens: {'--color-accent': '#FF0000'},
+ components: {button: {base: {borderRadius: '999px'}}},
+ variants: {button: ['primary-muted']},
+ });
+ expect(theme.tokens['--color-accent']).toBe('#FF0000');
+ expect(theme.components?.button?.base?.borderRadius).toBe('999px');
+ expect(theme.variants).toEqual({button: ['primary-muted']});
+ });
+});
diff --git a/packages/core/src/theme/defineTheme.ts b/packages/core/src/theme/defineTheme.ts
index 108909ce59..befa4d5cdc 100644
--- a/packages/core/src/theme/defineTheme.ts
+++ b/packages/core/src/theme/defineTheme.ts
@@ -215,6 +215,23 @@ export interface XDSDefineThemeInput {
components?: XDSComponentStyleMap;
/** Icon registry — maps semantic icon names to React nodes */
icons?: Partial<XDSIconRegistry>;
+ /**
+ * Custom variants added by this theme. Keyed by component name (lowercase),
+ * value is an array of variant strings.
+ *
+ * These variants are available at runtime (CSS + class names work correctly)
+ * but don't provide autocomplete until `xds theme build` generates the
+ * TypeScript module augmentation file.
+ *
+ * @example
+ * ```tsx
+ * variants: {
+ * button: ['primary-muted', 'primary-outline'],
+ * badge: ['info-subtle'],
+ * }
+ * ```
+ */
+ variants?: Record<string, string[]>;
}
/** A defined theme — ready to pass to <XDSTheme> */
@@ -227,6 +244,8 @@ export interface XDSDefinedTheme {
components?: XDSComponentStyleMap;
/** Icon registry */
icons?: Partial<XDSIconRegistry>;
+ /** Custom variants added by this theme, keyed by component name (lowercase) */
+ variants?: Record<string, string[]>;
/** Whether this theme has been pre-compiled by theme build CLI */
__built?: true;
}
@@ -364,6 +383,7 @@ export function defineTheme(input: XDSDefineThemeInput): XDSDefinedTheme {
tokens,
components,
icons: input.icons,
+ variants: input.variants,
};
}