Skip to content

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

TypeScript

docs(docsite): add theming targets and CSS vars to component page (#4537)

Cindy Zhangf306f13a8f64
diff --git a/apps/docsite/src/__tests__/theming-helpers.test.ts b/apps/docsite/src/__tests__/theming-helpers.test.ts
new file mode 100644
index 0000000000..9fb679822e
--- /dev/null
+++ b/apps/docsite/src/__tests__/theming-helpers.test.ts
@@ -0,0 +1,149 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {readFileSync} from 'node:fs';
+import {dirname, join} from 'node:path';
+import {fileURLToPath} from 'node:url';
+import {describe, expect, it} from 'vitest';
+import type {PropDoc, ThemingDoc} from '../generated/componentRegistry';
+import {
+ configKey,
+ dataAttrForName,
+ targetDataAttributes,
+ targetPropValues,
+ buildDefineThemeExample,
+ publicVars,
+} from '../components/component-detail/themingHelpers';
+
+describe('theming helpers — configKey', () => {
+ it('strips the astryx- namespace prefix', () => {
+ expect(configKey({className: 'astryx-button'})).toBe('button');
+ expect(configKey({className: 'astryx-banner-icon'})).toBe('banner-icon');
+ });
+
+ it('leaves a non-prefixed class untouched', () => {
+ expect(configKey({className: 'custom-thing'})).toBe('custom-thing');
+ });
+});
+
+describe('theming helpers — data attributes', () => {
+ it('kebab-cases camelCase names', () => {
+ expect(dataAttrForName('listStyle')).toBe('data-list-style');
+ expect(dataAttrForName('variant')).toBe('data-variant');
+ });
+
+ it('reflects both visual props and states', () => {
+ expect(
+ targetDataAttributes({
+ className: 'astryx-checkbox',
+ visualProps: ['size'],
+ states: ['checked', 'disabled'],
+ }),
+ ).toEqual(['data-size', 'data-checked', 'data-disabled']);
+ });
+});
+
+describe('theming helpers — targetPropValues', () => {
+ const variantProp: PropDoc = {
+ name: 'variant',
+ type: "'primary' | 'secondary' | 'ghost'",
+ description: '',
+ };
+
+ it('expands variant to its literal values', () => {
+ expect(
+ targetPropValues({className: 'astryx-button', visualProps: ['variant']}, [
+ variantProp,
+ ]),
+ ).toEqual(['primary', 'secondary', 'ghost']);
+ });
+
+ it('lists non-variant visual props as-is', () => {
+ expect(
+ targetPropValues(
+ {className: 'astryx-banner', visualProps: ['container', 'status']},
+ [],
+ ),
+ ).toEqual(['container', 'status']);
+ });
+
+ it('returns empty when there are no visual props', () => {
+ expect(targetPropValues({className: 'astryx-card'}, [])).toEqual([]);
+ });
+});
+
+describe('theming helpers — buildDefineThemeExample', () => {
+ it('emits a components block keyed by config key with base + prop', () => {
+ const theming: ThemingDoc = {
+ targets: [{className: 'astryx-button', visualProps: ['variant', 'size']}],
+ };
+ const example = buildDefineThemeExample(theming);
+ expect(example).toContain('components: {');
+ expect(example).toContain("'button': {");
+ expect(example).toContain('base: {');
+ expect(example).toContain("'variant:value': {");
+ });
+
+ it('adds a second sub-element target when present', () => {
+ const theming: ThemingDoc = {
+ targets: [
+ {className: 'astryx-banner'},
+ {className: 'astryx-banner-icon', states: ['status']},
+ ],
+ };
+ const example = buildDefineThemeExample(theming);
+ expect(example).toContain("'banner': {");
+ expect(example).toContain("'banner-icon': {");
+ expect(example).toContain("'status': {");
+ });
+
+ it('returns empty string with no targets', () => {
+ expect(buildDefineThemeExample({targets: []})).toBe('');
+ });
+});
+
+describe('theming helpers — publicVars', () => {
+ it('hides private and derived vars', () => {
+ const theming: ThemingDoc = {
+ targets: [],
+ vars: [
+ {name: '--button-focus-offset', description: 'x', default: '3px'},
+ {
+ name: '--_button-radius',
+ description: 'y',
+ default: 'var(--radius-element)',
+ private: true,
+ },
+ {
+ name: '--card-concentric-radius',
+ description: 'z',
+ default: '0px',
+ derived: true,
+ },
+ ],
+ };
+ const vars = publicVars(theming);
+ expect(vars.map(v => v.name)).toEqual(['--button-focus-offset']);
+ });
+
+ it('returns empty when a component exposes no vars', () => {
+ expect(publicVars({targets: []})).toEqual([]);
+ });
+});
+
+describe('theming section — canary gating', () => {
+ const source = readFileSync(
+ join(
+ dirname(fileURLToPath(import.meta.url)),
+ '../components/component-detail/Theming.tsx',
+ ),
+ 'utf8',
+ );
+
+ it('renders the section only on canary builds', () => {
+ expect(source).toContain("CURRENT_TARGET !== 'canary'");
+ });
+
+ it('shows an experimental notice about the theming API', () => {
+ expect(source).toMatch(/theming API is experimental/i);
+ });
+});
diff --git a/apps/docsite/src/components/component-detail/ComponentDetailClient.tsx b/apps/docsite/src/components/component-detail/ComponentDetailClient.tsx
index b7f6bc15f5..45ac50fae2 100644
--- a/apps/docsite/src/components/component-detail/ComponentDetailClient.tsx
+++ b/apps/docsite/src/components/component-detail/ComponentDetailClient.tsx
@@ -16,6 +16,7 @@ import {TabList, Tab} from '@astryxdesign/core/TabList';
import {ShowcasePreview} from './ShowcasePreview';
import {ComponentPreviewTheme} from './ComponentPreviewTheme';
import {BestPractices} from './BestPractices';
+import {Theming} from './Theming';
import {HookSignature} from './HookSignature';
import {ExampleBlock} from './ExampleBlock';
import {MarkdownText} from '../MarkdownText';
@@ -118,6 +119,10 @@ function OverviewContent({
<PropsTable props={comp.props} heading="Props" />
)}
+ {!isHook && comp.theming && (
+ <Theming theming={comp.theming} props={comp.props} />
+ )}
+
{(exampleRegistry[comp.name] || []).length > 0 && (
<>
<VStack gap={4}>
diff --git a/apps/docsite/src/components/component-detail/Theming.tsx b/apps/docsite/src/components/component-detail/Theming.tsx
new file mode 100644
index 0000000000..29f4abd361
--- /dev/null
+++ b/apps/docsite/src/components/component-detail/Theming.tsx
@@ -0,0 +1,327 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file Theming.tsx
+ * @input A component's `theming` doc (targets, vars, derived) + its props.
+ * @output Renders the component detail page's "Theming" section: a table of
+ * theme targets shown as the keys they take in a `defineTheme` `components`
+ * config, a copyable `defineTheme` example, and a table of themeable CSS
+ * variables.
+ * @position Component detail Overview; sibling to PropsTable / BestPractices.
+ *
+ * Data shaping lives in ./themingHelpers (unit-tested); this file is the view.
+ */
+
+import {Fragment} from 'react';
+import {Heading, Text} from '@astryxdesign/core/Text';
+import {VStack} from '@astryxdesign/core/Layout';
+import {Section} from '@astryxdesign/core/Section';
+import {Table, pixel} from '@astryxdesign/core/Table';
+import {Banner} from '@astryxdesign/core/Banner';
+import {useMediaQuery} from '@astryxdesign/core/hooks';
+import {Divider} from '@astryxdesign/core';
+import {CodeExampleBlock} from '../CodeExampleBlock';
+import {MarkdownText} from '../MarkdownText';
+import {CURRENT_TARGET} from '../../lib/docsVersions';
+import type {
+ PropDoc,
+ ThemingDoc,
+ ThemingTarget,
+ ComponentVar,
+} from '../../generated/componentRegistry';
+import {
+ configKey,
+ targetDataAttributes,
+ targetPropValues,
+ buildDefineThemeExample,
+ publicVars,
+} from './themingHelpers';
+
+interface TargetsTableProps {
+ targets: ThemingTarget[];
+ props: PropDoc[];
+}
+
+function TargetsTable({targets, props}: TargetsTableProps) {
+ const isMobile = useMediaQuery('(max-width: 768px)');
+
+ if (isMobile) {
+ return (
+ <VStack gap={0}>
+ {targets.map(target => {
+ const dataAttrs = targetDataAttributes(target);
+ const propValues = targetPropValues(target, props);
+ const states = target.states ?? [];
+ return (
+ <Fragment key={target.className}>
+ <Divider />
+ <VStack gap={1} style={{paddingBlock: 8}}>
+ <Text type="code" weight="bold">
+ {configKey(target)}
+ </Text>
+ <Text type="code" color="secondary">
+ .{target.className}
+ </Text>
+ {dataAttrs.length > 0 && (
+ <Text type="supporting" color="secondary">
+ Data attrs: {dataAttrs.map(a => `[${a}]`).join(', ')}
+ </Text>
+ )}
+ {propValues.length > 0 && (
+ <Text type="supporting" color="secondary">
+ Props: {propValues.join(', ')}
+ </Text>
+ )}
+ {states.length > 0 && (
+ <Text type="supporting" color="secondary">
+ States: {states.join(', ')}
+ </Text>
+ )}
+ </VStack>
+ </Fragment>
+ );
+ })}
+ </VStack>
+ );
+ }
+
+ const data = targets.map(target => ({
+ key: configKey(target) as unknown,
+ className: target.className as unknown,
+ dataAttrs: targetDataAttributes(target) as unknown,
+ props: targetPropValues(target, props) as unknown,
+ states: (target.states ?? []) as unknown,
+ })) as Record<string, unknown>[];
+
+ return (
+ <Table
+ data={data}
+ columns={[
+ {
+ key: 'key',
+ header: 'Config key',
+ width: pixel(180),
+ renderCell: (item: Record<string, unknown>) => (
+ <Text type="code" weight="bold" style={{whiteSpace: 'nowrap'}}>
+ {item.key as string}
+ </Text>
+ ),
+ },
+ {
+ key: 'className',
+ header: 'Class',
+ width: pixel(200),
+ renderCell: (item: Record<string, unknown>) => (
+ <Text type="code" color="secondary" style={{whiteSpace: 'nowrap'}}>
+ .{item.className as string}
+ </Text>
+ ),
+ },
+ {
+ key: 'dataAttrs',
+ header: 'Data attributes',
+ width: pixel(220),
+ renderCell: (item: Record<string, unknown>) => {
+ const attrs = item.dataAttrs as string[];
+ return attrs.length > 0 ? (
+ <Text type="code" color="secondary">
+ {attrs.map(a => `[${a}]`).join(', ')}
+ </Text>
+ ) : (
+ <Text color="secondary">—</Text>
+ );
+ },
+ },
+ {
+ key: 'props',
+ header: 'Props',
+ renderCell: (item: Record<string, unknown>) => {
+ const values = item.props as string[];
+ return values.length > 0 ? (
+ <Text type="code" color="secondary">
+ {values.join(', ')}
+ </Text>
+ ) : (
+ <Text color="secondary">—</Text>
+ );
+ },
+ },
+ {
+ key: 'states',
+ header: 'States',
+ renderCell: (item: Record<string, unknown>) => {
+ const values = item.states as string[];
+ return values.length > 0 ? (
+ <Text type="code" color="secondary">
+ {values.join(', ')}
+ </Text>
+ ) : (
+ <Text color="secondary">—</Text>
+ );
+ },
+ },
+ ]}
+ density="spacious"
+ dividers="rows"
+ />
+ );
+}
+
+interface CssVarsTableProps {
+ vars: ComponentVar[];
+}
+
+function CssVarsTable({vars}: CssVarsTableProps) {
+ const isMobile = useMediaQuery('(max-width: 768px)');
+
+ if (isMobile) {
+ return (
+ <VStack gap={0}>
+ {vars.map(v => (
+ <Fragment key={v.name}>
+ <Divider />
+ <VStack gap={1} style={{paddingBlock: 8}}>
+ <Text type="code" weight="bold">
+ {v.name}
+ </Text>
+ <Text type="code" color="secondary">
+ {v.default}
+ </Text>
+ {v.description && (
+ <MarkdownText type="body" color="secondary">
+ {v.description}
+ </MarkdownText>
+ )}
+ </VStack>
+ </Fragment>
+ ))}
+ </VStack>
+ );
+ }
+
+ const data = vars.map(v => ({
+ name: v.name as unknown,
+ default: v.default as unknown,
+ description: (v.description ?? '') as unknown,
+ })) as Record<string, unknown>[];
+
+ return (
+ <Table
+ data={data}
+ columns={[
+ {
+ key: 'name',
+ header: 'CSS variable',
+ width: pixel(240),
+ renderCell: (item: Record<string, unknown>) => (
+ <Text type="code" weight="bold" style={{whiteSpace: 'nowrap'}}>
+ {item.name as string}
+ </Text>
+ ),
+ },
+ {
+ key: 'default',
+ header: 'Default',
+ width: pixel(220),
+ renderCell: (item: Record<string, unknown>) => (
+ <Text type="code" color="secondary">
+ {item.default as string}
+ </Text>
+ ),
+ },
+ {
+ key: 'description',
+ header: 'Description',
+ renderCell: (item: Record<string, unknown>) => (
+ <MarkdownText type="body">
+ {item.description as string}
+ </MarkdownText>
+ ),
+ },
+ ]}
+ density="spacious"
+ dividers="rows"
+ />
+ );
+}
+
+interface ThemingProps {
+ theming: ThemingDoc;
+ props: PropDoc[];
+}
+
+export function Theming({theming, props}: ThemingProps) {
+ // Canary-only while the theming API is hardened. Production (`latest`) hides
+ // the section entirely rather than documenting an unstable contract.
+ if (CURRENT_TARGET !== 'canary') {
+ return null;
+ }
+
+ const hasTargets = theming.targets.length > 0;
+ const vars = publicVars(theming);
+ const hasVars = vars.length > 0;
+
+ if (!hasTargets && !hasVars) {
+ return null;
+ }
+
+ const example = hasTargets ? buildDefineThemeExample(theming) : '';
+
+ return (
+ <Section>
+ <VStack gap={4}>
+ <VStack gap={2}>
+ <Heading level={2} type="display-3">
+ Theming
+ </Heading>
+ <Banner
+ container="card"
+ status="warning"
+ title="Experimental"
+ description="The theming API is experimental and not yet guaranteed — targets, keys, and CSS variables may change while we harden the theme system."
+ />
+ <Text type="large" weight="normal">
+ Restyle this component with a <Text type="code">defineTheme</Text>{' '}
+ config. Target the component through the keys below, or override the
+ CSS variables it exposes.
+ </Text>
+ </VStack>
+
+ {hasTargets && (
+ <VStack gap={3}>
+ <Heading level={3}>Theme targets</Heading>
+ <Text color="secondary">
+ Each target is a key in the <Text type="code">components</Text>{' '}
+ map of <Text type="code">defineTheme</Text>. Scope styles to a
+ prop or state with a <Text type="code">prop:value</Text> or state
+ key; use <Text type="code">base</Text> for all instances.
+ </Text>
+ <TargetsTable targets={theming.targets} props={props} />
+ {example && (
+ <CodeExampleBlock
+ code={example}
+ language="ts"
+ width="100%"
+ hasCopyButton
+ />
+ )}
+ </VStack>
+ )}
+
+ {hasVars && (
+ <VStack gap={3}>
+ <Heading level={3}>Themeable CSS variables</Heading>
+ <Text color="secondary">
+ Additional custom properties this component reads. Override them
+ in a <Text type="code">base</Text> block of the component's{' '}
+ <Text type="code">defineTheme</Text> config.
+ </Text>
+ <CssVarsTable vars={vars} />
+ </VStack>
+ )}
+ </VStack>
+ </Section>
+ );
+}
diff --git a/apps/docsite/src/components/component-detail/themingHelpers.ts b/apps/docsite/src/components/component-detail/themingHelpers.ts
new file mode 100644
index 0000000000..065a540806
--- /dev/null
+++ b/apps/docsite/src/components/component-detail/themingHelpers.ts
@@ -0,0 +1,119 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file themingHelpers.ts
+ * @input A component's `theming` doc (targets, vars, derived) and its props.
+ * @output Pure helpers that shape theming data for the component-detail
+ * Theming section — deriving `defineTheme` config keys, reflected data
+ * attributes, prop-value lists, the copyable config example, and the set of
+ * publicly-settable CSS variables.
+ * @position Consumed by Theming.tsx; kept separate so the logic is unit-testable
+ * without rendering React.
+ *
+ * Mirrors the theming output of the CLI (`packages/cli/lib/component-format.mjs`)
+ * so the docsite and `astryx component <Name>` present the same contract.
+ */
+
+import type {
+ PropDoc,
+ ThemingDoc,
+ ThemingTarget,
+ ComponentVar,
+} from '../../generated/componentRegistry';
+
+const NAMESPACE_PREFIX = 'astryx-';
+
+/**
+ * The key a target takes inside a `defineTheme` `components` config — the
+ * stable class name with the `astryx-` namespace stripped. `astryx-button` →
+ * `button`, `astryx-banner-icon` → `banner-icon`. Kept in sync with the CLI's
+ * `targetKey` (packages/cli/lib/component-format.mjs) and `generateThemeRules`,
+ * which re-adds the prefix when building the `.astryx-*` selector.
+ */
+export function configKey(target: ThemingTarget): string {
+ return target.className.startsWith(NAMESPACE_PREFIX)
+ ? target.className.slice(NAMESPACE_PREFIX.length)
+ : target.className;
+}
+
+/** Kebab-case a visual-prop/state name into its reflected `data-*` attribute. */
+export function dataAttrForName(name: string): string {
+ return `data-${name.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase()}`;
+}
+
+/** All `data-*` attributes reflected on a target, from visual props + states. */
+export function targetDataAttributes(target: ThemingTarget): string[] {
+ return [
+ ...(target.visualProps ?? []).map(dataAttrForName),
+ ...(target.states ?? []).map(dataAttrForName),
+ ];
+}
+
+/**
+ * Resolve the display values for a target's props column. When `variant` is a
+ * visual prop, expand it to the actual literal values from the component's
+ * `variant` prop type (`'primary' | 'secondary'` → `primary, secondary`);
+ * otherwise list the visual prop names as-is (`size`, `orientation`, …).
+ */
+export function targetPropValues(
+ target: ThemingTarget,
+ props: PropDoc[],
+): string[] {
+ if (!target.visualProps?.length) {
+ return [];
+ }
+ if (target.visualProps.includes('variant')) {
+ const variantProp = props.find(p => p.name === 'variant');
+ if (variantProp && variantProp.type.includes('|')) {
+ return variantProp.type
+ .replace(/['"]/g, '')
+ .split('|')
+ .map(v => v.trim())
+ .filter(Boolean);
+ }
+ }
+ return target.visualProps;
+}
+
+/**
+ * Build the `defineTheme` `components` example, showing the root target's
+ * `base` + a representative prop/state key, plus one sub-element target if the
+ * component exposes more than one. Mirrors the CLI's generated snippet.
+ */
+export function buildDefineThemeExample(theming: ThemingDoc): string {
+ const targets = theming.targets;
+ if (!targets.length) {
+ return '';
+ }
+
+ const lines: string[] = ['components: {'];
+
+ const root = targets[0];
+ lines.push(` '${configKey(root)}': {`);
+ lines.push(` base: { /* CSS properties */ },`);
+ if (root.visualProps?.length) {
+ lines.push(` '${root.visualProps[0]}:value': { /* prop-specific */ },`);
+ }
+ if (root.states?.length) {
+ lines.push(` '${root.states[0]}': { /* state-specific */ },`);
+ }
+ lines.push(` },`);
+
+ if (targets.length > 1) {
+ const sub = targets[1];
+ lines.push(` '${configKey(sub)}': {`);
+ lines.push(` base: { /* CSS properties */ },`);
+ if (sub.states?.length) {
+ lines.push(` '${sub.states[0]}': { /* state-specific */ },`);
+ }
+ lines.push(` },`);
+ }
+
+ lines.push('}');
+ return lines.join('\n');
+}
+
+/** Public, directly-settable vars — private + derived vars are hidden. */
+export function publicVars(theming: ThemingDoc): ComponentVar[] {
+ return (theming.vars ?? []).filter(v => !v.private && !v.derived);
+}