Skip to content

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

TypeScript

fix(theme): standalone theme fixes — baseline text styling, extends, build improvements (#1831)

Cindy Zhang6b196680fc80
diff --git a/.claude/commands/create-theme.md b/.claude/commands/create-theme.md
index 8bf3e4d81b..8b3e9e9db4 100644
--- a/.claude/commands/create-theme.md
+++ b/.claude/commands/create-theme.md
@@ -147,6 +147,26 @@ Component overrides generate scoped CSS:
- **Unbuilt**: `XDSTheme` generates CSS and injects `<style>` at runtime
- **Built**: `npx xds theme build` pre-compiles to a CSS file
+## Extending an Existing Theme
+
+Use `extends` to derive from another theme — inherits tokens, components, icons, fonts. Only specify overrides.
+
+```tsx
+import {defineTheme} from '@xds/core/theme';
+import {defaultTheme} from '@xds/theme-default';
+
+export const brandTheme = defineTheme({
+ name: 'brand',
+ extends: defaultTheme,
+ icons: myIcons, // swap icons
+ tokens: {
+ '--color-accent': ['#7B61FF', '#9B85FF'], // override accent
+ },
+});
+```
+
+Child values win. Tokens and components are deep-merged; scale configs (typography, motion, radius) replace entirely.
+
## Reference
See existing themes for examples:
diff --git a/apps/storybook/.storybook/preview.tsx b/apps/storybook/.storybook/preview.tsx
index 4efa223775..719a209556 100644
--- a/apps/storybook/.storybook/preview.tsx
+++ b/apps/storybook/.storybook/preview.tsx
@@ -109,7 +109,7 @@ const preview: Preview = {
},
},
initialGlobals: {
- xdsTheme: 'default',
+ xdsTheme: 'none',
colorMode: 'light',
},
decorators: [withXDSTheme],
diff --git a/packages/cli/docs/theme.doc.mjs b/packages/cli/docs/theme.doc.mjs
index 5c2fef3977..8d5135d6e0 100644
--- a/packages/cli/docs/theme.doc.mjs
+++ b/packages/cli/docs/theme.doc.mjs
@@ -175,6 +175,43 @@ const myTheme = defineTheme({
},
],
},
+ {
+ title: 'Extending a Theme',
+ content: [
+ {
+ type: 'prose',
+ text: '`extends` lets you derive a new theme from an existing one — inheriting its tokens, component overrides, icons, and fonts. Only specify what you want to change; everything else carries over from the base theme.',
+ },
+ {
+ type: 'code',
+ lang: 'tsx',
+ label: 'Extending the default theme',
+ code: `import {defineTheme} from '@xds/core/theme';
+import {defaultTheme} from '@xds/theme-default';
+import {myIcons} from './icons';
+
+const brandTheme = defineTheme({
+ name: 'brand',
+ extends: defaultTheme,
+ icons: myIcons,
+ tokens: {
+ '--color-accent': ['#7B61FF', '#9B85FF'],
+ },
+});`,
+ },
+ {
+ type: 'table',
+ headers: ['Field', 'Merge behavior'],
+ rows: [
+ ['tokens', 'Base tokens are copied first, then child tokens override on top.'],
+ ['components', 'Deep-merged — child component rules override matching keys from the base.'],
+ ['icons', 'Shallow-merged — child icons override matching names from the base.'],
+ ['fonts', 'Base fonts included first, then child fonts appended.'],
+ ['typography, motion, radius, color', 'Child config replaces base entirely (these are scale inputs, not additive).'],
+ ],
+ },
+ ],
+ },
{
title: 'Component Style Overrides',
content: [
diff --git a/packages/cli/src/commands/build-theme.mjs b/packages/cli/src/commands/build-theme.mjs
index 08e75f59d1..670eefa284 100644
--- a/packages/cli/src/commands/build-theme.mjs
+++ b/packages/cli/src/commands/build-theme.mjs
@@ -35,6 +35,28 @@ try {
// Core not available — fall back to legacy generation
}
+/**
+ * Build a @generated attribution header for generated files.
+ * @param {string} sourceFile - Relative path to the source theme file
+ * @param {'css'|'js'|'ts'} lang - File language (determines comment syntax)
+ * @param {string} [command] - The full CLI command used to generate this file
+ */
+function generatedHeader(sourceFile, lang = 'js', command) {
+ const timestamp = new Date().toISOString();
+ const body = [
+ `@generated by \`xds theme build\` — do not edit manually.`,
+ `Source: ${sourceFile}`,
+ ];
+ if (command) {
+ body.push(`Command: ${command}`);
+ }
+ body.push(`Generated: ${timestamp}`);
+ if (lang === 'css') {
+ return `/*\n * ${body.join('\n * ')}\n */\n\n`;
+ }
+ return `/**\n * ${body.join('\n * ')}\n */\n\n`;
+}
+
/**
* Convert camelCase CSS property to kebab-case
*/
@@ -1026,10 +1048,6 @@ export function registerTheme(program) {
if (_generateThemeRulesSplit) {
const {component, prose} = _generateThemeRulesSplit(resolvedTheme);
- if (component.length === 0 && prose.length === 0) {
- if (!json) console.log('No overrides found — nothing to build.');
- return;
- }
const cssParts = [];
if (prose.length > 0) {
const proseInner = prose.join('\n\n');
@@ -1053,21 +1071,19 @@ export function registerTheme(program) {
css = cssParts.join('\n\n') + '\n';
} else {
const rules = _generateThemeRules(resolvedTheme);
- if (rules.length === 0) {
- if (!json) console.log('No overrides found — nothing to build.');
- return;
- }
- const inner = rules.join('\n\n');
- const scopeBlock = `@scope (${scopeSelector}) to (${scopeTo}) {\n${inner}\n}`;
- const colorSchemeDecl = scopeBlock.includes('light-dark(')
- ? ' :root { color-scheme: light dark; }\n\n'
- : '';
- css = `@layer xds-theme {\n${colorSchemeDecl}${scopeBlock}\n}\n`;
- // On-media rules (legacy path)
- if (_generateOnMediaCSS) {
- const onMediaCss = _generateOnMediaCSS(resolvedTheme);
- if (onMediaCss) {
- css += `\n@layer xds-theme {\n${onMediaCss}\n}\n`;
+ if (rules.length > 0) {
+ const inner = rules.join('\n\n');
+ const scopeBlock = `@scope (${scopeSelector}) to (${scopeTo}) {\n${inner}\n}`;
+ const colorSchemeDecl = scopeBlock.includes('light-dark(')
+ ? ' :root { color-scheme: light dark; }\n\n'
+ : '';
+ css = `@layer xds-theme {\n${colorSchemeDecl}${scopeBlock}\n}\n`;
+ // On-media rules (legacy path)
+ if (_generateOnMediaCSS) {
+ const onMediaCss = _generateOnMediaCSS(resolvedTheme);
+ if (onMediaCss) {
+ css += `\n@layer xds-theme {\n${onMediaCss}\n}\n`;
+ }
}
}
}
@@ -1089,14 +1105,18 @@ export function registerTheme(program) {
css = `@layer xds-theme {\n${colorSchemeDecl}${joined}\n}\n`;
}
+ // Source path relative to cwd — used in @generated headers
+ const sourceRelative = path.relative(process.cwd(), filePath);
+ const buildCommand = `xds theme build ${sourceRelative}${options.out ? ' --out ' + path.relative(process.cwd(), path.resolve(process.cwd(), options.out)) : ''}`;
+
// Determine output path
const outPath = options.out
? path.resolve(process.cwd(), options.out)
: filePath.replace(/\.(ts|tsx|js|jsx|mjs)$/, '.css');
- // Write CSS
+ // Write CSS with @generated header
fs.mkdirSync(path.dirname(outPath), {recursive: true});
- fs.writeFileSync(outPath, css);
+ fs.writeFileSync(outPath, generatedHeader(sourceRelative, 'css', buildCommand) + css);
const displayTheme = resolvedTheme || themeDef;
const tokenCount = displayTheme.tokens ? Object.keys(displayTheme.tokens).length : 0;
@@ -1118,8 +1138,8 @@ export function registerTheme(program) {
const iconInfo = extractIconInfo(filePath);
- fs.writeFileSync(jsPath, generateBuiltModule(resolvedTheme || themeDef, iconInfo));
- fs.writeFileSync(dtsPath, generateBuiltTypes(themeDef, iconInfo));
+ fs.writeFileSync(jsPath, generatedHeader(sourceRelative, 'js', buildCommand) + generateBuiltModule(resolvedTheme || themeDef, iconInfo));
+ fs.writeFileSync(dtsPath, generatedHeader(sourceRelative, 'ts', buildCommand) + generateBuiltTypes(themeDef, iconInfo));
if (!json) {
console.log(`✓ ${path.relative(process.cwd(), jsPath)}`);
@@ -1132,7 +1152,7 @@ export function registerTheme(program) {
let variantDtsPath;
if (variantDecl) {
variantDtsPath = path.join(outDir, `${baseName}.variants.d.ts`);
- fs.writeFileSync(variantDtsPath, variantDecl);
+ fs.writeFileSync(variantDtsPath, generatedHeader(sourceRelative, 'ts', buildCommand) + variantDecl);
const augCount = (variantDecl.match(/': true;/g) || []).length;
if (!json) console.log(`✓ ${path.relative(process.cwd(), variantDtsPath)} (${augCount} type augmentations)`);
}
diff --git a/packages/core/src/Text/XDSHeading.tsx b/packages/core/src/Text/XDSHeading.tsx
index 5f14f03c6f..6ee7a859fc 100644
--- a/packages/core/src/Text/XDSHeading.tsx
+++ b/packages/core/src/Text/XDSHeading.tsx
@@ -14,7 +14,6 @@
* - /packages/cli/templates/blocks/components/Text/ (showcase blocks)
*/
-
import {lazy, Suspense, useCallback, useRef, type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import type {
@@ -25,6 +24,7 @@ import type {
} from '../theme/types';
import {
colorStyles,
+ sizeByLevelStyles,
displayStyles,
truncationStyles,
wordBreakStyles,
@@ -47,7 +47,10 @@ const LazyXDSTooltip = lazy(() =>
*/
export type XDSHeadingLevel = 1 | 2 | 3 | 4 | 5 | 6;
-export interface XDSHeadingProps extends Omit<XDSBaseProps<HTMLHeadingElement>, 'children'> {
+export interface XDSHeadingProps extends Omit<
+ XDSBaseProps<HTMLHeadingElement>,
+ 'children'
+> {
/** Ref forwarded to the root element */
ref?: React.Ref<HTMLHeadingElement>;
/**
@@ -227,6 +230,7 @@ export function XDSHeading({
xdsClassName('heading', {level, color}),
stylex.props(
colorStyles[color],
+ sizeByLevelStyles[level],
// Display: use truncation styles when maxLines > 0
maxLines === 1
? truncationStyles.singleLine
diff --git a/packages/core/src/Text/XDSText.tsx b/packages/core/src/Text/XDSText.tsx
index 68fdba5f6d..2fef65b6e3 100644
--- a/packages/core/src/Text/XDSText.tsx
+++ b/packages/core/src/Text/XDSText.tsx
@@ -28,6 +28,7 @@ import type {
import {
colorStyles,
defaultWeightByTypeStyles,
+ sizeByTypeStyles,
weightStyles,
displayStyles,
truncationStyles,
@@ -243,6 +244,7 @@ export function XDSText({
xdsClassName('text', {type, color: resolvedColor}),
stylex.props(
colorStyles[resolvedColor],
+ sizeByTypeStyles[type],
defaultWeightByTypeStyles[type],
weight && weightStyles[weight],
// Display: use truncation styles when maxLines > 0
diff --git a/packages/core/src/Text/text.stylex.ts b/packages/core/src/Text/text.stylex.ts
index 617869edca..7c29f99ba2 100644
--- a/packages/core/src/Text/text.stylex.ts
+++ b/packages/core/src/Text/text.stylex.ts
@@ -9,7 +9,12 @@
*/
import * as stylex from '@stylexjs/stylex';
-import {colorVars, fontWeightVars, typeScaleVars} from '../theme/tokens.stylex';
+import {
+ colorVars,
+ fontWeightVars,
+ typeScaleVars,
+ typographyVars,
+} from '../theme/tokens.stylex';
// =============================================================================
// Color Styles
@@ -86,6 +91,90 @@ export const defaultWeightByTypeStyles = stylex.create({
},
});
+// =============================================================================
+// Baseline Size/Leading by Type (from type-scale tokens)
+//
+// These ensure XDSText renders with correct sizing even without a theme.
+// Theme component overrides (.xds-text.body { ... }) win when present
+// because they have higher specificity via @scope.
+// =============================================================================
+
+export const sizeByTypeStyles = stylex.create({
+ body: {
+ fontSize: typeScaleVars['--text-body-size'],
+ lineHeight: typeScaleVars['--text-body-leading'],
+ },
+ large: {
+ fontSize: typeScaleVars['--text-large-size'],
+ lineHeight: typeScaleVars['--text-large-leading'],
+ },
+ label: {
+ fontSize: typeScaleVars['--text-label-size'],
+ lineHeight: typeScaleVars['--text-label-leading'],
+ },
+ code: {
+ fontSize: typeScaleVars['--text-code-size'],
+ lineHeight: typeScaleVars['--text-code-leading'],
+ fontFamily: typographyVars['--font-family-code'],
+ },
+ supporting: {
+ fontSize: typeScaleVars['--text-supporting-size'],
+ lineHeight: typeScaleVars['--text-supporting-leading'],
+ },
+ 'display-1': {
+ fontSize: typeScaleVars['--text-display-1-size'],
+ lineHeight: typeScaleVars['--text-display-1-leading'],
+ },
+ 'display-2': {
+ fontSize: typeScaleVars['--text-display-2-size'],
+ lineHeight: typeScaleVars['--text-display-2-leading'],
+ },
+ 'display-3': {
+ fontSize: typeScaleVars['--text-display-3-size'],
+ lineHeight: typeScaleVars['--text-display-3-leading'],
+ },
+});
+
+// =============================================================================
+// Baseline Size/Leading by Heading Level (from type-scale tokens)
+//
+// Same rationale as sizeByTypeStyles — ensures XDSHeading renders
+// with correct sizing even without a theme.
+// =============================================================================
+
+export const sizeByLevelStyles = stylex.create({
+ 1: {
+ fontSize: typeScaleVars['--text-heading-1-size'],
+ lineHeight: typeScaleVars['--text-heading-1-leading'],
+ fontWeight: typeScaleVars['--text-heading-1-weight'],
+ },
+ 2: {
+ fontSize: typeScaleVars['--text-heading-2-size'],
+ lineHeight: typeScaleVars['--text-heading-2-leading'],
+ fontWeight: typeScaleVars['--text-heading-2-weight'],
+ },
+ 3: {
+ fontSize: typeScaleVars['--text-heading-3-size'],
+ lineHeight: typeScaleVars['--text-heading-3-leading'],
+ fontWeight: typeScaleVars['--text-heading-3-weight'],
+ },
+ 4: {
+ fontSize: typeScaleVars['--text-heading-4-size'],
+ lineHeight: typeScaleVars['--text-heading-4-leading'],
+ fontWeight: typeScaleVars['--text-heading-4-weight'],
+ },
+ 5: {
+ fontSize: typeScaleVars['--text-heading-5-size'],
+ lineHeight: typeScaleVars['--text-heading-5-leading'],
+ fontWeight: typeScaleVars['--text-heading-5-weight'],
+ },
+ 6: {
+ fontSize: typeScaleVars['--text-heading-6-size'],
+ lineHeight: typeScaleVars['--text-heading-6-leading'],
+ fontWeight: typeScaleVars['--text-heading-6-weight'],
+ },
+});
+
// =============================================================================
// Display Styles
// =============================================================================
diff --git a/packages/core/src/theme/defineTheme.test.ts b/packages/core/src/theme/defineTheme.test.ts
index f32f7437fb..5c113f7a73 100644
--- a/packages/core/src/theme/defineTheme.test.ts
+++ b/packages/core/src/theme/defineTheme.test.ts
@@ -1,4 +1,5 @@
import {describe, it, expect, vi} from 'vitest';
+import type {XDSIconRegistry} from '../Icon/globalIconRegistry';
import {
defineTheme,
generateThemeCSS,
@@ -77,8 +78,8 @@ describe('defineTheme', () => {
});
it('includes icons in the theme', () => {
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- const icons = {close: 'X'} as any;
+
+ const icons = {close: 'X'} as Partial<XDSIconRegistry>;
const theme = defineTheme({name: 'icons', icons});
expect(theme.icons).toBe(icons);
});
@@ -1045,3 +1046,142 @@ describe('container padding mapping', () => {
expect(css).toContain('--xds-card-padding-inline-end: 24px');
});
});
+
+describe('defineTheme extends', () => {
+ it('inherits tokens from base theme', () => {
+ const base = defineTheme({
+ name: 'base',
+ tokens: {
+ '--color-accent': '#0077B6',
+ '--radius-container': '16px',
+ },
+ });
+ const child = defineTheme({
+ name: 'child',
+ extends: base,
+ });
+ expect(child.tokens['--color-accent']).toBe('#0077B6');
+ expect(child.tokens['--radius-container']).toBe('16px');
+ });
+
+ it('overrides base tokens with explicit tokens', () => {
+ const base = defineTheme({
+ name: 'base',
+ tokens: {
+ '--color-accent': '#0077B6',
+ '--radius-container': '16px',
+ },
+ });
+ const child = defineTheme({
+ name: 'child',
+ extends: base,
+ tokens: {'--color-accent': '#FF0000'},
+ });
+ expect(child.tokens['--color-accent']).toBe('#FF0000');
+ expect(child.tokens['--radius-container']).toBe('16px');
+ });
+
+ it('inherits component overrides from base theme', () => {
+ const base = defineTheme({
+ name: 'base',
+ components: {
+ button: {
+ base: {fontWeight: '600'},
+ 'variant:secondary': {backgroundColor: 'rgba(0,0,0,0.06)'},
+ },
+ },
+ });
+ const child = defineTheme({
+ name: 'child',
+ extends: base,
+ });
+ expect(child.components?.button?.base).toEqual({fontWeight: '600'});
+ expect(child.components?.button?.['variant:secondary']).toEqual({
+ backgroundColor: 'rgba(0,0,0,0.06)',
+ });
+ });
+
+ it('merges component overrides — child wins', () => {
+ const base = defineTheme({
+ name: 'base',
+ components: {
+ button: {
+ base: {fontWeight: '600', borderRadius: '4px'},
+ },
+ },
+ });
+ const child = defineTheme({
+ name: 'child',
+ extends: base,
+ components: {
+ button: {
+ base: {fontWeight: '700'},
+ },
+ },
+ });
+ expect(child.components?.button?.base).toEqual({
+ fontWeight: '700',
+ borderRadius: '4px',
+ });
+ });
+
+ it('merges icons — child overrides base', () => {
+ const baseIcons = {close: 'X', menu: 'M'} as Partial<XDSIconRegistry>;
+ const childIcons = {close: 'Y'} as Partial<XDSIconRegistry>;
+ const base = defineTheme({name: 'base', icons: baseIcons});
+ const child = defineTheme({
+ name: 'child',
+ extends: base,
+ icons: childIcons,
+ });
+ expect(child.icons?.close).toBe('Y');
+ expect(child.icons?.menu).toBe('M');
+ });
+
+ it('inherits icons when child has none', () => {
+ const baseIcons = {close: 'X'} as Partial<XDSIconRegistry>;
+ const base = defineTheme({name: 'base', icons: baseIcons});
+ const child = defineTheme({name: 'child', extends: base});
+ expect(child.icons?.close).toBe('X');
+ });
+
+ it('uses child name, not base name', () => {
+ const base = defineTheme({name: 'base'});
+ const child = defineTheme({name: 'my-brand', extends: base});
+ expect(child.name).toBe('my-brand');
+ });
+
+ it('inherits fonts from base theme', () => {
+ const base = defineTheme({
+ name: 'base',
+ typography: {
+ body: {
+ family: 'Geist',
+ fallbacks: 'sans-serif',
+ url: 'https://fonts.example.com/geist.css',
+ },
+ scale: {base: 14, ratio: 1.2},
+ },
+ });
+ const child = defineTheme({name: 'child', extends: base});
+ expect(child.fonts).toEqual([
+ {family: 'Geist', url: 'https://fonts.example.com/geist.css'},
+ ]);
+ });
+
+ it('typography in child overrides base typography tokens', () => {
+ const base = defineTheme({
+ name: 'base',
+ typography: {scale: {base: 14, ratio: 1.2}},
+ });
+ const child = defineTheme({
+ name: 'child',
+ extends: base,
+ typography: {scale: {base: 16, ratio: 1.25}},
+ });
+ // Child's type scale tokens should differ from base
+ expect(child.tokens['--font-size-base']).not.toBe(
+ base.tokens['--font-size-base'],
+ );
+ });
+});
diff --git a/packages/core/src/theme/defineTheme.ts b/packages/core/src/theme/defineTheme.ts
index 00cc0466c6..5b12fd50d0 100644
--- a/packages/core/src/theme/defineTheme.ts
+++ b/packages/core/src/theme/defineTheme.ts
@@ -162,6 +162,28 @@ export type XDSComponentStyleMap = Record<
export interface XDSDefineThemeInput {
/** Theme name — used for data-xds-theme attribute and identification */
name: string;
+
+ /**
+ * Base theme to extend. When provided, the new theme starts with the
+ * base theme's tokens, components, and fonts, then applies overrides
+ * from this input on top. The base theme's values have lowest precedence.
+ *
+ * Use this to create variant themes that customize only a few aspects
+ * (e.g. icons, accent color) without re-specifying the full theme.
+ *
+ * @example
+ * ```tsx
+ * import {defaultTheme} from '@xds/theme-default';
+ *
+ * const myTheme = defineTheme({
+ * name: 'my-brand',
+ * extends: defaultTheme,
+ * icons: myIcons,
+ * tokens: { '--color-accent': '#FF0000' },
+ * });
+ * ```
+ */
+ extends?: XDSDefinedTheme;
/**
* Unified typography configuration — fonts, scale, and weights.
*
@@ -452,6 +474,14 @@ function buildFontFamily(
export function defineTheme(input: XDSDefineThemeInput): XDSDefinedTheme {
const tokens: Record<string, string> = {};
+ // 0. Pre-seed from base theme when `extends` is provided (lowest precedence)
+ const base = input.extends;
+ if (base) {
+ for (const [key, value] of Object.entries(base.tokens)) {
+ tokens[key] = value;
+ }
+ }
+
// Build typeScale config from typography if present
const typo = input.typography;
let typeScaleConfig: XDSTypeScaleConfig | undefined;
@@ -561,12 +591,15 @@ export function defineTheme(input: XDSDefineThemeInput): XDSDefinedTheme {
}
}
- // 3. Generate component overrides: typeScale-generated (lowest) + explicit (highest)
+ // 3. Generate component overrides: base (lowest) → typeScale → explicit (highest)
let components = input.components;
if (typeScaleConfig) {
const generated = generateTypeScaleComponents(typeScaleConfig);
components = deepMergeComponents(generated, input.components);
}
+ if (base?.components) {
+ components = deepMergeComponents(base.components, components);
+ }
// 4. Derive fonts array from typography roles (for runtime loading)
let fonts: ThemeFontSource[] | undefined;
@@ -588,12 +621,31 @@ export function defineTheme(input: XDSDefineThemeInput): XDSDefinedTheme {
const __onDark = resolveOnMedia('dark', input.onDark);
const __onLight = resolveOnMedia('light', input.onLight);
+ // 6. Merge icons — input icons override base icons
+ const icons =
+ input.icons && base?.icons
+ ? {...base.icons, ...input.icons}
+ : input.icons ?? base?.icons;
+
+ // 7. Merge fonts — input fonts take priority, deduplicate by family
+ let mergedFonts = fonts;
+ if (!mergedFonts && base?.fonts) {
+ mergedFonts = base.fonts;
+ } else if (mergedFonts && base?.fonts) {
+ const seen = new Set(mergedFonts.map(f => f.family));
+ for (const font of base.fonts) {
+ if (!seen.has(font.family)) {
+ mergedFonts.push(font);
+ }
+ }
+ }
+
return {
name: input.name,
tokens,
components,
- icons: input.icons,
- fonts,
+ icons,
+ fonts: mergedFonts,
__inputTokens: input.tokens,
__onDark,
__onLight,