An open source design system that's fully customizable and agent ready
TypeScript
feat(docsite): add Overview/Playground tabs to component detail page (#1984)
Cindy Zhang57a6ff72fbf7
diff --git a/apps/docsite/src/app/components/[name]/page.tsx b/apps/docsite/src/app/components/[name]/page.tsxindex 801cfb5a67..f30326b993 100644--- a/apps/docsite/src/app/components/[name]/page.tsx+++ b/apps/docsite/src/app/components/[name]/page.tsx@@ -1,27 +1,14 @@/*** Component detail page.- * Adapts based on content:- * - Visual components: showcase + usage + anatomy + props + examples- * - Hooks/utilities: usage + params/returns + examples- * - Compound components: also lists sub-components with their props+ * Server component that resolves data, then delegates to ComponentDetailClient+ * which handles tabs (Overview / Playground) on the client.*/import {notFound} from 'next/navigation';-import {XDSHeading, XDSText} from '@xds/core/Text';-import {XDSVStack} from '@xds/core/Layout';-import {XDSSection} from '@xds/core/Section';-import {XDSCard} from '@xds/core/Card';-import {XDSCenter} from '@xds/core/Center';-import {XDSDivider} from '@xds/core';-import {XDSCodeBlock} from '@xds/core/CodeBlock';import {components} from '../../../generated/componentRegistry';import {blocks} from '../../../generated/blockRegistry';-import {PropsTable} from '../../../components/component-detail/PropsTable';-import {BestPractices} from '../../../components/component-detail/BestPractices';-import {Anatomy} from '../../../components/component-detail/Anatomy';-import {HookSignature} from '../../../components/component-detail/HookSignature';-import {ExampleBlock} from '../../../components/component-detail/ExampleBlock';-import {ShowcasePreview} from '../../../components/component-detail/ShowcasePreview';+import {packages} from '../../../generated/packageRegistry';+import {ComponentDetailClient} from '../../../components/component-detail/ComponentDetailClient';const allComponents = Object.values(components).flat();@@ -43,137 +30,20 @@ export default async function ComponentPage({comps.includes(comp),)?.[0];- const isHook = comp.params != null;+ const pkgVersion = packages.find(p => p.name === pkg)?.version;const componentBlocks = blocks.filter(b => b.exampleFor === name);const showcase = componentBlocks.find(b => b.isShowcase);const examples = componentBlocks.filter(b => !b.isShowcase);- const importPath = `import {${comp.moduleName}} from '${pkg}/${comp.directory}'`;-return (- <XDSSection- maxWidth={960}- padding={8}- variant="transparent"- style={{marginInline: 'auto'}}>- <XDSVStack gap={8}>- {/* Header */}- <XDSVStack gap={2}>- <XDSText type="display-1">{comp.moduleName}</XDSText>- <XDSText type="supporting" color="secondary">- {pkg} · {comp.directory}- </XDSText>- </XDSVStack>-- <XDSDivider />-- {/* Preview */}- <XDSCard variant="muted" padding={0}>- <XDSCenter height={360}>- <ShowcasePreview name={name} />- </XDSCenter>- </XDSCard>-- {/* Usage + Best Practices */}- {comp.usage && (- <XDSVStack gap={8}>- <XDSHeading level={2}>Usage</XDSHeading>- <XDSText type="large" weight="normal">- {comp.usage.description}- </XDSText>-- {comp.usage.bestPractices &&- comp.usage.bestPractices.length > 0 && (- <BestPractices practices={comp.usage.bestPractices} />- )}-- {comp.usage.anatomy && comp.usage.anatomy.length > 0 && (- <Anatomy elements={comp.usage.anatomy} />- )}- </XDSVStack>- )}-- {/* Hook params/returns */}- {isHook && comp.params && comp.returns && (- <HookSignature params={comp.params} returns={comp.returns} />- )}-- {/* Import */}- <XDSVStack gap={2}>- <XDSHeading level={3}>Import</XDSHeading>- <XDSCodeBlock code={importPath} language="ts" hasCopyButton />- </XDSVStack>-- {/* Props */}- {!isHook && comp.props.length > 0 && (- <XDSVStack gap={3}>- <XDSHeading level={2}>Props</XDSHeading>- <PropsTable props={comp.props} />- </XDSVStack>- )}-- {/* Sub-components */}- {subComponents.length > 0 && (- <>- <XDSDivider />- <XDSVStack gap={6}>- <XDSVStack gap={2}>- <XDSHeading level={2}>Sub-components</XDSHeading>- <XDSText type="large" weight="normal">- {comp.moduleName.replace(/^XDS/, '')} is a compound component- with {subComponents.length} sub-component- {subComponents.length === 1 ? '' : 's'}.- </XDSText>- </XDSVStack>- {subComponents.map(sub => (- <XDSVStack key={sub.name} gap={3}>- <XDSVStack gap={1}>- <XDSHeading level={3}>{sub.moduleName}</XDSHeading>- <XDSText type="body" color="secondary">- {sub.description}- </XDSText>- </XDSVStack>- {sub.props.length > 0 && <PropsTable props={sub.props} />}- </XDSVStack>- ))}- </XDSVStack>- </>- )}-- {/* Examples */}- {examples.length > 0 && (- <>- <XDSDivider />- <XDSVStack gap={6}>- <XDSHeading level={2}>Examples</XDSHeading>- <XDSText type="large" weight="normal">- Common configurations, variations, and states.- </XDSText>- </XDSVStack>- <XDSVStack gap={8}>- {examples.map(block => (- <ExampleBlock key={block.dirName} block={block} />- ))}- </XDSVStack>- </>- )}-- {/* Showcase source */}- {showcase && (- <>- <XDSDivider />- <XDSVStack gap={2}>- <XDSHeading level={3}>Showcase source</XDSHeading>- <XDSCodeBlock- code={showcase.source}- language="tsx"- hasCopyButton- />- </XDSVStack>- </>- )}- </XDSVStack>- </XDSSection>+ <ComponentDetailClient+ comp={comp}+ pkg={pkg}+ pkgVersion={pkgVersion}+ subComponents={subComponents}+ showcase={showcase}+ examples={examples}+ />);}diff --git a/apps/docsite/src/components/DocsShell.tsx b/apps/docsite/src/components/DocsShell.tsxindex d1c93a482d..209f55ad72 100644--- a/apps/docsite/src/components/DocsShell.tsx+++ b/apps/docsite/src/components/DocsShell.tsx@@ -204,7 +204,7 @@ export function DocsShell({<><XDSAppShellvariant="surface"- height="fill"+ height="auto"topNav={<XDSTopNavlabel="XDS navigation"diff --git a/apps/docsite/src/components/component-detail/ComponentDetailClient.tsx b/apps/docsite/src/components/component-detail/ComponentDetailClient.tsxnew file mode 100644index 0000000000..4094150f3b--- /dev/null+++ b/apps/docsite/src/components/component-detail/ComponentDetailClient.tsx@@ -0,0 +1,250 @@+'use client';++import {Suspense} from 'react';+import {useSearchParams, useRouter, usePathname} from 'next/navigation';+import {XDSHeading, XDSText} from '@xds/core/Text';+import {XDSVStack} from '@xds/core/Layout';+import {XDSSection} from '@xds/core/Section';+import {XDSCard} from '@xds/core/Card';+import {XDSDivider} from '@xds/core';+import {XDSCodeBlock} from '@xds/core/CodeBlock';+import {XDSTabList, XDSTab} from '@xds/core/TabList';+import {ShowcasePreview} from './ShowcasePreview';+import {BestPractices} from './BestPractices';+import {HookSignature} from './HookSignature';+import {ExampleBlock} from './ExampleBlock';+import {PropsTable} from './PropsTable';+import {+ InteractivePreviewStage,+ useInteractiveState,+} from './InteractivePreview';+import {PlaygroundPropsTable} from './PlaygroundPropsTable';+import type {ComponentEntry} from '../../generated/componentRegistry';+import type {BlockEntry} from '../../generated/blockRegistry';+import {showcaseRegistry} from '../../generated/showcaseRegistry';++interface ComponentDetailClientProps {+ comp: ComponentEntry;+ pkg: string | undefined;+ pkgVersion: string | undefined;+ subComponents: ComponentEntry[];+ showcase: BlockEntry | undefined;+ examples: BlockEntry[];+}++function OverviewContent({+ comp,+ pkg,+ subComponents,+ showcase,+ examples,+ hasShowcase,+}: ComponentDetailClientProps & {hasShowcase: boolean}) {+ const isHook = comp.params != null;+ const importPath = `import {${comp.moduleName}} from '${pkg}/${comp.directory}'`;++ return (+ <XDSVStack gap={8}>+ {hasShowcase && (+ <XDSCard variant="muted" padding={0}>+ <ShowcasePreview name={comp.name} />+ </XDSCard>+ )}++ {comp.usage && (+ <XDSVStack gap={6}>+ <XDSHeading level={2}>Usage</XDSHeading>+ <XDSText type="large" weight="normal">+ {comp.usage.description}+ </XDSText>++ <XDSCodeBlock code={importPath} language="ts" hasCopyButton />++ {comp.usage.bestPractices && comp.usage.bestPractices.length > 0 && (+ <BestPractices practices={comp.usage.bestPractices} />+ )}+ </XDSVStack>+ )}++ {isHook && comp.params && comp.returns && (+ <HookSignature params={comp.params} returns={comp.returns} />+ )}++ {subComponents.length > 0 && (+ <>+ <XDSDivider />+ <XDSVStack gap={6}>+ <XDSVStack gap={2}>+ <XDSHeading level={2}>Sub-components</XDSHeading>+ <XDSText type="large" weight="normal">+ {comp.moduleName.replace(/^XDS/, '')} is a compound component+ with {subComponents.length} sub-component+ {subComponents.length === 1 ? '' : 's'}.+ </XDSText>+ </XDSVStack>+ {subComponents.map(sub => (+ <XDSVStack key={sub.name} gap={3}>+ <XDSVStack gap={1}>+ <XDSHeading level={3}>{sub.moduleName}</XDSHeading>+ <XDSText type="body" color="secondary">+ {sub.description}+ </XDSText>+ </XDSVStack>+ {sub.props.length > 0 && <PropsTable props={sub.props} />}+ </XDSVStack>+ ))}+ </XDSVStack>+ </>+ )}++ {examples.length > 0 && (+ <>+ <XDSDivider />+ <XDSVStack gap={6}>+ <XDSHeading level={2}>Examples</XDSHeading>+ <XDSText type="large" weight="normal">+ Common configurations, variations, and states.+ </XDSText>+ </XDSVStack>+ <XDSVStack gap={8}>+ {examples.map(block => (+ <ExampleBlock key={block.dirName} block={block} />+ ))}+ </XDSVStack>+ </>+ )}++ {showcase && (+ <>+ <XDSDivider />+ <XDSVStack gap={2}>+ <XDSHeading level={3}>Showcase source</XDSHeading>+ <XDSCodeBlock code={showcase.source} language="tsx" hasCopyButton />+ </XDSVStack>+ </>+ )}+ </XDSVStack>+ );+}++function ComponentDetailInner({+ comp,+ pkg,+ pkgVersion,+ subComponents,+ showcase,+ examples,+}: ComponentDetailClientProps) {+ const searchParams = useSearchParams();+ const router = useRouter();+ const pathname = usePathname();++ const isHook = comp.params != null;+ const hasShowcase = comp.name in showcaseRegistry;+ const hasPlayground = !isHook;++ const tab = searchParams.get('tab') ?? 'overview';+ const setTab = (value: string) => {+ const params = new URLSearchParams(searchParams.toString());+ if (value === 'overview') {+ params.delete('tab');+ } else {+ params.set('tab', value);+ }+ const qs = params.toString();+ router.replace(`${pathname}${qs ? `?${qs}` : ''}`, {scroll: false});+ };++ const {knobs, state, setProp} = useInteractiveState(comp.name, comp.props);++ return (+ <XDSSection+ maxWidth={960}+ padding={4}+ variant="transparent"+ style={{marginInline: 'auto'}}>+ <XDSVStack gap={4}>+ <XDSVStack gap={2}>+ <XDSText type="display-1">{comp.name}</XDSText>+ <XDSText type="supporting" color="secondary">+ {pkg} · {comp.moduleName}+ {pkgVersion ? ` v${pkgVersion}` : ''}+ </XDSText>+ </XDSVStack>++ {hasPlayground ? (+ <>+ <XDSTabList value={tab} onChange={setTab} hasDivider>+ <XDSTab value="overview" label="Overview" />+ <XDSTab value="playground" label="Playground" />+ </XDSTabList>++ {tab === 'overview' && (+ <OverviewContent+ comp={comp}+ pkg={pkg}+ pkgVersion={pkgVersion}+ subComponents={subComponents}+ showcase={showcase}+ examples={examples}+ hasShowcase={hasShowcase}+ />+ )}++ {tab === 'playground' && (+ <XDSVStack gap={4}>+ <div+ style={{+ position: 'sticky',+ top: 44,+ zIndex: 10,+ backgroundColor: 'var(--color-background-page)',+ backdropFilter: 'blur(16px)',+ maxHeight: 400,+ overflow: 'auto',+ }}>+ <InteractivePreviewStage name={comp.name} state={state} />+ </div>++ {comp.props.length > 0 && (+ <XDSSection>+ <XDSVStack gap={3}>+ <XDSHeading level={3}>Props</XDSHeading>+ <PlaygroundPropsTable+ props={comp.props}+ knobs={knobs}+ state={state}+ onPropChange={setProp}+ />+ </XDSVStack>+ </XDSSection>+ )}+ </XDSVStack>+ )}+ </>+ ) : (+ <>+ <XDSDivider />+ <OverviewContent+ comp={comp}+ pkg={pkg}+ pkgVersion={pkgVersion}+ subComponents={subComponents}+ showcase={showcase}+ examples={examples}+ hasShowcase={hasShowcase}+ />+ </>+ )}+ </XDSVStack>+ </XDSSection>+ );+}++export function ComponentDetailClient(props: ComponentDetailClientProps) {+ return (+ <Suspense>+ <ComponentDetailInner {...props} />+ </Suspense>+ );+}diff --git a/apps/docsite/src/components/component-detail/InteractivePreview.tsx b/apps/docsite/src/components/component-detail/InteractivePreview.tsxnew file mode 100644index 0000000000..bd91f34002--- /dev/null+++ b/apps/docsite/src/components/component-detail/InteractivePreview.tsx@@ -0,0 +1,249 @@+'use client';++import {+ createElement,+ useMemo,+ useState,+ useCallback,+ type ComponentType,+ isValidElement,+ Component,+ type ReactNode,+} from 'react';+import * as XDSCore from '@xds/core';+import {XDSButton} from '@xds/core/Button';+import {XDSCard} from '@xds/core/Card';+import {XDSCenter} from '@xds/core/Center';+import {XDSCodeBlock} from '@xds/core/CodeBlock';+import {XDSVStack} from '@xds/core/Layout';+import {XDSText} from '@xds/core/Text';+import {CodeBracketIcon} from '@heroicons/react/24/outline';+import {+ coerceDefault,+ parsePropType,+ type PropControlDescriptor,+} from './parsePropType';+import type {PropDoc} from '../../generated/componentRegistry';++// eslint-disable-next-line @typescript-eslint/no-explicit-any+type AnyXDSComponent = ComponentType<any>;++function getXDSComponent(name: string): AnyXDSComponent | null {+ const key = `XDS${name}` as keyof typeof XDSCore;+ const value = XDSCore[key];+ return typeof value === 'function' ? (value as AnyXDSComponent) : null;+}++export interface KnobProp {+ row: PropDoc;+ control: PropControlDescriptor;+}++class PreviewErrorBoundary extends Component<+ {children: ReactNode; resetKeys: unknown[]},+ {error: Error | null}+> {+ state = {error: null as Error | null};+ static getDerivedStateFromError(error: Error) {+ return {error};+ }+ componentDidUpdate(prevProps: {resetKeys: unknown[]}) {+ if (+ this.state.error &&+ JSON.stringify(prevProps.resetKeys) !==+ JSON.stringify(this.props.resetKeys)+ ) {+ this.setState({error: null});+ }+ }+ render() {+ if (this.state.error) {+ return (+ <XDSText type="supporting" color="secondary">+ Render error: {this.state.error.message}+ </XDSText>+ );+ }+ return this.props.children;+ }+}++function pickPrimaryProps(name: string, props: PropDoc[]): KnobProp[] {+ if (props.length === 0) return [];+ return props.map(row => ({+ row,+ control: parsePropType(row.type, row.name),+ }));+}++function buildInitialState(knobs: KnobProp[]): Record<string, unknown> {+ const state: Record<string, unknown> = {};+ for (const {row, control} of knobs) {+ const def = coerceDefault(row.default, control);+ if (def !== undefined) {+ state[row.name] = def;+ } else if (row.required) {+ switch (control.kind) {+ case 'enum':+ state[row.name] = control.options[0];+ break;+ case 'boolean':+ state[row.name] = false;+ break;+ case 'string':+ state[row.name] = row.name;+ break;+ case 'number':+ state[row.name] = 0;+ break;+ }+ }+ }+ return state;+}++function formatValue(value: unknown): string {+ if (value === undefined) return 'undefined';+ if (value === null) return 'null';+ if (typeof value === 'string') return `"${value}"`;+ if (typeof value === 'boolean' || typeof value === 'number')+ return String(value);+ if (isValidElement(value)) {+ const el = value as React.ReactElement<Record<string, unknown>>;+ const type =+ typeof el.type === 'string'+ ? el.type+ : ((el.type as {displayName?: string}).displayName ??+ el.type.name ??+ 'Component');+ const props = el.props;+ if (!props || Object.keys(props).length === 0) return `<${type} />`;+ const propStr = Object.entries(props)+ .filter(([k]) => k !== 'children')+ .map(([k, v]) => {+ if (typeof v === 'string') return `${k}="${v}"`;+ return `${k}={${JSON.stringify(v)}}`;+ })+ .join(' ');+ return `<${type} ${propStr} />`;+ }+ return JSON.stringify(value);+}++function generateCode(name: string, state: Record<string, unknown>): string {+ const componentName = `XDS${name}`;+ const entries = Object.entries(state).filter(([, v]) => v !== undefined);++ if (entries.length === 0) return `<${componentName} />`;++ const propLines = entries.map(([key, value]) => {+ if (typeof value === 'boolean' && value === true) return ` ${key}`;+ if (typeof value === 'string') return ` ${key}="${value}"`;+ return ` ${key}={${formatValue(value)}}`;+ });++ return `<${componentName}\n${propLines.join('\n')}\n/>`;+}++export function useInteractiveState(name: string, props: PropDoc[]) {+ const knobs = useMemo(() => pickPrimaryProps(name, props), [name, props]);+ const initialState = useMemo(() => buildInitialState(knobs), [knobs]);+ const [state, setState] = useState<Record<string, unknown>>(initialState);++ const setProp = useCallback(+ (propName: string, value: unknown) =>+ setState(prev => ({...prev, [propName]: value})),+ [],+ );++ const reset = useCallback(() => setState(initialState), [initialState]);++ const isDirty = useMemo(+ () => JSON.stringify(state) !== JSON.stringify(initialState),+ [state, initialState],+ );++ return {knobs, state, setProp, reset, isDirty};+}++export function InteractivePreviewStage({+ name,+ state,+}: {+ name: string;+ state: Record<string, unknown>;+}) {+ const [showCode, setShowCode] = useState(false);+ const Component = getXDSComponent(name);++ if (!Component) {+ return (+ <XDSCard variant="muted" padding={0}>+ <XDSCenter style={{minHeight: 200, width: '100%'}}>+ <XDSVStack+ gap={1}+ style={{+ paddingBlock: 24,+ paddingInline: 16,+ textAlign: 'center',+ }}>+ <XDSText type="supporting" color="secondary">+ Interactive preview not available for {name}.+ </XDSText>+ <XDSText type="supporting" color="secondary">+ This component is not part of @xds/core.+ </XDSText>+ </XDSVStack>+ </XDSCenter>+ </XDSCard>+ );+ }++ const code = generateCode(name, state);++ return (+ <XDSCard+ variant="muted"+ padding={0}+ style={{width: '100%', position: 'relative'}}>+ <div+ style={{+ position: 'absolute',+ top: 'var(--spacing-2)',+ right: 'var(--spacing-2)',+ zIndex: 2,+ }}>+ <XDSButton+ label="Show code"+ tooltip="Show code"+ icon={<CodeBracketIcon width={16} height={16} />}+ isIconOnly+ variant={showCode ? 'secondary' : 'ghost'}+ size="sm"+ onClick={() => setShowCode(v => !v)}+ />+ </div>+ {showCode ? (+ <div+ style={{+ minHeight: 200,+ overflow: 'auto',+ padding: 'var(--spacing-4)',+ }}>+ <XDSCodeBlock code={code} language="tsx" hasCopyButton />+ </div>+ ) : (+ <XDSCenter+ style={{+ minHeight: 200,+ width: '100%',+ padding: 'var(--spacing-4)',+ }}>+ <PreviewErrorBoundary resetKeys={[Component, JSON.stringify(state)]}>+ {createElement(Component, state)}+ </PreviewErrorBoundary>+ </XDSCenter>+ )}+ </XDSCard>+ );+}diff --git a/apps/docsite/src/components/component-detail/PlaygroundPropsTable.tsx b/apps/docsite/src/components/component-detail/PlaygroundPropsTable.tsxnew file mode 100644index 0000000000..f65151554c--- /dev/null+++ b/apps/docsite/src/components/component-detail/PlaygroundPropsTable.tsx@@ -0,0 +1,291 @@+'use client';++import {createElement, useState} from 'react';+import {XDSHeading, XDSText} from '@xds/core/Text';+import {XDSHStack, XDSVStack} from '@xds/core/Layout';+import {XDSDivider} from '@xds/core';+import {XDSSwitch} from '@xds/core/Switch';+import {XDSTextInput} from '@xds/core/TextInput';+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 {useMediaQuery} from '@xds/core/hooks';+import type {PropControlDescriptor} from './parsePropType';+import type {KnobProp} from './InteractivePreview';+import type {PropDoc} from '../../generated/componentRegistry';++function formatType(type: string, defaultValue?: string): React.ReactNode {+ const parts = type.split(/\s*\|\s*/);+ const isEnum = parts.length > 1 && parts.every(p => /^['"]/.test(p.trim()));+ if (isEnum) {+ return (+ <>+ {parts.map((part, i) => {+ const trimmed = part.trim();+ const isDefault = defaultValue != null && trimmed === defaultValue;+ return (+ <span key={i}>+ {'| '}+ {isDefault ? <b>{trimmed}</b> : trimmed}+ {isDefault && ' (default)'}+ {i < parts.length - 1 && <br />}+ </span>+ );+ })}+ </>+ );+ }+ if (defaultValue != null) {+ return (+ <>+ {type} <span style={{opacity: 0.6}}>(default: {defaultValue})</span>+ </>+ );+ }+ return type;+}++function createDefaultElement(componentName: string): React.ReactNode {+ switch (componentName) {+ case 'XDSIcon':+ return createElement(XDSIcon, {icon: 'check', size: 'sm'});+ case 'XDSBadge':+ return createElement(XDSBadge, {label: 'Badge'});+ default:+ return null;+ }+}++function ElementControl({+ control,+ value,+ onChange,+}: {+ control: Extract<PropControlDescriptor, {kind: 'element'}>;+ value: unknown;+ onChange: (next: unknown) => void;+}) {+ const [selected, setSelected] = useState<string>('None');++ if (control.options.length === 1) {+ const opt = control.options[0];+ return (+ <XDSSwitch+ label={opt.label}+ value={value != null}+ onChange={on =>+ onChange(on ? createDefaultElement(opt.componentName) : undefined)+ }+ />+ );+ }++ return (+ <XDSSelector+ label=""+ placeholder="None"+ value={value != null ? selected : 'None'}+ options={['None', ...control.options.map(o => o.label)]}+ onChange={next => {+ setSelected(next);+ if (next === 'None' || next === '') {+ onChange(undefined);+ } else {+ const opt = control.options.find(o => o.label === next);+ if (opt) onChange(createDefaultElement(opt.componentName));+ }+ }}+ />+ );+}++function InlineControl({+ control,+ value,+ onChange,+}: {+ control: PropControlDescriptor;+ value: unknown;+ onChange: (next: unknown) => void;+}) {+ switch (control.kind) {+ case 'boolean':+ return (+ <XDSSwitch+ label=""+ value={value === true}+ onChange={next => onChange(next)}+ />+ );+ case 'enum': {+ const isNumeric = control.options.every(o => /^-?\d+(\.\d+)?$/.test(o));+ return (+ <XDSSelector+ label=""+ value={String(value ?? control.options[0])}+ options={control.options}+ onChange={next => onChange(isNumeric ? Number(next) : next)}+ />+ );+ }+ case 'string':+ return (+ <XDSTextInput+ label=""+ placeholder="value"+ value={typeof value === 'string' ? value : ''}+ onChange={next => onChange(next)}+ />+ );+ case 'number':+ return (+ <XDSNumberInput+ label=""+ value={typeof value === 'number' ? value : 0}+ onChange={next => onChange(next)}+ />+ );+ case 'element':+ return (+ <ElementControl control={control} value={value} onChange={onChange} />+ );+ default:+ return null;+ }+}++function PropRow({+ prop,+ knob,+ value,+ onChange,+ isMobile,+}: {+ prop: PropDoc;+ knob?: KnobProp;+ value?: unknown;+ onChange?: (next: unknown) => void;+ isMobile: boolean;+}) {+ if (isMobile) {+ return (+ <XDSVStack gap={2} style={{paddingBlock: 8}}>+ <XDSText type="body" weight="bold">+ {prop.name}+ </XDSText>+ <XDSText type="code" display="block">+ {formatType(prop.type, prop.default)}+ </XDSText>+ {prop.description != null && prop.description !== '' && (+ <XDSText type="body" color="secondary">+ {prop.description}+ </XDSText>+ )}+ {knob && onChange && (+ <InlineControl+ control={knob.control}+ value={value}+ onChange={onChange}+ />+ )}+ </XDSVStack>+ );+ }++ return (+ <XDSHStack gap={3} style={{paddingBlock: 6}}>+ <div style={{flexBasis: 200, flexShrink: 0}}>+ <XDSText type="body" weight="bold">+ {prop.name}+ </XDSText>+ </div>+ <div style={{flex: 1}}>+ <XDSText type="code" display="block">+ {formatType(prop.type, prop.default)}+ </XDSText>+ {prop.description != null && prop.description !== '' && (+ <XDSText type="body" color="secondary" style={{marginTop: 6}}>+ {prop.description}+ </XDSText>+ )}+ </div>+ {knob && onChange && (+ <div style={{flexBasis: 200, flexShrink: 0}}>+ <InlineControl+ control={knob.control}+ value={value}+ onChange={onChange}+ />+ </div>+ )}+ </XDSHStack>+ );+}++interface PlaygroundPropsTableProps {+ props: PropDoc[];+ knobs: KnobProp[];+ state: Record<string, unknown>;+ onPropChange: (name: string, value: unknown) => void;+}++export function PlaygroundPropsTable({+ props,+ knobs,+ state,+ onPropChange,+}: PlaygroundPropsTableProps) {+ const isMobile = useMediaQuery('(max-width: 768px)');+ const required = props.filter(p => p.required);+ const optional = props.filter(p => !p.required);++ const knobMap = new Map(knobs.map(k => [k.row.name, k]));++ return (+ <>+ {required.length > 0 && (+ <>+ <XDSHeading level={4} color="secondary">+ Required+ </XDSHeading>+ {required+ .toSorted((a, b) => a.name.localeCompare(b.name))+ .map(prop => (+ <div key={prop.name}>+ <XDSDivider />+ <PropRow+ prop={prop}+ knob={knobMap.get(prop.name)}+ value={state[prop.name]}+ onChange={next => onPropChange(prop.name, next)}+ isMobile={isMobile}+ />+ </div>+ ))}+ </>+ )}+ {optional.length > 0 && (+ <>+ <XDSHeading level={4} color="secondary" style={{marginTop: 8}}>+ Optional+ </XDSHeading>+ {optional+ .toSorted((a, b) => a.name.localeCompare(b.name))+ .map(prop => (+ <div key={prop.name}>+ <XDSDivider />+ <PropRow+ prop={prop}+ knob={knobMap.get(prop.name)}+ value={state[prop.name]}+ onChange={next => onPropChange(prop.name, next)}+ isMobile={isMobile}+ />+ </div>+ ))}+ </>+ )}+ </>+ );+}diff --git a/apps/docsite/src/components/component-detail/ShowcasePreview.tsx b/apps/docsite/src/components/component-detail/ShowcasePreview.tsxindex 4903394024..3c571debd6 100644--- a/apps/docsite/src/components/component-detail/ShowcasePreview.tsx+++ b/apps/docsite/src/components/component-detail/ShowcasePreview.tsx@@ -4,6 +4,7 @@ import {useEffect, useState, type ComponentType} from 'react';import {XDSCenter} from '@xds/core/Center';import {XDSText} from '@xds/core/Text';import {XDSSpinner} from '@xds/core/Spinner';+import {useMediaQuery} from '@xds/core/hooks';import {showcaseRegistry} from '../../generated/showcaseRegistry';interface ShowcasePreviewProps {@@ -13,6 +14,7 @@ interface ShowcasePreviewProps {export function ShowcasePreview({name}: ShowcasePreviewProps) {const [Component, setComponent] = useState<ComponentType | null>(null);const [error, setError] = useState(false);+ const isSmall = useMediaQuery('(max-width: 768px)');useEffect(() => {const loader = showcaseRegistry[name];@@ -25,9 +27,13 @@ export function ShowcasePreview({name}: ShowcasePreviewProps) {.catch(() => setError(true));}, [name]);+ const placeholderStyle = isSmall+ ? {minHeight: 160, width: '100%'}+ : {aspectRatio: '16 / 9', width: '100%'};+if (error) {return (- <XDSCenter height={360}>+ <XDSCenter style={placeholderStyle}><XDSText type="supporting" color="secondary">Preview not available</XDSText>@@ -37,11 +43,41 @@ export function ShowcasePreview({name}: ShowcasePreviewProps) {if (!Component) {return (- <XDSCenter height={360}>+ <XDSCenter style={placeholderStyle}><XDSSpinner size="md" /></XDSCenter>);}- return <Component />;+ if (isSmall) {+ return (+ <div+ style={{+ width: '100%',+ overflow: 'auto',+ minHeight: 160,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ }}>+ <div style={{minWidth: 'fit-content'}}>+ <Component />+ </div>+ </div>+ );+ }++ return (+ <div+ style={{+ width: '100%',+ aspectRatio: '16 / 9',+ overflow: 'auto',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ }}>+ <Component />+ </div>+ );}diff --git a/apps/docsite/src/components/component-detail/parsePropType.ts b/apps/docsite/src/components/component-detail/parsePropType.tsnew file mode 100644index 0000000000..0614c46719--- /dev/null+++ b/apps/docsite/src/components/component-detail/parsePropType.ts@@ -0,0 +1,214 @@+/**+ * Parses a stringified TypeScript prop type into a control descriptor+ * that the playground can render an input for.+ *+ * Ported from the internal docsite (nest/apps/xds).+ */++export interface ElementOption {+ label: string;+ componentName: string;+}++export type PropControlDescriptor =+ | {kind: 'enum'; options: string[]; allowEmpty: boolean}+ | {kind: 'boolean'}+ | {kind: 'string'}+ | {kind: 'number'}+ | {kind: 'callback'}+ | {kind: 'element'; options: ElementOption[]}+ | {kind: 'unknown'};++const STRING_LITERAL_RE = /^['"]([^'"]*)['"]$/;+const NUMBER_LITERAL_RE = /^-?\d+(\.\d+)?$/;+const CALLBACK_RE = /=>/;+const NODE_TYPE_RE = /\b(ReactNode|ReactElement|JSX\.Element|ReactChild)\b/;+const REACT_ELEMENT_RE = /ReactElement<(XDS\w+)Props>/g;++function splitUnion(input: string): string[] {+ const parts: string[] = [];+ let depth = 0;+ let start = 0;+ let inString: string | null = null;++ for (let i = 0; i < input.length; i++) {+ const c = input[i];++ if (inString) {+ if (c === inString && input[i - 1] !== '\\') inString = null;+ continue;+ }++ if (c === "'" || c === '"' || c === '`') {+ inString = c;+ continue;+ }++ if (c === '(' || c === '[' || c === '{' || c === '<') depth++;+ else if (c === ')' || c === ']' || c === '}' || c === '>') depth--;+ else if (c === '|' && depth === 0) {+ parts.push(input.slice(start, i).trim());+ start = i + 1;+ }+ }++ parts.push(input.slice(start).trim());+ return parts.filter(p => p.length > 0);+}++export function parsePropType(+ typeStr: string,+ propName?: string,+): PropControlDescriptor {+ const t = typeStr.trim();+ if (!t) return {kind: 'unknown'};++ if (CALLBACK_RE.test(t)) return {kind: 'callback'};++ if (t === 'boolean') return {kind: 'boolean'};+ if (t === 'string') return {kind: 'string'};+ if (t === 'number') return {kind: 'number'};++ if (t === 'SpacingStep') {+ return {+ kind: 'enum',+ options: ['0', '0.5', '1', '1.5', '2', '3', '4', '5', '6', '8', '10'],+ allowEmpty: false,+ };+ }+ if (t === 'SizeValue') return {kind: 'number'};+ if (t === 'XDSIconType' || t === 'XDSIconName') {+ return {+ kind: 'enum',+ options: [+ 'check',+ 'close',+ 'info',+ 'warning',+ 'search',+ 'calendar',+ 'clock',+ 'chevronDown',+ 'chevronLeft',+ 'chevronRight',+ 'checkCircle',+ 'xCircle',+ 'externalLink',+ 'menu',+ 'moreHorizontal',+ 'copy',+ 'wrench',+ 'arrowUp',+ 'arrowDown',+ 'eyeSlash',+ ],+ allowEmpty: true,+ };+ }+ if (t === 'XDSInputStatus') {+ return {+ kind: 'enum',+ options: ['default', 'error', 'warning', 'success'],+ allowEmpty: false,+ };+ }+ if (t === 'XDSAppShellBreakpoint') {+ return {+ kind: 'enum',+ options: ['sm', 'md', 'lg', 'none'],+ allowEmpty: false,+ };+ }++ const elementMatches: ElementOption[] = [];+ let m;+ REACT_ELEMENT_RE.lastIndex = 0;+ while ((m = REACT_ELEMENT_RE.exec(t)) !== null) {+ const componentName = m[1];+ elementMatches.push({+ label: componentName.replace(/^XDS/, ''),+ componentName,+ });+ }+ if (elementMatches.length > 0) {+ return {kind: 'element', options: elementMatches};+ }++ if (NODE_TYPE_RE.test(t)) {+ const isIconProp =+ propName != null &&+ /^(icon|startIcon|endIcon|leftIcon|rightIcon)$/i.test(propName);+ if (isIconProp) {+ return {+ kind: 'element',+ options: [{label: 'Icon', componentName: 'XDSIcon'}],+ };+ }+ return {kind: 'string'};+ }++ const parts = splitUnion(t);+ const literals: string[] = [];+ let allowEmpty = false;+ let onlyLiterals = true;++ for (const part of parts) {+ if (part === 'undefined' || part === 'null') {+ allowEmpty = true;+ continue;+ }+ const sm = STRING_LITERAL_RE.exec(part);+ if (sm) {+ literals.push(sm[1]);+ } else if (NUMBER_LITERAL_RE.test(part)) {+ literals.push(part);+ } else {+ onlyLiterals = false;+ break;+ }+ }++ if (onlyLiterals && literals.length >= 2) {+ return {kind: 'enum', options: literals, allowEmpty};+ }++ if (+ onlyLiterals === false &&+ parts.every(p => p === 'true' || p === 'false')+ ) {+ return {kind: 'boolean'};+ }++ return {kind: 'unknown'};+}++export function coerceDefault(+ raw: string | undefined,+ control: PropControlDescriptor,+): unknown {+ if (raw == null) return undefined;+ const v = raw.trim();+ if (!v) return undefined;++ switch (control.kind) {+ case 'boolean':+ return v === 'true';+ case 'number': {+ const n = Number(v);+ return Number.isFinite(n) ? n : undefined;+ }+ case 'enum': {+ const m = STRING_LITERAL_RE.exec(v);+ const stripped = m ? m[1] : v;+ return control.options.includes(stripped) ? stripped : undefined;+ }+ case 'string': {+ const m = STRING_LITERAL_RE.exec(v);+ return m ? m[1] : v;+ }+ case 'element':+ return undefined;+ default:+ return undefined;+ }+}