Skip to content

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

TypeScript

feat(Banner): extensible status axis + rename variant to container (#814)

Cindy Zhangf5874377d1ee
diff --git a/apps/sandbox/src/app/(fullscreen)/pages/shell-lab/page.tsx b/apps/sandbox/src/app/(fullscreen)/pages/shell-lab/page.tsx
index 33ee32b8c6..226c440fa5 100644
--- a/apps/sandbox/src/app/(fullscreen)/pages/shell-lab/page.tsx
+++ b/apps/sandbox/src/app/(fullscreen)/pages/shell-lab/page.tsx
@@ -854,7 +854,7 @@ export default function ShellLabPage() {
<XDSBanner
status="info"
title="Shell Lab — System announcement banner"
- variant="section"
+ container="section"
isDismissable
/>
) : undefined
diff --git a/apps/storybook/stories/Banner.stories.tsx b/apps/storybook/stories/Banner.stories.tsx
index 2756a51e90..be88acc506 100644
--- a/apps/storybook/stories/Banner.stories.tsx
+++ b/apps/storybook/stories/Banner.stories.tsx
@@ -14,10 +14,10 @@ const meta: Meta<typeof XDSBanner> = {
options: ['info', 'warning', 'error', 'success'],
description: 'Status type controlling icon and color',
},
- variant: {
+ container: {
control: 'select',
options: ['card', 'section'],
- description: 'Visual variant',
+ description: 'Container type',
},
isDismissable: {
control: 'boolean',
@@ -105,7 +105,7 @@ export const SectionVariant: Story = {
title: 'System maintenance scheduled',
description:
'The system will be undergoing maintenance on Saturday from 2:00 AM to 6:00 AM UTC.',
- variant: 'section',
+ container: 'section',
},
};
@@ -253,9 +253,9 @@ export const AllFeatures: Story = {
</XDSBanner>
<XDSBanner
status="error"
- title="Section variant"
+ title="Section container"
description="Full-width with no border-radius."
- variant="section"
+ container="section"
/>
</div>
),
diff --git a/packages/cli/src/codemods/registry.mjs b/packages/cli/src/codemods/registry.mjs
index e7121493c6..1c65129e69 100644
--- a/packages/cli/src/codemods/registry.mjs
+++ b/packages/cli/src/codemods/registry.mjs
@@ -8,6 +8,7 @@
const registry = new Map([
['0.0.2', () => import('./transforms/v0.0.2/index.mjs')],
['0.0.6', () => import('./transforms/v0.0.6/index.mjs')],
+ ['0.0.7', () => import('./transforms/v0.0.7/index.mjs')],
]);
/**
diff --git a/packages/cli/src/codemods/transforms/v0.0.7/__tests__/rename-banner-variant-to-container.test.mjs b/packages/cli/src/codemods/transforms/v0.0.7/__tests__/rename-banner-variant-to-container.test.mjs
new file mode 100644
index 0000000000..6d59e0292d
--- /dev/null
+++ b/packages/cli/src/codemods/transforms/v0.0.7/__tests__/rename-banner-variant-to-container.test.mjs
@@ -0,0 +1,83 @@
+import {describe, it, expect} from 'vitest';
+
+async function applyTransform(source, filePath = 'test.tsx') {
+ const {default: transform} = await import(
+ '../rename-banner-variant-to-container.mjs'
+ );
+ const jscodeshift = (await import('jscodeshift')).default;
+ const j = filePath.endsWith('.ts') || filePath.endsWith('.tsx')
+ ? jscodeshift.withParser('tsx')
+ : jscodeshift;
+ const api = {jscodeshift: j, stats: () => {}, report: () => {}};
+ const file = {source, path: filePath};
+ const result = transform(file, api);
+ return result ?? source;
+}
+
+describe('rename-banner-variant-to-container', () => {
+ it('renames variant to container on XDSBanner', async () => {
+ const input = '<XDSBanner variant="card" status="info" title="Test" />';
+ const output = await applyTransform(input);
+ expect(output).toContain('container="card"');
+ expect(output).not.toContain('variant=');
+ });
+
+ it('handles section variant', async () => {
+ const input = '<XDSBanner variant="section" status="warning" title="Alert" />';
+ const output = await applyTransform(input);
+ expect(output).toContain('container="section"');
+ });
+
+ it('handles expression values', async () => {
+ const input = '<XDSBanner variant={myVariant} status="info" title="Test" />';
+ const output = await applyTransform(input);
+ expect(output).toContain('container={myVariant}');
+ });
+
+ it('does not rename variant on other components', async () => {
+ const input = '<XDSButton variant="primary" />';
+ const output = await applyTransform(input);
+ expect(output).toBe(input);
+ });
+
+ it('does not rename variant on non-XDS Banner', async () => {
+ const input = '<Banner variant="card" />';
+ const output = await applyTransform(input);
+ expect(output).toBe(input);
+ });
+
+ it('renames XDSBannerVariant type', async () => {
+ const input = 'const v: XDSBannerVariant = "card";';
+ const output = await applyTransform(input, 'test.ts');
+ expect(output).toContain('XDSBannerContainer');
+ expect(output).not.toContain('XDSBannerVariant');
+ });
+
+ it('does not rename XDSBannerVariantMap (removed, not renamed)', async () => {
+ const input = 'type T = XDSBannerVariantMap;';
+ const output = await applyTransform(input, 'test.ts');
+ // VariantMap is removed entirely — consumers need to manually
+ // migrate augmentations to XDSBannerStatusMap
+ expect(output).toBe(input);
+ });
+
+ it('preserves other props', async () => {
+ const input = '<XDSBanner variant="card" status="error" title="Oops" isDismissable />';
+ const output = await applyTransform(input);
+ expect(output).toContain('container="card"');
+ expect(output).toContain('status="error"');
+ expect(output).toContain('title="Oops"');
+ expect(output).toContain('isDismissable');
+ });
+
+ it('returns undefined when no changes needed', async () => {
+ const {default: transform} = await import(
+ '../rename-banner-variant-to-container.mjs'
+ );
+ const jscodeshift = (await import('jscodeshift')).default;
+ const api = {jscodeshift, stats: () => {}, report: () => {}};
+ const source = '<XDSBanner container="card" status="info" title="Test" />';
+ const result = transform({source, path: 'test.tsx'}, api);
+ expect(result).toBeUndefined();
+ });
+});
diff --git a/packages/cli/src/codemods/transforms/v0.0.7/index.mjs b/packages/cli/src/codemods/transforms/v0.0.7/index.mjs
new file mode 100644
index 0000000000..efd59a86d0
--- /dev/null
+++ b/packages/cli/src/codemods/transforms/v0.0.7/index.mjs
@@ -0,0 +1,17 @@
+/**
+ * @file v0.0.7 transform manifest
+ *
+ * Lists all codemods for the v0.0.7 release in the order they should run.
+ */
+
+import renameBannerVariantToContainer, {
+ meta as bannerVariantMeta,
+} from './rename-banner-variant-to-container.mjs';
+
+export default [
+ {
+ name: 'rename-banner-variant-to-container',
+ transform: renameBannerVariantToContainer,
+ meta: bannerVariantMeta,
+ },
+];
diff --git a/packages/cli/src/codemods/transforms/v0.0.7/rename-banner-variant-to-container.mjs b/packages/cli/src/codemods/transforms/v0.0.7/rename-banner-variant-to-container.mjs
new file mode 100644
index 0000000000..0011eb92c5
--- /dev/null
+++ b/packages/cli/src/codemods/transforms/v0.0.7/rename-banner-variant-to-container.mjs
@@ -0,0 +1,51 @@
+/**
+ * @file Codemod: Rename XDSBanner variant to container
+ * @see https://github.com/facebookexperimental/xds/pull/814
+ *
+ * Banner's `variant` prop (card/section) controlled container shape,
+ * not visual treatment. Renamed to `container` to free `variant`
+ * semantics for theming and make the API more honest.
+ *
+ * Also renames the type exports:
+ * - XDSBannerVariant → XDSBannerContainer
+ * - XDSBannerVariantMap → XDSBannerContainerMap
+ */
+
+export const meta = {
+ title: 'Rename Banner variant → container',
+ description:
+ 'Renames the `variant` prop on XDSBanner to `container`, and updates type references from XDSBannerVariant to XDSBannerContainer.',
+ pr: '#814',
+};
+
+export default function transformer(file, api) {
+ const j = api.jscodeshift;
+ const root = j(file.source);
+ let hasChanges = false;
+
+ // 1. Rename JSX prop: <XDSBanner variant="card" /> → <XDSBanner container="card" />
+ root
+ .find(j.JSXOpeningElement, {
+ name: {name: 'XDSBanner'},
+ })
+ .forEach((path) => {
+ path.node.attributes.forEach((attr) => {
+ if (attr.type === 'JSXAttribute' && attr.name.name === 'variant') {
+ attr.name.name = 'container';
+ hasChanges = true;
+ }
+ });
+ });
+
+ // 2. Rename type references: XDSBannerVariant → XDSBannerContainer
+ root.find(j.Identifier, {name: 'XDSBannerVariant'}).forEach((path) => {
+ path.node.name = 'XDSBannerContainer';
+ hasChanges = true;
+ });
+
+ // Note: XDSBannerVariantMap is removed entirely (theming now uses
+ // XDSBannerStatusMap). Any augmentations of XDSBannerVariantMap should
+ // be migrated to XDSBannerStatusMap manually.
+
+ return hasChanges ? root.toSource() : undefined;
+}
diff --git a/packages/cli/src/commands/build-theme.mjs b/packages/cli/src/commands/build-theme.mjs
index c69f86dc1e..27c9789512 100644
--- a/packages/cli/src/commands/build-theme.mjs
+++ b/packages/cli/src/commands/build-theme.mjs
@@ -13,6 +13,7 @@
import * as fs from 'node:fs';
import * as path from 'node:path';
import {createRequire} from 'node:module';
+import {pathToFileURL, fileURLToPath} from 'node:url';
// Import shared theme processing from core — ensures build and runtime
// use the same logic for typography.scale expansion, prose, and component rules.
@@ -54,38 +55,185 @@ function toPascalCase(name) {
}
/**
- * Generate TypeScript declaration file with module augmentation for theme variants.
+ * Load known built-in values for a component's visual props from its .doc.mjs file.
+ * Parses the type string (e.g. "'info' | 'warning' | 'error' | 'success'") to extract values.
+ * Returns a map of { propName: string[] } for props that are visual (listed in theming targets).
+ */
+async function loadKnownValues(componentName) {
+ // Resolve core src relative to the CLI package, not cwd (which may be a theme package)
+ const cliDir = path.dirname(fileURLToPath(import.meta.url));
+ const coreSrc = path.resolve(cliDir, '../../../core/src');
+ if (!fs.existsSync(coreSrc)) return {};
+ // Map component name to directory (e.g. 'banner' → 'Banner', 'dropdownmenu' → 'DropdownMenu')
+ const dirs = fs.readdirSync(coreSrc, { withFileTypes: true })
+ .filter(d => d.isDirectory())
+ .map(d => d.name);
+ const dir = dirs.find(d => d.toLowerCase() === componentName.toLowerCase()
+ || d.toLowerCase().replace(/[^a-z]/g, '') === componentName.toLowerCase());
+ if (!dir) return {};
+
+ const docPath = path.join(coreSrc, dir, `${dir}.doc.mjs`);
+ if (!fs.existsSync(docPath)) return {};
+
+ try {
+ const docModule = await import(pathToFileURL(docPath).href);
+ const doc = docModule.docs;
+ if (!doc?.theming?.targets) return {};
+
+ // Collect all props — from doc.props or doc.components[].props
+ const allProps = [];
+ if (doc.props) allProps.push(...doc.props);
+ if (doc.components) {
+ for (const comp of doc.components) {
+ if (comp.props) allProps.push(...comp.props);
+ }
+ }
+ if (allProps.length === 0) return {};
+
+ // Collect visual prop names from theming targets
+ const visualProps = new Set();
+ for (const target of doc.theming.targets) {
+ if (target.visualProps) {
+ for (const vp of target.visualProps) visualProps.add(vp);
+ }
+ }
+
+ // Extract values from prop type strings
+ const result = {};
+ for (const prop of allProps) {
+ if (!visualProps.has(prop.name)) continue;
+ if (!prop.type || typeof prop.type !== 'string') continue;
+
+ // Parse union type: "'info' | 'warning' | 'error' | 'success'" → ['info', 'warning', 'error', 'success']
+ const matches = prop.type.match(/'([^']+)'/g);
+ if (matches) {
+ result[prop.name] = matches.map(m => m.replace(/'/g, ''));
+ }
+ }
+ return result;
+ } catch {
+ return {};
+ }
+}
+
+// Cache for loaded known values
+const _knownValuesCache = new Map();
+async function getKnownValues(componentName) {
+ if (!_knownValuesCache.has(componentName)) {
+ _knownValuesCache.set(componentName, await loadKnownValues(componentName));
+ }
+ return _knownValuesCache.get(componentName);
+}
+
+
+/**
+ * Generate TypeScript declaration file with module augmentation for custom
+ * component prop values found in the theme's `components` keys.
+ *
+ * Scans component override keys (e.g. `status:neutral`, `variant:primary-muted`)
+ * and generates augmentations for values not in the base type.
*
- * Maps component names from the theme's `variants` field to their module paths
- * and augments the corresponding XDS{Component}VariantMap interfaces.
+ * Interface naming convention: XDS + PascalCase(component) + PascalCase(prop) + Map
+ * banner + status → XDSBannerStatusMap
+ * button + variant → XDSButtonVariantMap
*
- * @param {object} themeDef - Theme definition with variants
- * @returns {string|null} TypeScript declaration content, or null if no variants
+ * @param {object} themeDef - Theme definition (resolved by defineTheme)
+ * @returns {string|null} TypeScript declaration content, or null if no augmentations needed
*/
function generateVariantDeclarations(themeDef) {
- if (!themeDef.variants || Object.keys(themeDef.variants).length === 0) {
+ if (!themeDef.components || Object.keys(themeDef.components).length === 0) {
return null;
}
- const sections = ['// Generated by xds theme build', ''];
+ // Collect custom values: { component: { prop: [value, ...] } }
+ const customValues = {};
- for (const [componentKey, variantNames] of Object.entries(themeDef.variants)) {
- if (!variantNames || variantNames.length === 0) continue;
+ for (const [component, rules] of Object.entries(themeDef.components)) {
+ for (const key of Object.keys(rules)) {
+ if (key === 'base') continue;
- const pascal = toPascalCase(componentKey);
- const modulePath = `@xds/core/${pascal}`;
- const interfaceName = `XDS${pascal}VariantMap`;
+ // Parse prop:value pairs from keys like 'status:neutral' or 'variant:primary+size:sm'
+ const pairs = key.split('+');
+ for (const pair of pairs) {
+ const colonIdx = pair.indexOf(':');
+ if (colonIdx === -1) continue;
+ const prop = pair.slice(0, colonIdx);
+ const value = pair.slice(colonIdx + 1);
+
+ // It's a custom value — collect it for augmentation
+ // (filtering against known values happens async in generateVariantDeclarationsAsync)
+ if (!customValues[component]) customValues[component] = {};
+ if (!customValues[component][prop]) customValues[component][prop] = new Set();
+ customValues[component][prop].add(value);
+ }
+ }
+ }
- const entries = variantNames
- .map(v => ` '${v}': true;`)
- .join('\n');
+ // Sync stub — returns null, use generateVariantDeclarationsAsync instead
+ return null;
+}
+
+/**
+ * Async version of generateVariantDeclarations that reads known values from doc files.
+ */
+async function generateVariantDeclarationsAsync(themeDef) {
+ if (!themeDef.components || Object.keys(themeDef.components).length === 0) {
+ return null;
+ }
+
+ // Collect custom values: { component: { prop: [value, ...] } }
+ const customValues = {};
+
+ for (const [component, rules] of Object.entries(themeDef.components)) {
+ const knownForComponent = await getKnownValues(component);
+
+ for (const key of Object.keys(rules)) {
+ if (key === 'base') continue;
- sections.push(`declare module '${modulePath}' {`);
- sections.push(` interface ${interfaceName} {`);
- sections.push(...variantNames.map(v => ` '${v}': true;`));
- sections.push(' }');
- sections.push('}');
- sections.push('');
+ const pairs = key.split('+');
+ for (const pair of pairs) {
+ const colonIdx = pair.indexOf(':');
+ if (colonIdx === -1) continue;
+ const prop = pair.slice(0, colonIdx);
+ const value = pair.slice(colonIdx + 1);
+
+ // Skip known built-in values
+ const knownForProp = knownForComponent[prop];
+ if (knownForProp && knownForProp.includes(value)) continue;
+
+ if (!customValues[component]) customValues[component] = {};
+ if (!customValues[component][prop]) customValues[component][prop] = new Set();
+ customValues[component][prop].add(value);
+ }
+ }
+ }
+
+ // Check if we found any custom values
+ const hasCustom = Object.values(customValues).some(
+ props => Object.values(props).some(values => values.size > 0)
+ );
+ if (!hasCustom) return null;
+
+ const sections = ['// Generated by xds theme build', ''];
+
+ for (const [component, props] of Object.entries(customValues)) {
+ for (const [prop, values] of Object.entries(props)) {
+ if (values.size === 0) continue;
+
+ const pascal = toPascalCase(component);
+ const propPascal = prop.charAt(0).toUpperCase() + prop.slice(1);
+ const modulePath = `@xds/core/${pascal}`;
+ const interfaceName = `XDS${pascal}${propPascal}Map`;
+
+ sections.push(`declare module '${modulePath}' {`);
+ sections.push(` interface ${interfaceName} {`);
+ for (const v of values) {
+ sections.push(` '${v}': true;`);
+ }
+ sections.push(' }');
+ sections.push('}');
+ sections.push('');
+ }
}
return sections.join('\n');
@@ -466,7 +614,7 @@ const KNOWN_COMPONENTS = {
aspectratio: [],
avatar: ['size'],
badge: ['variant', 'color'],
- banner: ['variant'],
+ banner: ['container', 'status'],
breadcrumbs: ['variant'],
button: ['variant', 'size'],
calendar: [],
@@ -633,7 +781,6 @@ export function registerTheme(program) {
radius: themeDef.radius,
tokens: themeDef.tokens,
components: themeDef.components,
- variants: themeDef.variants,
});
const rules = _generateThemeRules(resolvedTheme);
if (rules.length === 0) {
@@ -698,14 +845,14 @@ 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);
+ // Generate type augmentation .d.ts if theme has custom prop values
+ const augmentationSource = resolvedTheme || themeDef;
+ const variantDecl = await generateVariantDeclarationsAsync(augmentationSource);
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)`);
+ const augCount = (variantDecl.match(/': true;/g) || []).length;
+ console.log(`✓ ${path.relative(process.cwd(), variantDtsPath)} (${augCount} type augmentations)`);
}
// Print install instructions
diff --git a/packages/core/src/Banner/Banner.doc.mjs b/packages/core/src/Banner/Banner.doc.mjs
index 90cd143c6b..c9c77c2dd5 100644
--- a/packages/core/src/Banner/Banner.doc.mjs
+++ b/packages/core/src/Banner/Banner.doc.mjs
@@ -12,8 +12,8 @@ export const docs = {
'onDismiss callback fires alongside the internal state change for logging or backend sync',
'Default status icons from @heroicons/react/24/solid: InformationCircleIcon (info), ExclamationTriangleIcon (warning), XCircleIcon (error), CheckCircleIcon (success)',
'Status colors: info uses --color-accent-muted, warning uses --color-warning-muted, error uses --color-error-muted, success uses --color-success-muted',
- 'Card variant (default): has border-radius with optional card content area below the colored header',
- 'Section variant: no border-radius, full-width for page-level banners',
+ 'Card container (default): has border-radius with optional card content area below the colored header',
+ 'Section container: no border-radius, full-width for page-level banners',
],
examples: [
@@ -88,10 +88,10 @@ export const docs = {
'Action content rendered in the header area, end-aligned. Typically a button or link.',
},
{
- name: 'variant',
+ name: 'container',
type: "'card' | 'section'",
description:
- 'Visual variant: card has border-radius; section is full-width with no border-radius for page-level use.',
+ 'Container type: card has border-radius; section is full-width with no border-radius for page-level use.',
default: "'card'",
},
{
@@ -117,14 +117,15 @@ export const docs = {
theming: {
targets: [
- {className: 'xds-banner', visualProps: ['variant', 'status']},
+ {className: 'xds-banner', visualProps: ['container', 'status']},
{className: 'xds-banner-icon', visualProps: ['status']},
],
vars: [
- {name: '--banner-radius', description: 'Border radius (card variant only)', default: 'var(--radius-3)'},
+ {name: '--banner-radius', description: 'Border radius (card container only)', default: 'var(--radius-3)'},
],
},
notes: [
+ 'Banner uses `status` as its extensible theming axis. Custom statuses via `defineTheme` components: `status:neutral`.',
'Collapsible support is planned: the content area will support collapsing via useXDSCollapsible (issue #187)',
],
};
@@ -218,7 +219,7 @@ export const docsZh = {
'渲染在头部区域末端对齐的操作内容,通常是按钮或链接。',
},
{
- name: 'variant',
+ name: 'container',
type: "'card' | 'section'",
description:
'视觉变体:card 带圆角;section 无圆角全宽,适用于页面级场景。',
@@ -247,14 +248,15 @@ export const docsZh = {
theming: {
targets: [
- {className: 'xds-banner', visualProps: ['variant', 'status']},
+ {className: 'xds-banner', visualProps: ['container', 'status']},
{className: 'xds-banner-icon', visualProps: ['status']},
],
vars: [
- {name: '--banner-radius', description: 'Border radius (card variant only)', default: 'var(--radius-3)'},
+ {name: '--banner-radius', description: 'Border radius (card container only)', default: 'var(--radius-3)'},
],
},
notes: [
+ 'Banner 使用 `status` 作为可扩展的主题轴。通过 defineTheme components 添加自定义状态:`status:neutral`。',
'折叠支持已规划:内容区将通过 useXDSCollapsible 支持折叠(issue #187)',
],
};
@@ -269,8 +271,8 @@ export const docsDense = {
'onDismiss fires alongside internal state change for logging/backend sync',
'default status icons from @heroicons/react/24/solid: InformationCircleIcon, ExclamationTriangleIcon, XCircleIcon, CheckCircleIcon',
'status colors: info=accent-deemphasized, warning=warning-deemphasized, error=negative-deemphasized, success=positive-deemphasized',
- 'card variant (default): border-radius w/ optional card content below header',
- 'section variant: no border-radius, full-width for page-level banners',
+ 'card container (default): border-radius w/ optional card content below header',
+ 'section container: no border-radius, full-width for page-level banners',
],
notes: [
'collapsible support planned via useXDSCollapsible (issue #187)',
@@ -289,7 +291,7 @@ export const docsDense = {
isDismissable: 'user can dismiss banner',
onDismiss: 'dismiss callback; banner self-hides regardless',
endContent: 'end-aligned action in header, typically button/link',
- variant: 'card=border-radius; section=full-width no radius for page-level',
+ container: 'card=border-radius; section=full-width no radius for page-level',
children: 'content in card-bg area below colored header',
xstyle: 'StyleX layout customization via stylex.create()',
},
diff --git a/packages/core/src/Banner/XDSBanner.test.tsx b/packages/core/src/Banner/XDSBanner.test.tsx
index e686631b55..2108eff0a5 100644
--- a/packages/core/src/Banner/XDSBanner.test.tsx
+++ b/packages/core/src/Banner/XDSBanner.test.tsx
@@ -146,17 +146,17 @@ describe('XDSBanner', () => {
expect(screen.getByTestId('end-btn')).toBeInTheDocument();
});
- it('renders card variant by default', () => {
+ it('renders card container by default', () => {
const {container} = render(
- <XDSBanner status="info" title="Card Variant" />,
+ <XDSBanner status="info" title="Card Container" />,
);
const root = container.firstElementChild;
expect(root).toBeInTheDocument();
});
- it('renders section variant', () => {
+ it('renders section container', () => {
const {container} = render(
- <XDSBanner status="info" title="Section Variant" variant="section" />,
+ <XDSBanner status="info" title="Section Container" container="section" />,
);
const root = container.firstElementChild;
expect(root).toBeInTheDocument();
diff --git a/packages/core/src/Banner/XDSBanner.tsx b/packages/core/src/Banner/XDSBanner.tsx
index fd1bd50503..2d6bc14b3d 100644
--- a/packages/core/src/Banner/XDSBanner.tsx
+++ b/packages/core/src/Banner/XDSBanner.tsx
@@ -3,7 +3,7 @@
/**
* @file XDSBanner.tsx
* @input Uses ReactuseState, @heroicons/react/24/solid icons, XDSButton, XDSIcon, StyleX
- * @output Exports XDSBanner component, XDSBannerProps, XDSBannerStatus, XDSBannerVariant types
+ * @output Exports XDSBanner component, XDSBannerProps, XDSBannerStatus, XDSBannerContainer types
* @position Core implementation; consumed by index.ts, tested by XDSBanner.test.tsx
*
* Visual structure:
@@ -48,37 +48,58 @@ import {xdsClassName, mergeProps} from '../utils';
// Types
// =============================================================================
+/**
+ * Extensible status map for XDSBanner.
+ *
+ * Theme packages can add custom statuses via TypeScript module augmentation:
+ * @example
+ * ```
+ * declare module '@xds/core/Banner' {
+ * interface XDSBannerStatusMap {
+ * 'neutral': true;
+ * }
+ * }
+ * ```
+ */
+export interface XDSBannerStatusMap {
+ info: true;
+ warning: true;
+ error: true;
+ success: true;
+}
+
/**
* Status type controlling the banner's icon and color.
+ * Extensible via module augmentation of XDSBannerStatusMap.
*/
-export type XDSBannerStatus = 'info' | 'warning' | 'error' | 'success';
+export type XDSBannerStatus = keyof XDSBannerStatusMap;
/**
- * Extensible variant map for XDSBanner.
+ * Extensible container map for XDSBanner.
*
- * Theme packages can add custom variants via TypeScript module augmentation:
+ * Theme packages can add custom container types via TypeScript module augmentation:
* @example
* ```
* declare module '@xds/core/Banner' {
- * interface XDSBannerVariantMap {
+ * interface XDSBannerContainerMap {
* 'floating': true;
* }
* }
* ```
*/
-export interface XDSBannerVariantMap {
+export interface XDSBannerContainerMap {
card: true;
section: true;
}
/**
- * Visual variant of the banner.
+ * Container type of the banner.
* - `card`: standalone card with border-radius and shadow
* - `section`: full-width section banner (no border-radius)
*
- * Extensible via module augmentation of XDSBannerVariantMap.
+ * Extensible via module augmentation of XDSBannerContainerMap.
*/
-export type XDSBannerVariant = keyof XDSBannerVariantMap;
+export type XDSBannerContainer = keyof XDSBannerContainerMap;
export interface XDSBannerProps {
/** Ref forwarded to the root element */
@@ -122,12 +143,12 @@ export interface XDSBannerProps {
*/
endContent?: ReactNode;
/**
- * Visual variant of the banner.
+ * Container type of the banner.
* - `card`: standalone card with border-radius
* - `section`: full-width section banner (no border-radius)
* @default 'card'
*/
- variant?: XDSBannerVariant;
+ container?: XDSBannerContainer;
/**
* Whether the content area (children) starts expanded.
* Only relevant when children are provided.
@@ -364,7 +385,7 @@ export function XDSBanner({
isDismissable = false,
onDismiss,
endContent,
- variant = 'card',
+ container = 'card',
defaultIsExpanded = false,
children,
xstyle,
@@ -406,11 +427,11 @@ export function XDSBanner({
role={role}
data-testid={testId}
{...mergeProps(
- xdsClassName('banner', {variant, status}),
+ xdsClassName('banner', {container, status}),
stylex.props(
styles.root,
- variant === 'card' && styles.card,
- variant === 'section' && styles.section,
+ container === 'card' && styles.card,
+ container === 'section' && styles.section,
xstyle,
),
className,
@@ -479,7 +500,7 @@ export function XDSBanner({
<div
{...stylex.props(
styles.contentArea,
- variant === 'card' && styles.contentAreaCard,
+ container === 'card' && styles.contentAreaCard,
)}>
{children}
</div>
diff --git a/packages/core/src/Banner/index.ts b/packages/core/src/Banner/index.ts
index 9c49284e56..4ac49aaeeb 100644
--- a/packages/core/src/Banner/index.ts
+++ b/packages/core/src/Banner/index.ts
@@ -3,7 +3,7 @@
/**
* @file index.ts
* @input Imports XDSBanner component and types from XDSBanner.tsx
- * @output Exports XDSBanner, XDSBannerProps, XDSBannerStatus, XDSBannerVariant
+ * @output Exports XDSBanner, XDSBannerProps, XDSBannerStatus, XDSBannerContainer
* @position Component entry point; re-exported by /packages/core/src/index.ts
*
* SYNC: When modified, update this header and /packages/core/src/Banner/Banner.doc.mjs
@@ -13,6 +13,7 @@ export {XDSBanner} from './XDSBanner';
export type {
XDSBannerProps,
XDSBannerStatus,
- XDSBannerVariant,
- XDSBannerVariantMap,
+ XDSBannerStatusMap,
+ XDSBannerContainer,
+ XDSBannerContainerMap,
} from './XDSBanner';
diff --git a/packages/core/src/theme/defineTheme.test.ts b/packages/core/src/theme/defineTheme.test.ts
index 9f6d553697..d45508ed9a 100644
--- a/packages/core/src/theme/defineTheme.test.ts
+++ b/packages/core/src/theme/defineTheme.test.ts
@@ -433,116 +433,104 @@ describe('radius', () => {
});
});
-describe('variants', () => {
- it('extracts variant names from styled variant objects', () => {
+describe('custom status via components', () => {
+ it('passes custom status through components as status:value keys', () => {
const theme = defineTheme({
- name: 'custom',
- variants: {
- button: {
- 'primary-muted': {
- backgroundColor: 'var(--color-accent-muted)',
- color: 'var(--color-accent)',
- },
- 'primary-outline': {
- borderWidth: '2px',
- borderStyle: 'solid',
+ name: 'banner-status',
+ components: {
+ banner: {
+ 'status:neutral': {
+ backgroundColor: 'var(--color-muted)',
},
},
- badge: {
- 'info-subtle': {
- backgroundColor: 'var(--color-info-muted)',
+ },
+ });
+ expect(theme.components?.banner?.['status:neutral']).toEqual({
+ backgroundColor: 'var(--color-muted)',
+ });
+ });
+
+ it('generates correct CSS selectors for banner status extensions', () => {
+ const theme = defineTheme({
+ name: 'banner-css',
+ components: {
+ banner: {
+ 'status:neutral': {
+ backgroundColor: 'var(--color-muted)',
},
},
},
});
- expect(theme.variants).toEqual({
- button: ['primary-muted', 'primary-outline'],
- badge: ['info-subtle'],
- });
+ const css = generateThemeCSS(theme);
+ // parseStyleKey('status:neutral') → '.neutral', so CSS should have .xds-banner.neutral
+ expect(css).toContain('.xds-banner.neutral');
+ expect(css).toContain('background-color: var(--color-muted)');
});
- it('merges variant styles into components as variant: keys', () => {
+ it('custom button variant via components', () => {
const theme = defineTheme({
- name: 'styled-variants',
- variants: {
+ name: 'button-variant',
+ components: {
button: {
- 'primary-muted': {
- backgroundColor: 'var(--color-accent-muted)',
- color: 'var(--color-accent)',
+ 'variant:primary-muted': {
+ backgroundColor: '#ECF5FF',
},
},
},
});
expect(theme.components?.button?.['variant:primary-muted']).toEqual({
- backgroundColor: 'var(--color-accent-muted)',
- color: 'var(--color-accent)',
+ backgroundColor: '#ECF5FF',
});
});
- it('handles empty style objects (register-only variants)', () => {
+ it('generates correct CSS for custom button variant', () => {
const theme = defineTheme({
- name: 'register-only',
- variants: {
+ name: 'button-css',
+ components: {
button: {
- 'primary-muted': {},
+ 'variant:primary-muted': {
+ backgroundColor: '#ECF5FF',
+ },
},
},
});
- expect(theme.variants).toEqual({button: ['primary-muted']});
- // Empty styles should not create a component entry
- expect(theme.components?.button?.['variant:primary-muted']).toBeUndefined();
- });
-
- it('returns undefined variants when not provided', () => {
- const theme = defineTheme({name: 'bare'});
- expect(theme.variants).toBeUndefined();
+ const css = generateThemeCSS(theme);
+ expect(css).toContain('.xds-button.primary-muted');
+ expect(css).toContain('background-color: #ECF5FF');
});
- it('combines variants with tokens and explicit components', () => {
+ it('combines custom status with base and token overrides', () => {
const theme = defineTheme({
name: 'combo',
tokens: {'--color-accent': '#FF0000'},
- components: {button: {base: {borderRadius: '999px'}}},
- variants: {
- button: {
- 'primary-muted': {
- backgroundColor: 'var(--color-accent-muted)',
+ components: {
+ banner: {
+ 'status:neutral': {
+ backgroundColor: 'var(--color-muted)',
+ color: 'gray',
},
},
+ button: {base: {borderRadius: '999px'}},
},
});
expect(theme.tokens['--color-accent']).toBe('#FF0000');
- // Explicit component styles preserved
- expect(theme.components?.button?.base?.borderRadius).toBe('999px');
- // Variant styles merged in
- expect(theme.components?.button?.['variant:primary-muted']).toEqual({
- backgroundColor: 'var(--color-accent-muted)',
+ expect(theme.components?.banner?.['status:neutral']).toEqual({
+ backgroundColor: 'var(--color-muted)',
+ color: 'gray',
});
- expect(theme.variants).toEqual({button: ['primary-muted']});
+ expect(theme.components?.button?.base?.borderRadius).toBe('999px');
});
- it('explicit components override variant styles on collision', () => {
+ it('does not have a variants field on the output', () => {
const theme = defineTheme({
- name: 'override',
+ name: 'no-variants',
components: {
- button: {
- 'variant:primary-muted': {backgroundColor: 'red'},
- },
- },
- variants: {
- button: {
- 'primary-muted': {backgroundColor: 'blue', color: 'white'},
+ banner: {
+ 'status:neutral': {backgroundColor: 'gray'},
},
},
});
- // Explicit component override wins for backgroundColor
- expect(
- theme.components?.button?.['variant:primary-muted']?.backgroundColor,
- ).toBe('red');
- // Variant-only property still present
- expect(theme.components?.button?.['variant:primary-muted']?.color).toBe(
- 'white',
- );
+ expect(theme).not.toHaveProperty('variants');
});
});
diff --git a/packages/core/src/theme/defineTheme.ts b/packages/core/src/theme/defineTheme.ts
index ad880ff6c8..bfcc6a593a 100644
--- a/packages/core/src/theme/defineTheme.ts
+++ b/packages/core/src/theme/defineTheme.ts
@@ -219,62 +219,27 @@ export interface XDSDefineThemeInput {
* Each entry maps style keys to CSS property overrides, scoped under
* the theme's data-xds-theme attribute via @scope.
*
+ * Use `prop:value` keys to target specific visual props. New values
+ * not in the base type are automatically detected by `xds theme build`
+ * and generate TypeScript module augmentations for type-safe extensibility.
+ *
* @example
* ```tsx
* components: {
* button: {
* base: { fontWeight: '600' },
* 'variant:secondary': { backgroundColor: '...' },
+ * 'variant:primary-muted': { backgroundColor: '#ECF5FF' }, // new — generates augmentation
+ * },
+ * banner: {
+ * 'status:neutral': { backgroundColor: 'var(--color-muted)' }, // new status
* },
* }
- * // Generates:
- * // @scope ([data-xds-theme="ocean"]) to ([data-xds-theme]) {
- * // .xds-button { font-weight: 600; }
- * // .xds-button.secondary { background-color: ...; }
- * // }
* ```
*/
components?: XDSComponentStyleMap;
/** Icon registry — maps semantic icon names to React nodes */
icons?: Partial<XDSIconRegistry>;
- /**
- * Custom variants added by this theme — declaration and styles together.
- * Keyed by component name (lowercase), then variant name → style object.
- *
- * Use this for NEW variants the theme introduces. To override styles on
- * existing built-in variants (e.g. `variant:secondary`), use `components`.
- *
- * An empty object `{}` registers the variant name without adding styles.
- *
- * Variant names 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': {
- * backgroundColor: 'var(--color-accent-muted)',
- * color: 'var(--color-accent)',
- * },
- * 'primary-outline': {
- * borderWidth: '2px',
- * borderStyle: 'solid',
- * borderColor: 'var(--color-accent)',
- * backgroundColor: 'transparent',
- * },
- * },
- * badge: {
- * 'info-subtle': {
- * backgroundColor: 'var(--color-info-muted)',
- * color: 'var(--color-info)',
- * },
- * },
- * }
- * ```
- */
- variants?: Record<string, Record<string, Record<string, string>>>;
}
/** A defined theme — ready to pass to <XDSTheme> */
@@ -287,8 +252,6 @@ 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;
/**
@@ -513,34 +476,7 @@ export function defineTheme(input: XDSDefineThemeInput): XDSDefinedTheme {
components = deepMergeComponents(generated, input.components);
}
- // 4. Process variants: extract names for type augmentation + merge styles into components
- let variantNames: Record<string, string[]> | undefined;
- if (input.variants) {
- variantNames = {};
- const variantComponents: XDSComponentStyleMap = {};
- for (const [component, variantMap] of Object.entries(input.variants)) {
- const names: string[] = [];
- for (const [variantName, styles] of Object.entries(variantMap)) {
- names.push(variantName);
- // Merge non-empty variant styles into components as `variant:name`
- if (styles && Object.keys(styles).length > 0) {
- if (!variantComponents[component]) {
- variantComponents[component] = {};
- }
- variantComponents[component][`variant:${variantName}`] = styles;
- }
- }
- if (names.length > 0) {
- variantNames[component] = names;
- }
- }
- // Merge variant-derived component styles (lowest) with explicit components (highest)
- if (Object.keys(variantComponents).length > 0) {
- components = deepMergeComponents(variantComponents, components);
- }
- }
-
- // 5. Derive fonts array from typography roles (for runtime loading)
+ // 4. Derive fonts array from typography roles (for runtime loading)
let fonts: ThemeFontSource[] | undefined;
if (typo) {
const seen = new Set<string>();
@@ -561,7 +497,6 @@ export function defineTheme(input: XDSDefineThemeInput): XDSDefinedTheme {
tokens,
components,
icons: input.icons,
- variants: variantNames,
fonts,
};
}
diff --git a/packages/themes/brutalist/src/index.ts b/packages/themes/brutalist/src/index.ts
index aea6732212..6ed78ed7a6 100644
--- a/packages/themes/brutalist/src/index.ts
+++ b/packages/themes/brutalist/src/index.ts
@@ -37,6 +37,15 @@ export const brutalistTheme = defineTheme({
'--radius-rounded': '0px',
},
components: {
+ // Custom banner status — danger
+ banner: {
+ 'status:danger': {
+ backgroundColor: '#FF0000',
+ color: '#FFFFFF',
+ fontWeight: '900',
+ textTransform: 'uppercase',
+ },
+ },
// Cards get heavy borders
card: {
base: {