An open source design system that's fully customizable and agent ready
TypeScript
feat(theme): derived var expansion — CSS properties to internal vars (#1467)
Cindy Zhang53c3ac76ec34
diff --git a/packages/core/src/Banner/Banner.doc.mjs b/packages/core/src/Banner/Banner.doc.mjsindex 4a996e84c3..86603e4d99 100644--- a/packages/core/src/Banner/Banner.doc.mjs+++ b/packages/core/src/Banner/Banner.doc.mjs@@ -93,6 +93,9 @@ export const docs = {vars: [{name: '--banner-radius', description: 'Border radius (card container only)', default: 'var(--radius-container)'},],+ derived: [+ {property: 'borderRadius', description: 'Border radius of the banner', default: 'var(--radius-container)', vars: ['--banner-radius']},+ ],},};@@ -154,6 +157,9 @@ export const docsZh = {vars: [{name: '--banner-radius', description: 'Border radius (card container only)', default: 'var(--radius-container)'},],+ derived: [+ {property: 'borderRadius', description: 'Border radius of the banner', default: 'var(--radius-container)', vars: ['--banner-radius']},+ ],},};diff --git a/packages/core/src/Button/Button.doc.mjs b/packages/core/src/Button/Button.doc.mjsindex dce62b231e..975b198d9b 100644--- a/packages/core/src/Button/Button.doc.mjs+++ b/packages/core/src/Button/Button.doc.mjs@@ -129,6 +129,9 @@ export const docs = {{name: '--button-focus-offset', description: 'Focus ring outline offset', default: '3px'},{name: '--button-icon-only-aspect', description: 'Aspect ratio for icon-only buttons', default: '1 / 1'},],+ derived: [+ {property: 'borderRadius', description: 'Border radius of buttons', default: 'var(--radius-element)', vars: ['--button-radius']},+ ],},};@@ -204,6 +207,9 @@ export const docsZh = {{name: '--button-focus-offset', description: '焦点环轮廓偏移', default: '3px'},{name: '--button-icon-only-aspect', description: '纯图标按钮的宽高比', default: '1 / 1'},],+ derived: [+ {property: 'borderRadius', description: 'Border radius of buttons', default: 'var(--radius-element)', vars: ['--button-radius']},+ ],},};diff --git a/packages/core/src/Card/Card.doc.mjs b/packages/core/src/Card/Card.doc.mjsindex d1b5608d14..0142be15a8 100644--- a/packages/core/src/Card/Card.doc.mjs+++ b/packages/core/src/Card/Card.doc.mjs@@ -73,6 +73,10 @@ export const docs = {default: 'var(--spacing-4)',},],+ derived: [+ {property: 'borderRadius', description: 'Border radius of the card', default: 'var(--radius-container)', vars: ['--card-radius']},+ {property: 'padding', description: 'Container padding of the card', default: 'var(--spacing-4)', expand: 'container'},+ ],},};@@ -117,6 +121,10 @@ export const docsZh = {default: 'var(--spacing-4)',},],+ derived: [+ {property: 'borderRadius', description: 'Border radius of the card', default: 'var(--radius-container)', vars: ['--card-radius']},+ {property: 'padding', description: 'Container padding of the card', default: 'var(--spacing-4)', expand: 'container'},+ ],},};diff --git a/packages/core/src/Chat/Chat.doc.mjs b/packages/core/src/Chat/Chat.doc.mjsindex 3f704a4378..483fef5e63 100644--- a/packages/core/src/Chat/Chat.doc.mjs+++ b/packages/core/src/Chat/Chat.doc.mjs@@ -24,6 +24,10 @@ export const docs = {{name: '--composer-padding', description: 'Padding of the composer body. Used in the concentric radius calculation.', default: 'var(--spacing-3)'},{name: '--button-radius', description: 'Concentric button radius inside the composer.', default: 'max(var(--radius-element), calc(var(--composer-radius) - var(--composer-padding)))', derived: true, formula: 'max(var(--radius-element), calc(var(--composer-radius) - var(--composer-padding)))'},],+ derived: [+ {property: 'borderRadius', description: 'Border radius of the composer. Inner elements derive their radius concentrically.', default: 'var(--radius-page)', vars: ['--composer-radius']},+ {property: 'padding', description: 'Padding of the composer. Used in the concentric radius calculation.', default: 'var(--spacing-3)', vars: ['--composer-padding']},+ ],},components: [{diff --git a/packages/core/src/Dialog/Dialog.doc.mjs b/packages/core/src/Dialog/Dialog.doc.mjsindex 98dfe20a91..0564c047a2 100644--- a/packages/core/src/Dialog/Dialog.doc.mjs+++ b/packages/core/src/Dialog/Dialog.doc.mjs@@ -19,6 +19,10 @@ export const docs = {default: 'var(--spacing-4)',},],+ derived: [+ {property: 'borderRadius', description: 'Border radius of the dialog', default: 'var(--radius-container)', vars: ['--dialog-radius']},+ {property: 'padding', description: 'Container padding of the dialog', default: 'var(--spacing-4)', expand: 'container'},+ ],},components: [{@@ -155,6 +159,10 @@ export const docsZh = {default: 'var(--spacing-4)',},],+ derived: [+ {property: 'borderRadius', description: 'Border radius of the dialog', default: 'var(--radius-container)', vars: ['--dialog-radius']},+ {property: 'padding', description: 'Container padding of the dialog', default: 'var(--spacing-4)', expand: 'container'},+ ],},components: [{diff --git a/packages/core/src/DropdownMenu/DropdownMenu.doc.mjs b/packages/core/src/DropdownMenu/DropdownMenu.doc.mjsindex 3ef8af5b08..3116e64ea4 100644--- a/packages/core/src/DropdownMenu/DropdownMenu.doc.mjs+++ b/packages/core/src/DropdownMenu/DropdownMenu.doc.mjs@@ -12,6 +12,10 @@ export const docs = {{name: '--dropdown-radius', description: 'Border radius of the menu popup', default: 'var(--radius-element)'},{name: '--dropdown-padding', description: 'Inner padding of the menu popup', default: 'var(--spacing-1)'},],+ derived: [+ {property: 'borderRadius', description: 'Border radius of the menu popup', default: 'var(--radius-element)', vars: ['--dropdown-radius']},+ {property: 'padding', description: 'Inner padding of the menu popup', default: 'var(--spacing-1)', vars: ['--dropdown-padding']},+ ],},components: [{@@ -193,6 +197,10 @@ export const docsZh = {{name: '--dropdown-radius', description: 'Border radius of the menu popup', default: 'var(--radius-element)'},{name: '--dropdown-padding', description: 'Inner padding of the menu popup', default: 'var(--spacing-1)'},],+ derived: [+ {property: 'borderRadius', description: 'Border radius of the menu popup', default: 'var(--radius-element)', vars: ['--dropdown-radius']},+ {property: 'padding', description: 'Inner padding of the menu popup', default: 'var(--spacing-1)', vars: ['--dropdown-padding']},+ ],},components: [{diff --git a/packages/core/src/Field/Field.doc.mjs b/packages/core/src/Field/Field.doc.mjsindex 925af102dd..a23d6363c9 100644--- a/packages/core/src/Field/Field.doc.mjs+++ b/packages/core/src/Field/Field.doc.mjs@@ -12,6 +12,9 @@ export const docs = {vars: [{name: '--input-radius', description: 'Border radius of input fields', default: 'var(--radius-element)'},],+ derived: [+ {property: 'borderRadius', description: 'Border radius of input fields', default: 'var(--radius-element)', vars: ['--input-radius']},+ ],},components: [{@@ -235,6 +238,9 @@ export const docsZh = {vars: [{name: '--input-radius', description: 'Border radius of input fields', default: 'var(--radius-element)'},],+ derived: [+ {property: 'borderRadius', description: 'Border radius of input fields', default: 'var(--radius-element)', vars: ['--input-radius']},+ ],},components: [{diff --git a/packages/core/src/HoverCard/HoverCard.doc.mjs b/packages/core/src/HoverCard/HoverCard.doc.mjsindex 8a55f454c9..bd24f0baa6 100644--- a/packages/core/src/HoverCard/HoverCard.doc.mjs+++ b/packages/core/src/HoverCard/HoverCard.doc.mjs@@ -10,6 +10,9 @@ export const docs = {vars: [{name: '--hovercard-radius', description: 'Border radius of the hover card', default: 'var(--radius-container)'},],+ derived: [+ {property: 'borderRadius', description: 'Border radius of the hover card', default: 'var(--radius-container)', vars: ['--hovercard-radius']},+ ],},components: [{@@ -157,6 +160,9 @@ export const docsZh = {vars: [{name: '--hovercard-radius', description: 'Border radius of the hover card', default: 'var(--radius-container)'},],+ derived: [+ {property: 'borderRadius', description: 'Border radius of the hover card', default: 'var(--radius-container)', vars: ['--hovercard-radius']},+ ],},components: [{diff --git a/packages/core/src/Popover/Popover.doc.mjs b/packages/core/src/Popover/Popover.doc.mjsindex 9c84661238..8fd35fdd36 100644--- a/packages/core/src/Popover/Popover.doc.mjs+++ b/packages/core/src/Popover/Popover.doc.mjs@@ -138,6 +138,9 @@ export const docs = {vars: [{name: '--popover-radius', description: 'Border radius of the popover', default: 'var(--radius-element)'},],+ derived: [+ {property: 'borderRadius', description: 'Border radius of the popover', default: 'var(--radius-element)', vars: ['--popover-radius']},+ ],},usage: {description:@@ -290,6 +293,9 @@ export const docsZh = {vars: [{name: '--popover-radius', description: 'Border radius of the popover', default: 'var(--radius-element)'},],+ derived: [+ {property: 'borderRadius', description: 'Border radius of the popover', default: 'var(--radius-element)', vars: ['--popover-radius']},+ ],},usage: {description:diff --git a/packages/core/src/Section/Section.doc.mjs b/packages/core/src/Section/Section.doc.mjsindex 9d353bc6eb..0b71a2858f 100644--- a/packages/core/src/Section/Section.doc.mjs+++ b/packages/core/src/Section/Section.doc.mjs@@ -67,6 +67,9 @@ export const docs = {default: 'var(--spacing-4)',},],+ derived: [+ {property: 'padding', description: 'Container padding of the section', default: 'var(--spacing-4)', expand: 'container'},+ ],},usage: {description:@@ -146,6 +149,9 @@ export const docsZh = {default: 'var(--spacing-4)',},],+ derived: [+ {property: 'padding', description: 'Container padding of the section', default: 'var(--spacing-4)', expand: 'container'},+ ],},usage: {description:diff --git a/packages/core/src/SegmentedControl/SegmentedControl.doc.mjs b/packages/core/src/SegmentedControl/SegmentedControl.doc.mjsindex 6d85d0f290..5c905e0882 100644--- a/packages/core/src/SegmentedControl/SegmentedControl.doc.mjs+++ b/packages/core/src/SegmentedControl/SegmentedControl.doc.mjs@@ -8,6 +8,14 @@ export const docs = {{className: 'xds-segmented-control', visualProps: ['size']},{className: 'xds-segmented-control-item'},],+ vars: [+ {name: '--segmented-radius', description: 'Border radius of the segmented control', default: 'var(--radius-element)'},+ {name: '--segmented-padding', description: 'Inner padding of the segmented control', default: 'var(--spacing-0-5)'},+ ],+ derived: [+ {property: 'borderRadius', description: 'Border radius of the segmented control', default: 'var(--radius-element)', vars: ['--segmented-radius']},+ {property: 'padding', description: 'Inner padding of the segmented control', default: 'var(--spacing-0-5)', vars: ['--segmented-padding']},+ ],},components: [{diff --git a/packages/core/src/docs-types.ts b/packages/core/src/docs-types.tsindex 85fc10ac53..1b03492213 100644--- a/packages/core/src/docs-types.ts+++ b/packages/core/src/docs-types.ts@@ -95,6 +95,52 @@ export interface CSSPropertyDoc {default?: string;}+/**+ * Maps a standard CSS property to one or more internal CSS custom properties.+ *+ * Theme authors write standard CSS (e.g. `borderRadius: '32px'`). The theme+ * pipeline reads this metadata and expands it: emitting both the CSS property+ * AND the internal var(s) that the component reads.+ *+ * Entries are ordered by priority — earlier entries are emitted first.+ * When multiple entries share the same `property`, all fire (in order).+ *+ * The special `expand: 'container'` triggers the 7-token container padding+ * expansion instead of setting a specific var.+ *+ * @example+ * ```+ * // Simple: borderRadius → one internal var+ * { property: 'borderRadius', vars: ['--_card-radius'] }+ *+ * // Container expansion: padding → 7 container tokens+ * { property: 'padding', expand: 'container' }+ *+ * // Multiple vars from one property+ * { property: 'padding', vars: ['--_composer-padding', '--_composer-button-offset'] }+ *+ * // Multiple entries for the same property (both fire, in order)+ * { property: 'padding', expand: 'container' },+ * { property: 'padding', vars: ['--_card-padding'] },+ * ```+ */+export interface DerivedVar {+ /** The standard CSS property name (camelCase) that theme authors write.+ * e.g. `'borderRadius'`, `'padding'`, `'paddingBlock'` */+ property: string;+ /** What this derived mapping controls, in 1-2 sentences. */+ description?: string;+ /** Default value as a CSS expression if not set by theme.+ * e.g. `'var(--radius-container)'`, `'var(--spacing-4)'` */+ default?: string;+ /** Internal CSS custom property names to set when this property appears+ * in a theme's component overrides. Omit when using `expand`. */+ vars?: string[];+ /** Named expansion strategy instead of specific vars.+ * `'container'` — expands padding to 7 container layout tokens. */+ expand?: 'container';+}+/*** Documents a CSS custom property exposed by a component for theming.* These vars are set on the component's root element and can be overridden@@ -256,6 +302,12 @@ interface BaseDoc {* via component overrides. Only document supported public properties —* internal variables must not be listed here. */cssProperties?: CSSPropertyDoc[];+ /** Maps standard CSS properties to internal vars for theme pipeline+ * expansion. Ordered by priority — earlier entries emit first.+ * The pipeline reads this to know: when a theme sets `borderRadius`+ * on this component, also emit `--_card-radius`.+ * @see DerivedVar */+ derived?: DerivedVar[];};/** Component usage documentation — concise summary, best practices,* and optional visual anatomy. */diff --git a/packages/core/src/theme/defineTheme.ts b/packages/core/src/theme/defineTheme.tsindex 8b9ddfa6af..4335fad9dd 100644--- a/packages/core/src/theme/defineTheme.ts+++ b/packages/core/src/theme/defineTheme.ts@@ -36,6 +36,7 @@ import {type ResolvedOnMedia,} from './onMediaTokens';import {parseStyleKey} from '../utils/parseStyleKey';+import {getDerivedVars} from './derivedVarRegistry';import {colorDefaults,spacingDefaults,@@ -825,7 +826,9 @@ export function generateThemeRules(theme: XDSDefinedTheme): string[] {}// Container padding mapping: intercept padding on container- // components and emit container token declarations instead+ // components and emit container token declarations instead.+ // Also expand derived vars: when a theme sets a standard CSS+ // property (e.g. borderRadius), emit the internal vars too.let finalProps = props;if (CONTAINER_COMPONENTS.has(component)) {const paddingProps = props.filter(([p]) => PADDING_PROPS.has(p));@@ -839,6 +842,26 @@ export function generateThemeRules(theme: XDSDefinedTheme): string[] {}}+ // Derived var expansion: for each CSS property, check if the+ // component has derived var entries and emit additional declarations.+ // Entries are processed in order (priority).+ const derivedProps: [string, string][] = [];+ for (const [prop, value] of finalProps) {+ const derived = getDerivedVars(component, prop);+ for (const entry of derived) {+ if (entry.vars) {+ for (const varName of entry.vars) {+ derivedProps.push([varName, value]);+ }+ }+ // 'container' expansion is already handled above via+ // CONTAINER_COMPONENTS — no double-emit needed here+ }+ }+ if (derivedProps.length > 0) {+ finalProps = [...finalProps, ...derivedProps];+ }+// Emit base ruleif (finalProps.length > 0) {const declarations = finalPropsdiff --git a/packages/core/src/theme/derivedVarRegistry.test.ts b/packages/core/src/theme/derivedVarRegistry.test.tsnew file mode 100644index 0000000000..181faee42b--- /dev/null+++ b/packages/core/src/theme/derivedVarRegistry.test.ts@@ -0,0 +1,280 @@+/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-require-imports */+/**+ * @file Validates derivedVarRegistry stays in sync with component doc files,+ * AND detects undocumented component CSS custom properties in source files.+ *+ * Three layers of checking:+ * 1. Source scan: finds all component-level CSS vars in .tsx files+ * 2. Doc check: verifies each var is documented in the doc file's vars[]+ * 3. Registry check: verifies themeable vars have derived[] entries that+ * match the registry+ */++import {describe, it, expect} from 'vitest';+import {derivedVarRegistry, getDerivedVars} from './derivedVarRegistry';+import {readdirSync, readFileSync, existsSync} from 'fs';+import {join} from 'path';++const SRC_DIR = join(__dirname, '..');++// ---------------------------------------------------------------------------+// Source scanning: find CSS custom property declarations in component files+// ---------------------------------------------------------------------------++/**+ * Structural/runtime vars that are NOT component-specific theming vars.+ * These are set by JS at runtime or cascade through layout — they don't+ * belong in derived[] because they aren't things theme authors write.+ */+const STRUCTURAL_VARS = new Set([+ '--container-padding',+ '--container-padding-inline',+ '--container-padding-inline-start',+ '--container-padding-inline-end',+ '--container-padding-block-start',+ '--container-padding-block-end',+ '--container-max-height',+ '--layout-padding-inner-x',+ '--layout-padding-inner-y',+ '--layout-padding-outer-x',+ '--layout-padding-outer-y',+ '--layout-content-width',+ '--edge-start',+ '--edge-end',+ '--component-padding-inline',+ '--appshell-header-height',+ '--dialog-dir-x',+ '--dialog-dir-y',+ '--indicator-color',+ '--indicator-width',+ '--table-resize-height',+ '--separator-display',+]);++/**+ * Extract component-specific CSS custom property names from a source file.+ * Matches patterns like '--card-radius': or '--composer-padding':+ * Excludes structural/runtime vars and standard token vars (--color-*, --spacing-*, etc.).+ */+function extractComponentVars(filePath: string): string[] {+ const content = readFileSync(filePath, 'utf-8');+ const varPattern = /['"](--(\w[\w-]*))['"]\s*:/g;+ const vars = new Set<string>();+ let match;++ while ((match = varPattern.exec(content)) !== null) {+ const varName = match[1];+ // Skip token vars (--color-*, --spacing-*, --radius-*, etc.)+ if (/^--(color|spacing|radius|shadow|duration|ease|transition|font|text|size)-/.test(varName)) continue;+ // Skip structural vars+ if (STRUCTURAL_VARS.has(varName)) continue;+ // Skip vars that start with structural prefixes+ if (/^--(container-|layout-|edge-|component-)/.test(varName)) continue;+ vars.add(varName);+ }+ return [...vars];+}++// ---------------------------------------------------------------------------+// Discovery: scan all component directories+// ---------------------------------------------------------------------------++interface ComponentInfo {+ dir: string;+ sourceVars: string[];+ docVars: string[];+ docDerived: Array<{property: string; vars?: string[]; expand?: string}>;+}++function discoverComponents(): ComponentInfo[] {+ const results: ComponentInfo[] = [];+ const dirs = readdirSync(SRC_DIR, {withFileTypes: true})+ .filter(d => d.isDirectory())+ .map(d => d.name);++ for (const dir of dirs) {+ const dirPath = join(SRC_DIR, dir);+ // Find source files with component vars (.tsx and .ts, excluding tests/docs)+ const sourceFiles = readdirSync(dirPath)+ .filter(f => (f.endsWith('.tsx') || f.endsWith('.ts')) && !f.includes('.test.') && !f.endsWith('.doc.mjs') && !f.endsWith('.d.ts'))+ .map(f => join(dirPath, f));++ const allVars = new Set<string>();+ for (const f of sourceFiles) {+ for (const v of extractComponentVars(f)) {+ allVars.add(v);+ }+ }+ if (allVars.size === 0) continue;++ // Only check component directories (those with a doc file)+ const docPath = join(dirPath, `${dir}.doc.mjs`);+ if (!existsSync(docPath)) continue;++ let docVars: string[] = [];+ let docDerived: any[] = [];+ try {+ const mod = require(docPath);+ docVars = (mod.docs?.theming?.vars || []).map((v: any) => v.name);+ docDerived = mod.docs?.theming?.derived || [];+ } catch { /* skip */ }++ results.push({+ dir,+ sourceVars: [...allVars],+ docVars,+ docDerived,+ });+ }+ return results;+}++// ---------------------------------------------------------------------------+// Known mapping: doc dir → registry key+// ---------------------------------------------------------------------------++const DIR_TO_REGISTRY_KEY: Record<string, string> = {+ Banner: 'banner',+ Button: 'button',+ Card: 'card',+ Chat: 'chat',+ Dialog: 'dialog',+ DropdownMenu: 'dropdown-menu',+ Field: 'field',+ HoverCard: 'hovercard',+ Popover: 'popover',+ Section: 'section',+ SegmentedControl: 'segmented-control',+};++/**+ * Vars that are intentionally set by one component for use by another+ * (cross-component vars). These are documented in the *consuming* component's+ * doc, not the *setting* component's doc.+ *+ * e.g. Carousel and Thumbnail set --button-radius for their child Buttons,+ * but --button-radius is documented in Button's doc.+ */+const CROSS_COMPONENT_VARS: Record<string, string[]> = {+ Carousel: ['--button-radius'],+ Thumbnail: ['--button-radius'],+ Chat: ['--button-radius'],+};++// ---------------------------------------------------------------------------+// Tests+// ---------------------------------------------------------------------------++describe('component CSS vars are documented and themeable', () => {+ const components = discoverComponents();++ for (const {dir, sourceVars, docVars, docDerived} of components) {+ const crossVars = new Set(CROSS_COMPONENT_VARS[dir] || []);++ it(`${dir}: all source vars are in doc file`, () => {+ const undocumented = sourceVars.filter(+ v => !docVars.includes(v) && !crossVars.has(v),+ );+ expect(+ undocumented,+ `${dir} has undocumented CSS vars in source: ${undocumented.join(', ')}. ` ++ `Add them to ${dir}.doc.mjs theming.vars[] and add a derived[] ` ++ `entry mapping the standard CSS property to the internal var.`,+ ).toEqual([]);+ });++ it(`${dir}: documented vars have derived entries for theming`, () => {+ // Every var that maps to a standard CSS property should have a+ // derived entry so theme authors can write standard CSS.+ const derivedVarNames = new Set(+ docDerived.flatMap((d: any) => d.vars || []),+ );+ const derivedExpands = docDerived+ .filter((d: any) => d.expand)+ .map((d: any) => d.expand);+ const hasContainerExpand = derivedExpands.includes('container');++ const missingDerived = docVars.filter(varName => {+ // Cross-component vars are handled by the owning component+ if (crossVars.has(varName)) return false;+ // Check if this var is covered by a derived entry+ if (derivedVarNames.has(varName)) return false;+ // Container expansion covers padding-related vars+ if (hasContainerExpand && varName.includes('padding')) return false;+ return true;+ });++ // Filter to only vars that look like they map to CSS properties+ // (radius → borderRadius, padding → padding). Vars like+ // --button-press-scale or --button-disabled-opacity are+ // component-specific behaviors, not standard CSS property mappings.+ const themeableVars = missingDerived.filter(v =>+ /radius|padding/.test(v),+ );++ expect(+ themeableVars,+ `${dir} has vars that should be themeable via derived[]: ${themeableVars.join(', ')}. ` ++ `Add derived[] entries in ${dir}.doc.mjs mapping standard CSS ` ++ `properties (borderRadius, padding) to these internal vars.`,+ ).toEqual([]);+ });+ }+});++describe('derivedVarRegistry ↔ doc file consistency', () => {+ const components = discoverComponents();++ for (const {dir, docDerived} of components) {+ const key = DIR_TO_REGISTRY_KEY[dir];+ if (!key || docDerived.length === 0) continue;++ it(`${dir} (${key}): registry matches doc derived`, () => {+ const registryEntries = derivedVarRegistry[key];+ expect(registryEntries).toBeDefined();+ expect(registryEntries).toEqual(docDerived);+ });+ }++ // Catch new doc files with derived that have no registry key mapping+ it('every doc with theming.derived has a registry mapping', () => {+ const missing: string[] = [];+ for (const {dir, docDerived} of components) {+ if (docDerived.length === 0) continue;+ const key = DIR_TO_REGISTRY_KEY[dir];+ if (!key) {+ missing.push(+ `${dir}: has theming.derived but no DIR_TO_REGISTRY_KEY mapping. ` ++ `Add the mapping and a derivedVarRegistry entry.`,+ );+ } else if (!derivedVarRegistry[key]) {+ missing.push(+ `${dir} (${key}): has theming.derived but no derivedVarRegistry entry.`,+ );+ }+ }+ expect(missing).toEqual([]);+ });++ it('registry has no orphan entries', () => {+ const validKeys = new Set(Object.values(DIR_TO_REGISTRY_KEY));+ const orphans = Object.keys(derivedVarRegistry).filter(k => !validKeys.has(k));+ expect(orphans).toEqual([]);+ });+});++describe('getDerivedVars', () => {+ it('returns matching entries for card borderRadius', () => {+ const result = getDerivedVars('card', 'borderRadius');+ expect(result).toHaveLength(1);+ expect(result[0].vars).toEqual(['--card-radius']);+ });++ it('returns empty for unknown component', () => {+ expect(getDerivedVars('unknown', 'borderRadius')).toEqual([]);+ });++ it('returns empty for unregistered property', () => {+ expect(getDerivedVars('card', 'color')).toEqual([]);+ });+});diff --git a/packages/core/src/theme/derivedVarRegistry.ts b/packages/core/src/theme/derivedVarRegistry.tsnew file mode 100644index 0000000000..99568b44fd--- /dev/null+++ b/packages/core/src/theme/derivedVarRegistry.ts@@ -0,0 +1,91 @@+/**+ * @file Derived variable registry — maps CSS properties to internal vars.+ *+ * Used by generateThemeRules to expand standard CSS properties (borderRadius,+ * padding) into internal CSS custom properties that components read.+ *+ * This is a compiled registry — the source of truth lives in each component's+ * doc file (theming.derived). The consistency test in derivedVarRegistry.test.ts+ * verifies this file stays in sync with the docs.+ *+ * When adding a new component with derived vars:+ * 1. Add the `derived` field to the component's doc.mjs file+ * 2. Add the corresponding entry here+ * 3. The consistency test will catch any drift+ *+ * @position Core theme infrastructure — read by generateThemeRules at runtime+ */++export interface DerivedVarEntry {+ /** The standard CSS property name (camelCase) that theme authors write. */+ property: string;+ /** What this derived mapping controls. */+ description?: string;+ /** Default value as a CSS expression. */+ default?: string;+ /** Internal CSS custom property names to set. Omit when using `expand`. */+ vars?: string[];+ /** Named expansion strategy. 'container' expands padding to container tokens. */+ expand?: 'container';+}++/**+ * Component → derived var mappings.+ *+ * Keys are lowercase component names (matching defineTheme component keys).+ * Values are ordered arrays — earlier entries emit first when multiple+ * entries share the same property.+ */+export const derivedVarRegistry: Record<string, DerivedVarEntry[]> = {+ banner: [+ {property: 'borderRadius', description: 'Border radius of the banner', default: 'var(--radius-container)', vars: ['--banner-radius']},+ ],+ button: [+ {property: 'borderRadius', description: 'Border radius of buttons', default: 'var(--radius-element)', vars: ['--button-radius']},+ ],+ card: [+ {property: 'borderRadius', description: 'Border radius of the card', default: 'var(--radius-container)', vars: ['--card-radius']},+ {property: 'padding', description: 'Container padding of the card', default: 'var(--spacing-4)', expand: 'container'},+ ],+ chat: [+ {property: 'borderRadius', description: 'Border radius of the composer. Inner elements derive their radius concentrically.', default: 'var(--radius-page)', vars: ['--composer-radius']},+ {property: 'padding', description: 'Padding of the composer. Used in the concentric radius calculation.', default: 'var(--spacing-3)', vars: ['--composer-padding']},+ ],+ dialog: [+ {property: 'borderRadius', description: 'Border radius of the dialog', default: 'var(--radius-container)', vars: ['--dialog-radius']},+ {property: 'padding', description: 'Container padding of the dialog', default: 'var(--spacing-4)', expand: 'container'},+ ],+ 'dropdown-menu': [+ {property: 'borderRadius', description: 'Border radius of the menu popup', default: 'var(--radius-element)', vars: ['--dropdown-radius']},+ {property: 'padding', description: 'Inner padding of the menu popup', default: 'var(--spacing-1)', vars: ['--dropdown-padding']},+ ],+ field: [+ {property: 'borderRadius', description: 'Border radius of input fields', default: 'var(--radius-element)', vars: ['--input-radius']},+ ],+ hovercard: [+ {property: 'borderRadius', description: 'Border radius of the hover card', default: 'var(--radius-container)', vars: ['--hovercard-radius']},+ ],+ popover: [+ {property: 'borderRadius', description: 'Border radius of the popover', default: 'var(--radius-element)', vars: ['--popover-radius']},+ ],+ section: [+ {property: 'padding', description: 'Container padding of the section', default: 'var(--spacing-4)', expand: 'container'},+ ],+ 'segmented-control': [+ {property: 'borderRadius', description: 'Border radius of the segmented control', default: 'var(--radius-element)', vars: ['--segmented-radius']},+ {property: 'padding', description: 'Inner padding of the segmented control', default: 'var(--spacing-0-5)', vars: ['--segmented-padding']},+ ],+};++/**+ * Look up derived var entries for a component + CSS property.+ * Returns matching entries in priority order, or empty array if none.+ */+export function getDerivedVars(+ component: string,+ property: string,+): DerivedVarEntry[] {+ const entries = derivedVarRegistry[component];+ if (!entries) return [];+ return entries.filter(e => e.property === property);+}diff --git a/packages/core/src/theme/generateThemeRules.test.ts b/packages/core/src/theme/generateThemeRules.test.tsindex 1ac3be51cc..fb6ce8371d 100644--- a/packages/core/src/theme/generateThemeRules.test.ts+++ b/packages/core/src/theme/generateThemeRules.test.ts@@ -204,3 +204,189 @@ describe('generateThemeRules with weight overrides', () => {expect(h3Rule).toContain('var(--font-weight-bold)');});});+++// =============================================================================+// Derived var expansion+// =============================================================================++describe('derived var expansion', () => {+ it('emits borderRadius AND internal var for card', () => {+ const theme = defineTheme({+ name: 'test-derived',+ components: {+ card: {+ base: {borderRadius: '32px'},+ },+ },+ });+ const rules = generateThemeRules(theme);+ const cardRule = rules.find(r => r.includes('.xds-card'));+ expect(cardRule).toBeDefined();+ expect(cardRule).toContain('border-radius: 32px');+ expect(cardRule).toContain('--card-radius: 32px');+ });++ it('emits borderRadius AND internal var for dropdown-menu', () => {+ const theme = defineTheme({+ name: 'test-derived-dropdown',+ components: {+ 'dropdown-menu': {+ base: {borderRadius: '16px'},+ },+ },+ });+ const rules = generateThemeRules(theme);+ const rule = rules.find(r => r.includes('.xds-dropdown-menu'));+ expect(rule).toBeDefined();+ expect(rule).toContain('border-radius: 16px');+ expect(rule).toContain('--dropdown-radius: 16px');+ });++ it('emits padding AND internal var for dropdown-menu', () => {+ const theme = defineTheme({+ name: 'test-derived-dropdown-pad',+ components: {+ 'dropdown-menu': {+ base: {padding: '8px'},+ },+ },+ });+ const rules = generateThemeRules(theme);+ const rule = rules.find(r => r.includes('.xds-dropdown-menu'));+ expect(rule).toBeDefined();+ expect(rule).toContain('--dropdown-padding: 8px');+ });++ it('emits internal vars for chat composer', () => {+ const theme = defineTheme({+ name: 'test-derived-chat',+ components: {+ chat: {+ base: {borderRadius: '24px', padding: '12px'},+ },+ },+ });+ const rules = generateThemeRules(theme);+ const rule = rules.find(r => r.includes('.xds-chat'));+ expect(rule).toBeDefined();+ expect(rule).toContain('--composer-radius: 24px');+ expect(rule).toContain('--composer-padding: 12px');+ });++ it('emits internal var for button borderRadius', () => {+ const theme = defineTheme({+ name: 'test-derived-button',+ components: {+ button: {+ base: {borderRadius: '8px'},+ },+ },+ });+ const rules = generateThemeRules(theme);+ const rule = rules.find(r => r.includes('.xds-button'));+ expect(rule).toBeDefined();+ expect(rule).toContain('border-radius: 8px');+ expect(rule).toContain('--button-radius: 8px');+ });++ it('does not emit derived vars for components without registry entries', () => {+ const theme = defineTheme({+ name: 'test-no-derived',+ components: {+ badge: {+ base: {borderRadius: '99px'},+ },+ },+ });+ const rules = generateThemeRules(theme);+ const rule = rules.find(r => r.includes('.xds-badge'));+ expect(rule).toBeDefined();+ expect(rule).toContain('border-radius: 99px');+ // No internal var — badge has no derived registry entry+ expect(rule).not.toContain('--');+ });++ it('container expansion still works for card padding', () => {+ const theme = defineTheme({+ name: 'test-container',+ components: {+ card: {+ base: {padding: '20px'},+ },+ },+ });+ const rules = generateThemeRules(theme);+ const rule = rules.find(r => r.includes('.xds-card'));+ expect(rule).toBeDefined();+ // Container expansion emits --xds-card-padding token+ expect(rule).toContain('--xds-card-padding: 20px');+ });++ it('handles variant-specific derived vars', () => {+ const theme = defineTheme({+ name: 'test-variant-derived',+ components: {+ card: {+ 'variant:muted': {borderRadius: '16px'},+ },+ },+ });+ const rules = generateThemeRules(theme);+ const rule = rules.find(r => r.includes('.xds-card.muted'));+ expect(rule).toBeDefined();+ expect(rule).toContain('border-radius: 16px');+ expect(rule).toContain('--card-radius: 16px');+ });+});+++describe('brutalist-style derived expansion', () => {+ it('button borderRadius emits --button-radius for pill shape', () => {+ const theme = defineTheme({+ name: 'test-brutalist',+ radius: {base: 4, multiplier: 0},+ components: {+ button: {+ base: {borderRadius: '9999px'},+ },+ },+ });+ const rules = generateThemeRules(theme);+ const rule = rules.find(r => r.includes('.xds-button'));+ expect(rule).toContain('border-radius: 9999px');+ expect(rule).toContain('--button-radius: 9999px');+ });++ it('card padding emits container tokens via derived expansion', () => {+ const theme = defineTheme({+ name: 'test-brutalist-card',+ components: {+ card: {+ base: {padding: '24px'},+ },+ },+ });+ const rules = generateThemeRules(theme);+ const rule = rules.find(r => r.includes('.xds-card'));+ expect(rule).toBeDefined();+ expect(rule).toContain('--xds-card-padding: 24px');+ });++ it('dropdown-menu borderRadius + padding emit both derived vars', () => {+ const theme = defineTheme({+ name: 'test-brutalist-dropdown',+ components: {+ 'dropdown-menu': {+ base: {borderRadius: '0px', padding: '4px'},+ },+ },+ });+ const rules = generateThemeRules(theme);+ const rule = rules.find(r => r.includes('.xds-dropdown-menu'));+ expect(rule).toBeDefined();+ expect(rule).toContain('border-radius: 0px');+ expect(rule).toContain('--dropdown-radius: 0px');+ expect(rule).toContain('--dropdown-padding: 4px');+ });+});diff --git a/packages/core/src/theme/index.ts b/packages/core/src/theme/index.tsindex 8f9925f2b1..01bff678f5 100644--- a/packages/core/src/theme/index.ts+++ b/packages/core/src/theme/index.ts@@ -152,3 +152,9 @@ export type {TypographyRole,FontWeight,} from './types';++export {+ derivedVarRegistry,+ getDerivedVars,+ type DerivedVarEntry,+} from './derivedVarRegistry';diff --git a/packages/themes/brutalist/src/brutalistTheme.ts b/packages/themes/brutalist/src/brutalistTheme.tsindex 0c10c8b8bb..7026b40217 100644--- a/packages/themes/brutalist/src/brutalistTheme.ts+++ b/packages/themes/brutalist/src/brutalistTheme.ts@@ -50,12 +50,23 @@ export const brutalistTheme = defineTheme({textTransform: 'uppercase',},},- // Cards get heavy borders+ // Cards get heavy borders + explicit padding via derived expansioncard: {base: {borderWidth: '3px',borderStyle: 'solid',borderColor: 'var(--color-text-primary)',+ padding: '24px',+ },+ },+ // Dropdown menus: sharp corners + tight padding via derived expansion+ 'dropdown-menu': {+ base: {+ borderRadius: '0px',+ padding: '4px',+ borderWidth: '2px',+ borderStyle: 'solid',+ borderColor: 'var(--color-text-primary)',},},// Buttons are loud — 9999px radius override tests layer ordering.