Skip to content

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

TypeScript

feat(docsite): playground defaults and slotElements for ReactNode props (#2005)

Cindy Zhang8390d0991b9a
diff --git a/apps/docsite/scripts/generate-data.mjs b/apps/docsite/scripts/generate-data.mjs
index 555163fc4d..c33cedf61b 100644
--- a/apps/docsite/scripts/generate-data.mjs
+++ b/apps/docsite/scripts/generate-data.mjs
@@ -230,6 +230,7 @@ async function generateComponentRegistry() {
const topDescription = doc.usage?.description || doc.description || '';
const usage = doc.usage ? sanitizeForJson(doc.usage) : null;
const theming = doc.theming ? sanitizeForJson(doc.theming) : null;
+ const playground = doc.playground ? sanitizeForJson(doc.playground) : null;
if (doc.components && doc.components.length > 0) {
for (const sub of doc.components) {
@@ -251,6 +252,7 @@ async function generateComponentRegistry() {
returns: null,
relatedComponents: null,
relatedHooks: null,
+ playground,
});
}
} else if (doc.params) {
@@ -273,6 +275,7 @@ async function generateComponentRegistry() {
returns: Array.isArray(doc.returns) ? sanitizeForJson(doc.returns) : [],
relatedComponents: doc.relatedComponents || null,
relatedHooks: doc.relatedHooks || null,
+ playground: null,
});
} else {
// Simple/standalone component
@@ -294,6 +297,7 @@ async function generateComponentRegistry() {
returns: null,
relatedComponents: null,
relatedHooks: null,
+ playground,
});
}
}
@@ -321,8 +325,8 @@ export interface PropDoc {
description: string;
default?: string;
required?: boolean;
+ slotElements?: ElementDescriptor[];
}
-
export interface BestPractice {
guidance: boolean;
description: string;
@@ -402,6 +406,17 @@ export interface ComponentEntry {
returns: HookReturnDoc[] | null;
relatedComponents: string[] | null;
relatedHooks: string[] | null;
+ playground: PlaygroundConfig | null;
+}
+
+export interface ElementDescriptor {
+ __element: string;
+ props?: Record<string, unknown>;
+ children?: string | ElementDescriptor | (string | ElementDescriptor)[];
+}
+
+export interface PlaygroundConfig {
+ defaults: Record<string, unknown>;
}
export const components: Record<string, ComponentEntry[]> = ${JSON.stringify(allComponents, null, 2)};
diff --git a/apps/docsite/src/components/component-detail/ComponentDetailClient.tsx b/apps/docsite/src/components/component-detail/ComponentDetailClient.tsx
index 6741bce8a0..102b868a72 100644
--- a/apps/docsite/src/components/component-detail/ComponentDetailClient.tsx
+++ b/apps/docsite/src/components/component-detail/ComponentDetailClient.tsx
@@ -143,7 +143,11 @@ function ComponentDetailInner({
router.replace(`${pathname}${qs ? `?${qs}` : ''}`, {scroll: false});
};
- const {knobs, state, setProp} = useInteractiveState(comp.name, comp.props);
+ const {knobs, state, setProp} = useInteractiveState(
+ comp.name,
+ comp.props,
+ comp.playground,
+ );
return (
<XDSSection
diff --git a/apps/docsite/src/components/component-detail/InteractivePreview.tsx b/apps/docsite/src/components/component-detail/InteractivePreview.tsx
index bd91f34002..361ac47bff 100644
--- a/apps/docsite/src/components/component-detail/InteractivePreview.tsx
+++ b/apps/docsite/src/components/component-detail/InteractivePreview.tsx
@@ -23,7 +23,42 @@ import {
parsePropType,
type PropControlDescriptor,
} from './parsePropType';
-import type {PropDoc} from '../../generated/componentRegistry';
+import type {
+ PropDoc,
+ PlaygroundConfig,
+ ElementDescriptor,
+} from '../../generated/componentRegistry';
+
+function isElementDescriptor(v: unknown): v is ElementDescriptor {
+ return v != null && typeof v === 'object' && '__element' in v;
+}
+
+function resolveElementDescriptor(desc: ElementDescriptor): React.ReactNode {
+ const Comp = getXDSComponent(desc.__element.replace(/^XDS/, ''));
+ const tag = Comp ?? desc.__element;
+
+ let children: React.ReactNode = undefined;
+ if (desc.children != null) {
+ if (typeof desc.children === 'string') {
+ children = desc.children;
+ } else if (Array.isArray(desc.children)) {
+ children = desc.children.map((c, i) =>
+ typeof c === 'string'
+ ? c
+ : createElement('span', {key: i}, resolveElementDescriptor(c)),
+ );
+ } else {
+ children = resolveElementDescriptor(desc.children);
+ }
+ }
+
+ return createElement(tag, desc.props ?? {}, children);
+}
+
+function resolveValue(v: unknown): unknown {
+ if (isElementDescriptor(v)) return resolveElementDescriptor(v);
+ return v;
+}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type AnyXDSComponent = ComponentType<any>;
@@ -72,13 +107,26 @@ function pickPrimaryProps(name: string, props: PropDoc[]): KnobProp[] {
if (props.length === 0) return [];
return props.map(row => ({
row,
- control: parsePropType(row.type, row.name),
+ control: parsePropType(row.type, row.name, row.slotElements),
}));
}
-function buildInitialState(knobs: KnobProp[]): Record<string, unknown> {
+function buildInitialState(
+ knobs: KnobProp[],
+ playground?: PlaygroundConfig | null,
+): Record<string, unknown> {
const state: Record<string, unknown> = {};
+
+ // Apply playground defaults first (resolved from ElementDescriptor if needed)
+ if (playground?.defaults) {
+ for (const [key, value] of Object.entries(playground.defaults)) {
+ state[key] = resolveValue(value);
+ }
+ }
+
+ // Fill in remaining props from doc defaults / auto-generation
for (const {row, control} of knobs) {
+ if (state[row.name] !== undefined) continue;
const def = coerceDefault(row.default, control);
if (def !== undefined) {
state[row.name] = def;
@@ -145,9 +193,16 @@ function generateCode(name: string, state: Record<string, unknown>): string {
return `<${componentName}\n${propLines.join('\n')}\n/>`;
}
-export function useInteractiveState(name: string, props: PropDoc[]) {
+export function useInteractiveState(
+ name: string,
+ props: PropDoc[],
+ playground?: PlaygroundConfig | null,
+) {
const knobs = useMemo(() => pickPrimaryProps(name, props), [name, props]);
- const initialState = useMemo(() => buildInitialState(knobs), [knobs]);
+ const initialState = useMemo(
+ () => buildInitialState(knobs, playground),
+ [knobs, playground],
+ );
const [state, setState] = useState<Record<string, unknown>>(initialState);
const setProp = useCallback(
diff --git a/apps/docsite/src/components/component-detail/PlaygroundPropsTable.tsx b/apps/docsite/src/components/component-detail/PlaygroundPropsTable.tsx
index f65151554c..a342d7e953 100644
--- a/apps/docsite/src/components/component-detail/PlaygroundPropsTable.tsx
+++ b/apps/docsite/src/components/component-detail/PlaygroundPropsTable.tsx
@@ -10,6 +10,7 @@ import {XDSNumberInput} from '@xds/core/NumberInput';
import {XDSSelector} from '@xds/core/Selector';
import {XDSIcon} from '@xds/core/Icon';
import {XDSBadge} from '@xds/core/Badge';
+import * as XDSCore from '@xds/core';
import {useMediaQuery} from '@xds/core/hooks';
import type {PropControlDescriptor} from './parsePropType';
import type {KnobProp} from './InteractivePreview';
@@ -46,7 +47,21 @@ function formatType(type: string, defaultValue?: string): React.ReactNode {
return type;
}
-function createDefaultElement(componentName: string): React.ReactNode {
+function resolveSlotElement(
+ componentName: string,
+ slotElements?: Array<{__element: string; props?: Record<string, unknown>}>,
+): React.ReactNode {
+ // If we have slotElements metadata, use the matching one
+ if (slotElements) {
+ const match = slotElements.find(el => el.__element === componentName);
+ if (match) {
+ const key = match.__element.replace(/^XDS/, '') as keyof typeof XDSCore;
+ const Comp = typeof XDSCore[key] === 'function' ? XDSCore[key] : null;
+ if (Comp)
+ return createElement(Comp as React.ComponentType, match.props ?? {});
+ }
+ }
+ // Fallback to hardcoded defaults
switch (componentName) {
case 'XDSIcon':
return createElement(XDSIcon, {icon: 'check', size: 'sm'});
@@ -61,10 +76,12 @@ function ElementControl({
control,
value,
onChange,
+ prop,
}: {
control: Extract<PropControlDescriptor, {kind: 'element'}>;
value: unknown;
onChange: (next: unknown) => void;
+ prop: PropDoc;
}) {
const [selected, setSelected] = useState<string>('None');
@@ -75,7 +92,11 @@ function ElementControl({
label={opt.label}
value={value != null}
onChange={on =>
- onChange(on ? createDefaultElement(opt.componentName) : undefined)
+ onChange(
+ on
+ ? resolveSlotElement(opt.componentName, prop.slotElements)
+ : undefined,
+ )
}
/>
);
@@ -93,7 +114,8 @@ function ElementControl({
onChange(undefined);
} else {
const opt = control.options.find(o => o.label === next);
- if (opt) onChange(createDefaultElement(opt.componentName));
+ if (opt)
+ onChange(resolveSlotElement(opt.componentName, prop.slotElements));
}
}}
/>
@@ -104,10 +126,12 @@ function InlineControl({
control,
value,
onChange,
+ prop,
}: {
control: PropControlDescriptor;
value: unknown;
onChange: (next: unknown) => void;
+ prop: PropDoc;
}) {
switch (control.kind) {
case 'boolean':
@@ -148,7 +172,12 @@ function InlineControl({
);
case 'element':
return (
- <ElementControl control={control} value={value} onChange={onChange} />
+ <ElementControl
+ control={control}
+ value={value}
+ onChange={onChange}
+ prop={prop}
+ />
);
default:
return null;
@@ -187,6 +216,7 @@ function PropRow({
control={knob.control}
value={value}
onChange={onChange}
+ prop={prop}
/>
)}
</XDSVStack>
@@ -216,6 +246,7 @@ function PropRow({
control={knob.control}
value={value}
onChange={onChange}
+ prop={prop}
/>
</div>
)}
diff --git a/apps/docsite/src/components/component-detail/parsePropType.ts b/apps/docsite/src/components/component-detail/parsePropType.ts
index 0614c46719..1eaa9315d9 100644
--- a/apps/docsite/src/components/component-detail/parsePropType.ts
+++ b/apps/docsite/src/components/component-detail/parsePropType.ts
@@ -59,10 +59,22 @@ function splitUnion(input: string): string[] {
export function parsePropType(
typeStr: string,
propName?: string,
+ slotElements?: Array<{__element: string; props?: Record<string, unknown>}>,
): PropControlDescriptor {
const t = typeStr.trim();
if (!t) return {kind: 'unknown'};
+ // If slotElements is declared, use it directly for the element control
+ if (slotElements && slotElements.length > 0) {
+ return {
+ kind: 'element',
+ options: slotElements.map(el => ({
+ label: el.__element.replace(/^XDS/, ''),
+ componentName: el.__element,
+ })),
+ };
+ }
+
if (CALLBACK_RE.test(t)) return {kind: 'callback'};
if (t === 'boolean') return {kind: 'boolean'};
diff --git a/packages/core/src/Badge/Badge.doc.mjs b/packages/core/src/Badge/Badge.doc.mjs
index f6779cc2fb..3fc837f358 100644
--- a/packages/core/src/Badge/Badge.doc.mjs
+++ b/packages/core/src/Badge/Badge.doc.mjs
@@ -22,6 +22,12 @@ export const docs = {
description: 'Optional leading icon.',
},
],
+ playground: {
+ defaults: {
+ label: 'Badge',
+ variant: 'neutral',
+ },
+ },
theming: {
targets: [
{className: 'xds-badge', visualProps: ['variant']},
diff --git a/packages/core/src/Button/Button.doc.mjs b/packages/core/src/Button/Button.doc.mjs
index 503f8e1170..afffb08049 100644
--- a/packages/core/src/Button/Button.doc.mjs
+++ b/packages/core/src/Button/Button.doc.mjs
@@ -84,6 +84,7 @@ export const docs = {
type: 'ReactNode',
description:
'Icon element rendered before the label text.',
+ slotElements: [{__element: 'XDSIcon', props: {icon: 'check', size: 'sm'}}],
},
{
name: 'isIconOnly',
@@ -103,6 +104,10 @@ export const docs = {
type: 'ReactElement<XDSIconProps> | ReactElement<XDSBadgeProps>',
description:
'Trailing icon or badge rendered after the label. Ignored when isIconOnly is true. Color is inherited from the button variant.',
+ slotElements: [
+ {__element: 'XDSIcon', props: {icon: 'chevronDown', size: 'sm'}},
+ {__element: 'XDSBadge', props: {label: '3'}},
+ ],
},
{
name: 'tooltip',
@@ -122,6 +127,12 @@ export const docs = {
'Async click handler. Shows loading state while the returned promise is pending.',
},
],
+ playground: {
+ defaults: {
+ label: 'Click me',
+ variant: 'primary',
+ },
+ },
theming: {
targets: [
{className: 'xds-button', visualProps: ['size', 'variant']},
diff --git a/packages/core/src/Card/Card.doc.mjs b/packages/core/src/Card/Card.doc.mjs
index e092ac72fa..f5025f5465 100644
--- a/packages/core/src/Card/Card.doc.mjs
+++ b/packages/core/src/Card/Card.doc.mjs
@@ -60,6 +60,19 @@ export const docs = {
default: "'default'",
},
],
+ playground: {
+ defaults: {
+ padding: 4,
+ children: {
+ __element: 'XDSVStack',
+ props: {gap: 2},
+ children: [
+ {__element: 'XDSHeading', props: {level: 3}, children: 'Card Title'},
+ {__element: 'XDSText', props: {type: 'body'}, children: 'Card content goes here. This is a standard card with a heading and body text.'},
+ ],
+ },
+ },
+ },
theming: {
container: true,
targets: [
diff --git a/packages/core/src/EmptyState/EmptyState.doc.mjs b/packages/core/src/EmptyState/EmptyState.doc.mjs
index 0549754b76..d47ad90365 100644
--- a/packages/core/src/EmptyState/EmptyState.doc.mjs
+++ b/packages/core/src/EmptyState/EmptyState.doc.mjs
@@ -50,6 +50,13 @@ export const docs = {
'StyleX styles for layout customization (margins, positioning, sizing). Must be a stylex.create() value — not an inline style object like style={{}}.',
},
],
+ playground: {
+ defaults: {
+ title: 'No results found',
+ description: 'Try adjusting your search or filter criteria.',
+ actions: {__element: 'XDSButton', props: {label: 'Clear filters', variant: 'secondary'}},
+ },
+ },
theming: {
targets: [
{className: 'xds-emptystate'},
diff --git a/packages/core/src/docs-types.ts b/packages/core/src/docs-types.ts
index 140e35ddf0..c9499e1535 100644
--- a/packages/core/src/docs-types.ts
+++ b/packages/core/src/docs-types.ts
@@ -45,6 +45,29 @@ export interface PropDoc {
default?: string;
/** True if the prop must be provided. Omit (don't set to false) if optional. */
required?: boolean;
+ /** For ReactNode props: the XDS components this slot typically accepts.
+ * Each entry is an ElementDescriptor that the playground uses to
+ * create a default instance when the user toggles the slot on.
+ *
+ * Single-element slots (icon, endContent) have one option with a toggle.
+ * Multi-element slots (children on List) can have options the user picks from.
+ *
+ * The playground uses this instead of hardcoded component→control mappings.
+ * Omit for ReactNode props that accept plain text (label, description).
+ *
+ * @example
+ * ```
+ * // Single option — renders as a toggle switch
+ * slotElements: [{__element: 'XDSIcon', props: {icon: 'check', size: 'sm'}}]
+ *
+ * // Multiple options — renders as a selector
+ * slotElements: [
+ * {__element: 'XDSIcon', props: {icon: 'check', size: 'sm'}},
+ * {__element: 'XDSBadge', props: {label: 'Badge'}},
+ * ]
+ * ```
+ */
+ slotElements?: ElementDescriptor[];
}
/**
@@ -254,6 +277,85 @@ export interface UsageDoc {
anatomy?: AnatomyElement[];
}
+/**
+ * A serializable descriptor for a React element. The playground resolves
+ * these at runtime via `createElement(XDSCore[component], props, ...children)`.
+ *
+ * Use this for any prop value that needs to be a React element —
+ * children slots, icon props, endContent, etc.
+ *
+ * @example
+ * ```
+ * // Simple element
+ * {__element: 'XDSIcon', props: {icon: 'check', size: 'sm'}}
+ *
+ * // Element with text children
+ * {__element: 'XDSText', props: {type: 'body'}, children: 'Hello world'}
+ *
+ * // Nested composition
+ * {__element: 'XDSVStack', props: {gap: 2}, children: [
+ * {__element: 'XDSHeading', props: {level: 3}, children: 'Title'},
+ * {__element: 'XDSText', props: {}, children: 'Body text'},
+ * ]}
+ * ```
+ */
+export interface ElementDescriptor {
+ /** Marker field — presence distinguishes this from a plain object prop value. */
+ __element: string;
+ /** Props passed to createElement. Omit or use {} for no props. */
+ props?: Record<string, unknown>;
+ /** Children — a string, another ElementDescriptor, or an array of them. */
+ children?: string | ElementDescriptor | (string | ElementDescriptor)[];
+}
+
+/**
+ * Playground configuration for the interactive component preview.
+ *
+ * `defaults` provides the initial prop state for the playground. Every key
+ * maps to a prop name, and the value is either:
+ * - A **primitive** (string, number, boolean) — used directly as the prop value
+ * - An **ElementDescriptor** — resolved to a React element via createElement
+ *
+ * Props not listed in `defaults` fall back to the standard logic:
+ * doc `default` values, then auto-generated values for required props.
+ *
+ * @example
+ * ```
+ * // Button — just override the label
+ * playground: {
+ * defaults: {label: 'Click me', variant: 'primary'},
+ * }
+ *
+ * // Card — provide children content
+ * playground: {
+ * defaults: {
+ * padding: 4,
+ * children: {
+ * __element: 'XDSVStack', props: {gap: 2}, children: [
+ * {__element: 'XDSHeading', props: {level: 3}, children: 'Card Title'},
+ * {__element: 'XDSText', props: {type: 'body'}, children: 'Card content goes here.'},
+ * ],
+ * },
+ * },
+ * }
+ *
+ * // Dialog — provide structured children
+ * playground: {
+ * defaults: {
+ * isOpen: true,
+ * isInline: true,
+ * onOpenChange: undefined,
+ * children: {__element: 'XDSText', props: {type: 'body'}, children: 'Dialog content'},
+ * },
+ * }
+ * ```
+ */
+export interface PlaygroundConfig {
+ /** Initial prop values for the playground preview.
+ * Keys are prop names. Values are primitives or ElementDescriptors. */
+ defaults: Record<string, unknown>;
+}
+
/**
* Shared fields between single-component and multi-component docs.
* Do not use this interface directly — use `ComponentDoc` (the union type).
@@ -310,6 +412,10 @@ interface BaseDoc {
/** Component usage documentation — concise summary, best practices,
* and optional visual anatomy. */
usage: UsageDoc;
+
+ /** Playground configuration. Controls how the interactive preview
+ * renders this component with sensible defaults and slot content. */
+ playground?: PlaygroundConfig;
}
/**