Skip to content

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

TypeScript

feat(Card): make the variant axis theme-extensible via CardVariantMap (#5551)

Cindy Zhang408cef2192f8
diff --git a/.changeset/card-variant-map.md b/.changeset/card-variant-map.md
new file mode 100644
index 0000000000..b8a444f75f
--- /dev/null
+++ b/.changeset/card-variant-map.md
@@ -0,0 +1,13 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] Card: make the `variant` axis theme-extensible through a `CardVariantMap` interface
+
+`CardVariant` was a hand-written union backed by a closed style record, so a theme could not add a card variant: an unknown value neither type-checked nor rendered. It is now `keyof CardVariantMap`, an interface exported from `@astryxdesign/core/Card` that a theme build augments — the same shape Button, Badge, Section and the other extensible axes already ship.
+
+`keyof CardVariantMap` resolves to exactly the thirteen values `CardVariant` had, so no existing call site changes. A variant a theme adds falls through to base styles and the theme's own `card['variant:<name>']` rule paints it.
+
+On SelectableCard that variant's selection ring is drawn in `--selectable-card-ring-color`, defaulting to the accent. No token the component could pick is guaranteed to contrast with a fill the component cannot know, so a theme rule that adds a variant sets the ring colour in the same rule as its `backgroundColor`.
+
+@cixzhang
diff --git a/apps/storybook/stories/Card.stories.tsx b/apps/storybook/stories/Card.stories.tsx
index 7614f6febd..42f1936b3e 100644
--- a/apps/storybook/stories/Card.stories.tsx
+++ b/apps/storybook/stories/Card.stories.tsx
@@ -4,6 +4,7 @@ import type {Meta, StoryObj} from '@storybook/react';
import * as stylex from '@stylexjs/stylex';
import {Card} from '@astryxdesign/core/Card';
import {Section} from '@astryxdesign/core/Section';
+import {SelectableCard} from '@astryxdesign/core/SelectableCard';
import {
VStack,
HStack,
@@ -14,6 +15,7 @@ import {
} from '@astryxdesign/core/Layout';
import {Button} from '@astryxdesign/core/Button';
import {Heading} from '@astryxdesign/core/Text';
+import {Theme, defineTheme} from '@astryxdesign/core/theme';
import {
colorVars,
spacingVars,
@@ -34,6 +36,10 @@ const styles = stylex.create({
color: colorVars['--color-text-secondary'],
fontSize: 14,
},
+ // Lets the ThemeAddedVariant story's card colour reach its own text.
+ textInherit: {
+ color: 'inherit',
+ },
storyWrapper: {
display: 'flex',
gap: spacingVars['--spacing-6'],
@@ -470,6 +476,84 @@ export const ColorVariants: Story = {
),
};
+/**
+ * `brand` is not one of Card's variants. The theme adds it: the module
+ * augmentation widens `CardVariantMap` so `variant="brand"` type-checks, and
+ * `card['variant:brand']` supplies the paint. Card itself has no style for the
+ * value, so it falls through to base styles and the theme rule is what shows —
+ * here an accent fill no built-in variant produces.
+ *
+ * The added variant is background-only, which is the shape the axis carries:
+ * Card subtracts a border's width from its padding for `default` alone, so a
+ * theme rule that paints a border sits a border-width proud of the cards
+ * beside it. That is true of a theme override on a built-in variant today and
+ * is not this axis to fix.
+ */
+declare module '@astryxdesign/core/Card' {
+ interface CardVariantMap {
+ brand: true;
+ }
+}
+
+const brandVariantTheme = defineTheme({
+ name: 'card-brand-variant-demo',
+ components: {
+ card: {
+ 'variant:brand': {
+ backgroundColor: 'var(--color-accent)',
+ color: 'var(--color-on-accent)',
+ // The ring for a variant Card has never seen: the theme picks it,
+ // because no token the component could pick is guaranteed to contrast
+ // with this fill.
+ '--selectable-card-ring-color': 'var(--color-on-accent)',
+ },
+ },
+ },
+});
+
+export const ThemeAddedVariant: Story = {
+ render: () => (
+ <Theme theme={brandVariantTheme} mode="light">
+ <div {...stylex.props(styles.storyWrapper)}>
+ <div>
+ <h4 {...stylex.props(styles.heading)}>brand (added by the theme)</h4>
+ <Card width={200} variant="brand">
+ <p {...stylex.props(styles.text, styles.textInherit)}>brand</p>
+ </Card>
+ </div>
+ <div>
+ <h4 {...stylex.props(styles.heading)}>default (built in)</h4>
+ <Card width={200}>
+ <p {...stylex.props(styles.text)}>default</p>
+ </Card>
+ </div>
+ <div>
+ <h4 {...stylex.props(styles.heading)}>brand, selected</h4>
+ <SelectableCard
+ label="brand, selected"
+ isSelected
+ onChange={() => {}}
+ variant="brand"
+ width={200}>
+ <p {...stylex.props(styles.text, styles.textInherit)}>selected</p>
+ </SelectableCard>
+ </div>
+ <div>
+ <h4 {...stylex.props(styles.heading)}>brand, unselected</h4>
+ <SelectableCard
+ label="brand, unselected"
+ isSelected={false}
+ onChange={() => {}}
+ variant="brand"
+ width={200}>
+ <p {...stylex.props(styles.text, styles.textInherit)}>unselected</p>
+ </SelectableCard>
+ </div>
+ </div>
+ </Theme>
+ ),
+};
+
/**
* A card with no children, and one with a minimum height. An empty card holds
* its padding and radius rather than collapsing, so a placeholder or a loading
diff --git a/packages/cli/clients/cli/commands/build-theme.variants.test.mjs b/packages/cli/clients/cli/commands/build-theme.variants.test.mjs
index cf03a4f7e0..a7ad2a82f2 100644
--- a/packages/cli/clients/cli/commands/build-theme.variants.test.mjs
+++ b/packages/cli/clients/cli/commands/build-theme.variants.test.mjs
@@ -164,6 +164,7 @@ describe('theme build custom-variant augmentations', () => {
},
breadcrumbs: { 'variant:customBreadcrumbs': { color: 'currentColor' } },
button: { 'variant:customButton': { backgroundColor: 'transparent' } },
+ card: { 'variant:customCard': { backgroundColor: 'transparent' } },
dialog: { 'variant:customDialog': { backgroundColor: 'transparent' } },
divider: { 'variant:customDivider': { borderColor: 'currentColor' } },
'field-status': { 'variant:customFieldStatus': { color: 'currentColor' } },
@@ -204,6 +205,7 @@ describe('theme build custom-variant augmentations', () => {
`import {Banner} from '@astryxdesign/core/Banner';\n` +
`import {Breadcrumbs} from '@astryxdesign/core/Breadcrumbs';\n` +
`import {Button} from '@astryxdesign/core/Button';\n` +
+ `import {Card} from '@astryxdesign/core/Card';\n` +
`import {Dialog} from '@astryxdesign/core/Dialog';\n` +
`import {Divider} from '@astryxdesign/core/Divider';\n` +
`import {FieldStatus} from '@astryxdesign/core/FieldStatus';\n` +
@@ -222,6 +224,7 @@ describe('theme build custom-variant augmentations', () => {
` <Banner title="Banner" status="customBannerStatus" container="customBannerContainer" />\n` +
` <Breadcrumbs variant="customBreadcrumbs">Crumbs</Breadcrumbs>\n` +
` <Button label="Button" variant="customButton" />\n` +
+ ` <Card variant="customCard">Card</Card>\n` +
` <Dialog isOpen onOpenChange={() => {}} variant="customDialog">Body</Dialog>\n` +
` <Divider variant="customDivider" />\n` +
` <FieldStatus type="success" message="Ok" variant="customFieldStatus" />\n` +
diff --git a/packages/core/src/Card/Card.test.tsx b/packages/core/src/Card/Card.test.tsx
index 1e351004ed..30e9476c53 100644
--- a/packages/core/src/Card/Card.test.tsx
+++ b/packages/core/src/Card/Card.test.tsx
@@ -4,6 +4,7 @@ import {createRef} from 'react';
import {describe, it, expect} from 'vitest';
import {render} from '@testing-library/react';
import {Card} from './Card';
+import type {CardVariant} from './Card';
describe('Card', () => {
it('renders children', () => {
@@ -67,4 +68,72 @@ describe('Card', () => {
const classes = (['none', 'low', 'med', 'high'] as const).map(classFor);
expect(new Set(classes).size).toBe(4);
});
+
+ // Deriving the prop from CardVariantMap must not change which values it
+ // accepts. A key added to or dropped from the map fails to type-check here:
+ // a missing one against Record<CardVariant, true>, an extra one as an excess
+ // property.
+ const builtInVariants: Record<CardVariant, true> = {
+ default: true,
+ transparent: true,
+ muted: true,
+ blue: true,
+ cyan: true,
+ gray: true,
+ green: true,
+ orange: true,
+ pink: true,
+ purple: true,
+ red: true,
+ teal: true,
+ yellow: true,
+ };
+
+ it('accepts exactly the thirteen built-in variants, each reflected', () => {
+ const variants = Object.keys(builtInVariants) as CardVariant[];
+ expect(variants).toHaveLength(13);
+ for (const variant of variants) {
+ const {container} = render(<Card variant={variant}>C</Card>);
+ expect(container.firstElementChild).toHaveAttribute(
+ 'data-variant',
+ variant,
+ );
+ }
+ });
+
+ describe('a variant a theme added', () => {
+ // The cast stands in for the module augmentation `astryx theme build`
+ // emits; that the augmentation itself widens the prop is covered by
+ // packages/cli/clients/cli/commands/build-theme.variants.test.mjs.
+ const themeAdded = 'brand' as CardVariant;
+
+ const classesFor = (variant: CardVariant) => {
+ const {container} = render(<Card variant={variant}>C</Card>);
+ return new Set(container.firstElementChild!.className.split(' '));
+ };
+
+ it('renders the selector a theme rule needs', () => {
+ const {container} = render(<Card variant={themeAdded}>C</Card>);
+ const root = container.firstElementChild!;
+ expect(root).toHaveAttribute('data-variant', 'brand');
+ expect(root.className).toContain('astryx-card');
+ expect(root.className).toContain('brand');
+ });
+
+ it('falls through to base styles instead of another variant', () => {
+ const muted = classesFor('muted');
+ const blue = classesFor('blue');
+ const brand = classesFor(themeAdded);
+
+ const variantOwned = [
+ ...[...muted].filter(c => !blue.has(c)),
+ ...[...blue].filter(c => !muted.has(c)),
+ ];
+ const shared = [...muted].filter(c => blue.has(c));
+
+ expect(variantOwned.length).toBeGreaterThan(0);
+ expect(variantOwned.filter(c => brand.has(c))).toEqual([]);
+ expect(shared.filter(c => !brand.has(c))).toEqual([]);
+ });
+ });
});
diff --git a/packages/core/src/Card/Card.tsx b/packages/core/src/Card/Card.tsx
index 3d8094fa46..83f870c8ea 100644
--- a/packages/core/src/Card/Card.tsx
+++ b/packages/core/src/Card/Card.tsx
@@ -3,7 +3,7 @@
/**
* @file Card.tsx
* @input Uses container utility, StyleX
- * @output Exports Card component and CardProps
+ * @output Exports Card component, CardProps, CardVariant types
* @position Core card container component
*
* SYNC: When modified, update these files to stay in sync:
@@ -15,6 +15,7 @@
import type {ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
+import type {StyleXStyles} from '@stylexjs/stylex';
import {
borderVars,
colorVars,
@@ -28,13 +29,16 @@ import type {Elevation, SizeValue, SpacingStep} from '../utils/types';
import {mergeProps} from '../utils';
import type {BaseProps} from '../BaseProps';
import {themeProps} from '../utils/themeProps';
+import type {CardVariantMap} from './index';
// =============================================================================
// Variant type
// =============================================================================
/**
- * Background color variant for Card.
+ * Background color variant for Card, derived from CardVariantMap.
+ * Extensible via module augmentation of CardVariantMap.
+ *
* - `default`: standard card background with visible border
* - `transparent`: no background, no visible border — for grouping content without visual weight
* - `muted`: subtle muted background for de-emphasised cards
@@ -46,20 +50,7 @@ import {themeProps} from '../utils/themeProps';
* keeping content geometry faithful to the spacing scale and identical to the
* borderless variants. Themes can override borderWidth/borderColor.
*/
-export type CardVariant =
- | 'default'
- | 'transparent'
- | 'muted'
- | 'blue'
- | 'cyan'
- | 'gray'
- | 'green'
- | 'orange'
- | 'pink'
- | 'purple'
- | 'red'
- | 'teal'
- | 'yellow';
+export type CardVariant = keyof CardVariantMap;
// =============================================================================
// Styles
@@ -96,48 +87,53 @@ const styles = stylex.create({
},
});
-// Background variant styles — each maps to a design token
-const variantStyles = stylex.create({
- default: {
- backgroundColor: colorVars['--color-background-card'],
- },
- transparent: {
- backgroundColor: 'transparent',
- },
- muted: {
- backgroundColor: colorVars['--color-background-muted'],
- },
- blue: {
- backgroundColor: colorVars['--color-background-blue'],
- },
- cyan: {
- backgroundColor: colorVars['--color-background-cyan'],
- },
- gray: {
- backgroundColor: colorVars['--color-background-gray'],
- },
- green: {
- backgroundColor: colorVars['--color-background-green'],
+// Background variant styles — each maps to a design token. Typed as PARTIAL
+// over CardVariant: a theme can add a variant, and the record deliberately has
+// no entry for it, so the lookup is undefined, StyleX drops it, and the card
+// takes base styles for the theme rule to paint over.
+const variantStyles: Partial<Record<CardVariant, StyleXStyles>> = stylex.create(
+ {
+ default: {
+ backgroundColor: colorVars['--color-background-card'],
+ },
+ transparent: {
+ backgroundColor: 'transparent',
+ },
+ muted: {
+ backgroundColor: colorVars['--color-background-muted'],
+ },
+ blue: {
+ backgroundColor: colorVars['--color-background-blue'],
+ },
+ cyan: {
+ backgroundColor: colorVars['--color-background-cyan'],
+ },
+ gray: {
+ backgroundColor: colorVars['--color-background-gray'],
+ },
+ green: {
+ backgroundColor: colorVars['--color-background-green'],
+ },
+ orange: {
+ backgroundColor: colorVars['--color-background-orange'],
+ },
+ pink: {
+ backgroundColor: colorVars['--color-background-pink'],
+ },
+ purple: {
+ backgroundColor: colorVars['--color-background-purple'],
+ },
+ red: {
+ backgroundColor: colorVars['--color-background-red'],
+ },
+ teal: {
+ backgroundColor: colorVars['--color-background-teal'],
+ },
+ yellow: {
+ backgroundColor: colorVars['--color-background-yellow'],
+ },
},
- orange: {
- backgroundColor: colorVars['--color-background-orange'],
- },
- pink: {
- backgroundColor: colorVars['--color-background-pink'],
- },
- purple: {
- backgroundColor: colorVars['--color-background-purple'],
- },
- red: {
- backgroundColor: colorVars['--color-background-red'],
- },
- teal: {
- backgroundColor: colorVars['--color-background-teal'],
- },
- yellow: {
- backgroundColor: colorVars['--color-background-yellow'],
- },
-});
+);
// Elevation → shadow-token map. Sets the private --_card-elevation variable
// (not box-shadow directly) so it composes with --_card-ring in the shadow
@@ -295,6 +291,8 @@ export function Card({
themeProps('card', {variant, elevation}),
stylex.props(
styles.card,
+ // A theme's own variant is not a key here: the lookup is undefined,
+ // StyleX drops it, and the theme rule paints over base styles.
variantStyles[variant],
elevationStyles[elevation],
hasFixedHeight && styles.scrollable,
diff --git a/packages/core/src/Card/index.ts b/packages/core/src/Card/index.ts
index 9f98539452..cf30b0bcd2 100644
--- a/packages/core/src/Card/index.ts
+++ b/packages/core/src/Card/index.ts
@@ -3,11 +3,46 @@
/**
* @file index.ts
* @input Imports Card component
- * @output Exports Card component and types
+ * @output Exports Card, CardProps, CardVariant, CardVariantMap
* @position Entry point for @astryxdesign/core/Card module
*
* SYNC: When modified, update /packages/core/src/Card/Card.doc.mjs
*/
+/**
+ * Extensible variant map for Card.
+ *
+ * Theme packages can add custom variants via TypeScript module augmentation:
+ * @example
+ * ```
+ * declare module '@astryxdesign/core/Card' {
+ * interface CardVariantMap {
+ * 'brand': true;
+ * }
+ * }
+ * ```
+ *
+ * Pair the theme rule's `backgroundColor` with `--selectable-card-ring-color`.
+ * SelectableCard rings an added variant in that var, defaulting to the accent —
+ * no token the component could pick is guaranteed to contrast with a fill it
+ * cannot know, so the theme that supplied the fill picks the ring, in the same
+ * rule.
+ */
+export interface CardVariantMap {
+ default: true;
+ transparent: true;
+ muted: true;
+ blue: true;
+ cyan: true;
+ gray: true;
+ green: true;
+ orange: true;
+ pink: true;
+ purple: true;
+ red: true;
+ teal: true;
+ yellow: true;
+}
+
export {Card} from './Card';
export type {CardProps, CardVariant, SizeValue} from './Card';
diff --git a/packages/core/src/SelectableCard/SelectableCard.doc.mjs b/packages/core/src/SelectableCard/SelectableCard.doc.mjs
index c5770002be..49fe31583e 100644
--- a/packages/core/src/SelectableCard/SelectableCard.doc.mjs
+++ b/packages/core/src/SelectableCard/SelectableCard.doc.mjs
@@ -37,6 +37,9 @@ export const docs = {
theming: {
container: true,
targets: [{className: 'astryx-selectable-card', visualProps: ['selected', 'variant']}],
+ vars: [
+ {name: '--selectable-card-ring-color', description: 'Colour of the selection ring drawn for a variant a theme added. The built-in variants each ring in their own border token and ignore this; a theme that adds a variant sets it in the same rule as that variant\'s `backgroundColor`, because no token the component could pick is guaranteed to contrast with a fill it cannot know.', default: 'var(--color-accent)'},
+ ],
},
playground: {
defaults: {
diff --git a/packages/core/src/SelectableCard/SelectableCard.tsx b/packages/core/src/SelectableCard/SelectableCard.tsx
index 0efee6fb17..46aa72aa1f 100644
--- a/packages/core/src/SelectableCard/SelectableCard.tsx
+++ b/packages/core/src/SelectableCard/SelectableCard.tsx
@@ -55,6 +55,10 @@ import {useMergedRefs} from '../hooks/useMergedRefs';
const styles = stylex.create({
interactive: {
+ // Declared here, on the element that carries the `astryx-selectable-card`
+ // target, so a theme has something to override — the ring for a variant
+ // only the theme knows about reads it (see selectedUnknown).
+ '--selectable-card-ring-color': colorVars['--color-accent'],
position: 'relative',
cursor: {
default: 'pointer',
@@ -153,6 +157,14 @@ const styles = stylex.create({
borderColor: colorVars['--color-border-yellow'],
'--_card-ring': `inset 0 0 0 2px ${colorVars['--color-border-yellow']}`,
},
+ // A theme-added variant paints with colours the component cannot know, so no
+ // token is guaranteed to contrast with it — an accent ring disappears against
+ // an accent fill, and an outset one is no better. The theme that supplied the
+ // fill is the only thing that can pick a ring, so it gets a lever beside it;
+ // the var defaults to the accent, keeping every built-in unchanged.
+ selectedUnknown: {
+ '--_card-ring': 'inset 0 0 0 2px var(--selectable-card-ring-color)',
+ },
});
const selectedStyleForVariant = (variant: CardVariant) => {
@@ -181,6 +193,10 @@ const selectedStyleForVariant = (variant: CardVariant) => {
return styles.selectedTeal;
case 'yellow':
return styles.selectedYellow;
+ // CardVariant is open — a theme can add a variant this switch has never
+ // seen, and it still has to look selected.
+ default:
+ return styles.selectedUnknown;
}
};
diff --git a/packages/core/src/theme/derivedVarRegistry.test.ts b/packages/core/src/theme/derivedVarRegistry.test.ts
index dce0c7347b..ea5b0967ff 100644
--- a/packages/core/src/theme/derivedVarRegistry.test.ts
+++ b/packages/core/src/theme/derivedVarRegistry.test.ts
@@ -293,6 +293,10 @@ const VARS_WITHOUT_DERIVED_MAPPING = new Set([
// other.
'--_card-elevation',
'--_card-ring',
+ // The colour inside that composed ring, for a variant only a theme knows.
+ // It is one component of one shadow in the list, so no standard property
+ // maps onto it either — a theme sets it beside the fill it has to contrast.
+ '--selectable-card-ring-color',
]);
// ---------------------------------------------------------------------------