An open source design system that's fully customizable and agent ready
TypeScript
feat(sandbox): refine DocPreview typography, color, and motion (#1847)
Cindy Zhangee5f0e9974b3
diff --git a/apps/sandbox/src/app/(sandbox)/pages/doc-preview/DocPreview.tsx b/apps/sandbox/src/app/(sandbox)/pages/doc-preview/DocPreview.tsxindex e6f0fef97f..ce130d241f 100644--- a/apps/sandbox/src/app/(sandbox)/pages/doc-preview/DocPreview.tsx+++ b/apps/sandbox/src/app/(sandbox)/pages/doc-preview/DocPreview.tsx@@ -1,23 +1,21 @@'use client';-import {useMemo, useRef, useEffect, useState} from 'react';+import {useMemo} from 'react';import * as stylex from '@stylexjs/stylex';-import {XDSVStack, XDSHStack} from '@xds/core/Layout';-import {XDSText, XDSHeading} from '@xds/core/Text';-import {XDSCodeBlock} from '@xds/core/CodeBlock';-import {XDSBadge} from '@xds/core/Badge';-import {XDSCard} from '@xds/core/Card';+import {XDSVStack} from '@xds/core/Layout';+import {XDSText} from '@xds/core/Text';import {XDSDivider} from '@xds/core/Divider';-import {XDSSection} from '@xds/core/Section';-import {XDSTable, pixel, proportional} from '@xds/core/Table';-import {XDSTooltip} from '@xds/core/Tooltip';-import {useXDSTheme} from '@xds/core/theme';-import type {- ReferenceDoc,- ReferenceSection,- ContentBlock,- TokenPreviewType,-} from '@xds/core';+import type {XDSDefinedTheme} from '@xds/core/theme';+import type {ReferenceDoc, ReferenceSection} from '@xds/core';+import {SectionRenderer} from './SectionRenderer';+import {+ ColorTokenTable,+ SpacingTokenTable,+ TypographyTokenTable,+ ElevationTokenTable,+ ShapeTokenTable,+ MotionTokenTable,+} from './token-tables';// =============================================================================// Styles@@ -29,907 +27,116 @@ const styles = stylex.create({margin: '0 auto',padding: 32,},- sectionTitle: {- scrollMarginTop: 80,- },- tokenTable: {- width: '100%',- borderCollapse: 'collapse',- fontSize: 13,- },- th: {- textAlign: 'start',- fontWeight: 600,- fontSize: 12,- paddingBlock: 12,- paddingInline: 16,- borderBottom: '1px solid var(--color-border)',- color: 'var(--color-text-secondary)',- textTransform: 'uppercase' as const,- letterSpacing: '0.04em',- },- td: {- paddingBlock: 12,- paddingInline: 16,- borderBottom: '1px solid var(--color-border)',- verticalAlign: 'middle',- fontFamily: 'var(--font-family-code)',- fontSize: 12,- },- tokenRow: {- borderRadius: 8,- transition: 'background-color 0.15s ease',- ':hover': {- backgroundColor: 'var(--color-background-wash)',- },- },- tokenName: {- fontWeight: 500,- color: 'var(--color-text-primary)',- whiteSpace: 'nowrap' as const,- },- tokenLink: {- cursor: 'pointer',- color: 'var(--color-text-primary)',- textDecoration: {- default: 'none',- ':hover': 'underline',- },- background: 'none',- border: 'none',- padding: 0,- fontFamily: 'var(--font-family-code)',- fontSize: 12,- fontWeight: 500,- },- tokenValue: {- color: 'var(--color-text-secondary)',- maxWidth: 320,- overflow: 'hidden',- textOverflow: 'ellipsis',- whiteSpace: 'nowrap' as const,- },- valueWithPreview: {- display: 'flex',- alignItems: 'center',- gap: 8,- },- typeScalePreview: {- overflow: 'hidden',- whiteSpace: 'nowrap' as const,- textOverflow: 'ellipsis',- display: 'block',- fontFamily: 'inherit',- },- tokenDetail: {- display: 'flex',- flexDirection: 'column' as const,- gap: 2,- },- tokenDetailName: {- fontFamily: 'var(--font-family-code)',- fontSize: 11,- fontWeight: 500,- color: 'var(--color-text-primary)',- whiteSpace: 'nowrap' as const,- },- tokenDetailValue: {- fontFamily: 'var(--font-family-code)',- fontSize: 11,- color: 'var(--color-text-secondary)',- whiteSpace: 'nowrap' as const,- },- listItem: {- paddingBlock: 2,- color: 'var(--color-text-primary)',- fontSize: 14,- lineHeight: 1.5,- },- fullWidth: {- width: '100%',- },- codeBlockEmbed: {- width: '100%',- },- prose: {- fontSize: 14,- lineHeight: 1.6,- color: 'var(--color-text-primary)',- },version: {fontFamily: 'var(--font-family-code)',},});// =============================================================================-// Token Preview Renderers-// =============================================================================--function SwatchPreview({value}: {value: string}) {- return (- <div- style={{- width: 28,- height: 28,- borderRadius: 6,- backgroundColor: value,- border: '1px solid var(--color-border)',- flexShrink: 0,- }}- />- );-}--function ShadowBoxPreview({value}: {value: string}) {- return (- <div- style={{- width: 32,- height: 24,- borderRadius: 6,- backgroundColor: 'var(--color-background-surface)',- boxShadow: value,- flexShrink: 0,- }}- />- );-}--function RadiusBoxPreview({value}: {value: string}) {- return (- <div- style={{- width: 28,- height: 28,- borderRadius: value,- border: '2px solid var(--color-accent)',- flexShrink: 0,- }}- />- );-}--function SpacingBarPreview({value}: {value: string}) {- return (- <div- style={{- width: value,- minWidth: 2,- maxWidth: 64,- height: 12,- borderRadius: 2,- backgroundColor: 'var(--color-accent)',- opacity: 0.6,- flexShrink: 0,- }}- />- );-}--function SizeBarPreview({value}: {value: string}) {- return (- <div- style={{- height: value,- width: 40,- maxHeight: 48,- borderRadius: 4,- backgroundColor: 'var(--color-accent-muted)',- border: '1px solid var(--color-accent)',- flexShrink: 0,- }}- />- );-}--function BorderLinePreview({value}: {value: string}) {- return (- <div- style={{- width: 32,- height: 0,- borderBottom: `${value} solid var(--color-border-emphasized)`,- flexShrink: 0,- }}- />- );-}--function DurationBarPreview({value}: {value: string}) {- const ref = useRef<HTMLDivElement>(null);- const [animate, setAnimate] = useState(false);-- useEffect(() => {- const interval = setInterval(() => setAnimate(a => !a), 2000);- return () => clearInterval(interval);- }, []);-- return (- <div- style={{- width: 40,- height: 8,- borderRadius: 4,- backgroundColor: 'var(--color-neutral)',- overflow: 'hidden',- flexShrink: 0,- }}>- <div- ref={ref}- style={{- width: animate ? '100%' : '0%',- height: '100%',- borderRadius: 4,- backgroundColor: 'var(--color-accent)',- transition: `width ${value} ease`,- }}- />- </div>- );-}--function EasingCurvePreview({value}: {value: string}) {- // Parse cubic-bezier values and draw a mini SVG curve- const match = value.match(- /cubic-bezier\(\s*([\d.]+)\s*,\s*([-\d.]+)\s*,\s*([\d.]+)\s*,\s*([-\d.]+)\s*\)/,- );- if (!match) return null;- const [, x1, y1, x2, y2] = match.map(Number);- return (- <svg width={32} height={24} viewBox="0 0 1 1" style={{flexShrink: 0}}>- <path- d={`M 0 1 C ${x1} ${1 - y1}, ${x2} ${1 - y2}, 1 0`}- fill="none"- stroke="var(--color-accent)"- strokeWidth={0.06}- />- </svg>- );-}--function FontSamplePreview({- tokenName,- value,-}: {- tokenName: string;- value: string;-}) {- const style: React.CSSProperties = {- flexShrink: 0,- whiteSpace: 'nowrap',- maxWidth: 120,- overflow: 'hidden',- textOverflow: 'ellipsis',- };-- if (tokenName.includes('font-family')) {- return <span style={{...style, fontFamily: value, fontSize: 13}}>Aa</span>;- }- if (tokenName.includes('font-size')) {- return <span style={{...style, fontSize: value}}>Aa</span>;- }- if (tokenName.includes('font-weight')) {- return <span style={{...style, fontWeight: value, fontSize: 13}}>Aa</span>;- }- if (tokenName.includes('text-') && tokenName.includes('-size')) {- return <span style={{...style, fontSize: value}}>Aa</span>;- }- if (tokenName.includes('text-') && tokenName.includes('-weight')) {- return <span style={{...style, fontWeight: value, fontSize: 13}}>Aa</span>;- }- return <span style={{...style, fontSize: 13}}>Aa</span>;-}--function TokenPreview({- type,- tokenName,- value,-}: {- type: TokenPreviewType;- tokenName: string;- value: string;-}) {- switch (type) {- case 'swatch':- return <SwatchPreview value={value} />;- case 'shadow-box':- return <ShadowBoxPreview value={value} />;- case 'radius-box':- return <RadiusBoxPreview value={value} />;- case 'spacing-bar':- return <SpacingBarPreview value={value} />;- case 'size-bar':- return <SizeBarPreview value={value} />;- case 'border-line':- return <BorderLinePreview value={value} />;- case 'duration-bar':- return <DurationBarPreview value={value} />;- case 'easing-curve':- return <EasingCurvePreview value={value} />;- case 'font-sample':- return <FontSamplePreview tokenName={tokenName} value={value} />;- default:- return null;- }-}--// =============================================================================-// Typescale Table+// Token table routing// =============================================================================-const FONT_FAMILY_MAP: Record<string, string> = {- 'heading-1': '--font-family-heading',- 'heading-2': '--font-family-heading',- 'heading-3': '--font-family-heading',- 'heading-4': '--font-family-heading',- 'heading-5': '--font-family-heading',- 'heading-6': '--font-family-heading',- 'body': '--font-family-body',- 'large': '--font-family-body',- 'label': '--font-family-body',- 'supporting': '--font-family-body',- 'code': '--font-family-code',- 'display-1': '--font-family-heading',- 'display-2': '--font-family-heading',- 'display-3': '--font-family-heading',-};--const STYLE_LABEL: Record<string, string> = {- 'display-1': 'Display 1',- 'display-2': 'Display 2',- 'display-3': 'Display 3',- 'heading-1': 'H1',- 'heading-2': 'H2',- 'heading-3': 'H3',- 'heading-4': 'H4',- 'heading-5': 'H5',- 'heading-6': 'H6',- 'body': 'Body',- 'large': 'Large',- 'label': 'Label',- 'code': 'Code',- 'supporting': 'Supporting',+const TOKEN_TABLE_BY_CATEGORY: Record<+ string,+ React.ComponentType<{theme: XDSDefinedTheme}>+> = {+ color: ColorTokenTable,+ spacing: SpacingTokenTable,+ typography: TypographyTokenTable,+ shadow: ElevationTokenTable,+ radius: ShapeTokenTable,+ duration: MotionTokenTable,+ easing: MotionTokenTable,+ motion: MotionTokenTable,};-const DUMMY_TEXT: Record<string, string> = {- 'display-1': '$12,450',- 'display-2': '98.7%',- 'display-3': 'Welcome',- 'heading-1': 'Page Title',- 'heading-2': 'Section Title',- 'heading-3': 'Card Heading',- 'heading-4': 'Subsection',- 'heading-5': 'Group Label',- 'heading-6': 'Overline',- 'body': 'Body text for reading',- 'large': 'Intro paragraph',- 'label': 'Form Label',- 'code': 'const x = 42;',- 'supporting': 'Helper text',-};--interface TypeScaleStyle {- name: string;- sizeToken: string;- sizeValue: string;- weightToken: string;- weightValue: string;- leadingToken: string;- leadingValue: string;- fontFamilyToken: string;-}--function isTypeScaleTable(rows: string[][], previewType?: string): boolean {- if (previewType !== 'font-sample') return false;- if (rows.length < 3) return false;- return (- rows[0]?.[0]?.endsWith('-size') &&- rows[1]?.[0]?.endsWith('-weight') &&- rows[2]?.[0]?.endsWith('-leading')- );-}--function groupTypeScaleRows(rows: string[][]): TypeScaleStyle[] {- const grouped: TypeScaleStyle[] = [];- for (let i = 0; i + 2 < rows.length; i += 3) {- const sizeToken = rows[i][0];- const name = sizeToken.replace('--text-', '').replace('-size', '');- grouped.push({- name,- sizeToken,- sizeValue: rows[i][1],- weightToken: rows[i + 1][0],- weightValue: rows[i + 1][1],- leadingToken: rows[i + 2][0],- leadingValue: rows[i + 2][1],- fontFamilyToken: FONT_FAMILY_MAP[name] ?? '--font-family-body',- });- }- return grouped;-}--const TYPE_SCALE_ORDER = [- 'display-1', 'display-2', 'display-3',- 'heading-1', 'heading-2', 'heading-3', 'heading-4', 'heading-5', 'heading-6',- 'large', 'body', 'label', 'code', 'supporting',-];--function TypeScaleTable({rows}: {rows: string[][]}) {- const {token} = useXDSTheme();- const grouped = useMemo(() => {- const items = groupTypeScaleRows(rows);- const orderMap = new Map(TYPE_SCALE_ORDER.map((k, i) => [k, i]));- return items.sort((a, b) => (orderMap.get(a.name) ?? 99) - (orderMap.get(b.name) ?? 99));- }, [rows]);-- const data = grouped.map(s => {- const leading = token(s.leadingToken) ?? s.leadingValue;- const size = token(s.sizeToken);- const px = size ? Math.round(parseFloat(leading) * parseFloat(size)) : null;- return {- name: s.name,- preview: STYLE_LABEL[s.name] ?? s.name,- fontFamily: token(s.fontFamilyToken),- fontSize: token(s.sizeToken) ?? s.sizeValue,- fontWeight: token(s.weightToken) ?? s.weightValue,- leading: px ? `${leading} (${px}px)` : leading,- fontFamilyToken: s.fontFamilyToken,- sizeToken: s.sizeToken,- weightToken: s.weightToken,- leadingToken: s.leadingToken,- };- });-- return (- <XDSTable- data={data as Record<string, unknown>[]}- columns={[- {- key: 'preview',- header: 'Style',- width: proportional(2),- renderCell: (item: Record<string, unknown>) => (- <span- {...stylex.props(styles.typeScalePreview)}- style={{- fontFamily: item.fontFamily as string,- fontSize: item.fontSize as string,- fontWeight: item.fontWeight as string,- lineHeight: (item.leading as string)?.split(' ')[0],- }}>- {item.preview as string}- </span>- ),- },- {- key: 'fontFamily',- header: 'Font',- renderCell: (item: Record<string, unknown>) => (- <>{(item.fontFamily as string)?.split(',')[0]?.trim()}</>- ),- },- {- key: 'fontSize',- header: 'Size',- },- {- key: 'fontWeight',- header: 'Weight',- },- {- key: 'leading',- header: 'Leading',- },- ]}- density="spacious"- dividers="rows"- hasHover- />- );-}--function CopyableTokenName({name}: {name: string}) {- const [copied, setCopied] = useState(false);- return (- <XDSTooltip content={copied ? 'Copied!' : 'Click to copy'}>- <button- {...stylex.props(styles.tokenLink)}- onClick={(e) => {- e.stopPropagation();- navigator.clipboard.writeText(name);- setCopied(true);- setTimeout(() => setCopied(false), 1500);- }}>- {name}- </button>- </XDSTooltip>- );-}--// =============================================================================-// Block Renderers-// =============================================================================--function TokenTableInner({- rows,- previewType,- isDualColor,+function ThemeTokenSection({+ category,+ theme,}: {- rows: string[][];- previewType?: TokenPreviewType;- isDualColor: boolean;+ category: string;+ theme: XDSDefinedTheme;}) {- const {token} = useXDSTheme();- const data = rows.map((row, i) => ({- _idx: i,- tokenName: row[0],- light: row[1],- dark: row[2],- value: token(row[0]) ?? row[1],- }));-- const columns = isDualColor- ? [- {- key: 'tokenName' as const,- header: 'Token',- renderCell: (item: Record<string, unknown>) => (- <CopyableTokenName name={item.tokenName as string} />- ),- },- {- key: 'light' as const,- header: 'Light',- renderCell: (item: Record<string, unknown>) => (- <div {...stylex.props(styles.valueWithPreview)}>- <SwatchPreview value={item.light as string} />- {item.light as string}- </div>- ),- },- {- key: 'dark' as const,- header: 'Dark',- renderCell: (item: Record<string, unknown>) => (- <div {...stylex.props(styles.valueWithPreview)}>- <SwatchPreview value={item.dark as string} />- {item.dark as string}- </div>- ),- },- ]- : [- {- key: 'tokenName' as const,- header: 'Token',- renderCell: (item: Record<string, unknown>) => (- <CopyableTokenName name={item.tokenName as string} />- ),- },- {- key: 'value' as const,- header: 'Value',- renderCell: (item: Record<string, unknown>) => {- const name = item.tokenName as string;- const val = item.value as string;- return previewType ? (- <div {...stylex.props(styles.valueWithPreview)}>- <TokenPreview type={previewType} tokenName={name} value={val} />- {val}- </div>- ) : (- <>{val}</>- );- },- },- ];-- return (- <XDSTable- data={data as Record<string, unknown>[]}- columns={columns}- density="spacious"- dividers="rows"- hasHover- />- );-}--function TokenTable({- headers,- rows,- previewType,-}: {- headers: string[];- rows: string[][];- previewType?: TokenPreviewType;-}) {- if (isTypeScaleTable(rows, previewType)) {- return <TypeScaleTable rows={rows} />;- }-- const isDualColor = headers.length === 3 && previewType === 'swatch';-- return (- <TokenTableInner- rows={rows}- previewType={previewType}- isDualColor={isDualColor}- />- );-}--function ProseBlock({text}: {text: string}) {- return (- <div {...stylex.props(styles.prose)}>- <XDSText>{text}</XDSText>- </div>- );-}--function CodeBlockRenderer({- lang,- code,- label,-}: {- lang: string;- code: string;- label?: string;-}) {- return (- <div {...stylex.props(styles.fullWidth)}>- <XDSVStack gap={1}>- {label && (- <XDSText type="body" color="primary">- {label}- </XDSText>- )}- <XDSCard variant="muted" padding={0}>- <XDSCodeBlock- code={code}- language={lang}- hasCopyButton- size="sm"- xstyle={styles.codeBlockEmbed}- style={{'--color-syntax-background': 'transparent'} as React.CSSProperties}- />- </XDSCard>- </XDSVStack>- </div>- );-}--function ListBlock({- items,- listStyle,-}: {- items: string[];- listStyle: 'ordered' | 'unordered' | 'do' | 'dont';-}) {- if (listStyle === 'do' || listStyle === 'dont' || listStyle === ('do-dont-merged' as string)) {- const data = listStyle === ('do-dont-merged' as string)- ? items.map(item => {- const isdo = item.startsWith('do:');- return {type: isdo ? 'do' : 'dont', text: item.slice(item.indexOf(':') + 1)};- })- : items.map(text => ({type: listStyle as string, text}));- return (- <XDSTable- data={data as Record<string, unknown>[]}- columns={[- {- key: 'type',- header: 'Guidance',- width: pixel(100),- renderCell: (item: Record<string, unknown>) => (- <XDSBadge- label={item.type === 'do' ? 'Do' : "Don't"}- variant={item.type === 'do' ? 'success' : 'error'}- />- ),- },- {- key: 'text',- header: 'Practices',- renderCell: (item: Record<string, unknown>) => (- <XDSText type="body">{item.text as string}</XDSText>- ),- },- ]}- density="spacious"- dividers="rows"- />- );- }-- return (- <XDSVStack gap={1}>- {items.map((item, i) => (- <XDSHStack key={i} gap={2} vAlign="center">- {listStyle === 'ordered' && (- <XDSText type="body" color="secondary">- {i + 1}.- </XDSText>- )}- {listStyle === 'unordered' && (- <XDSText type="body" color="secondary">- •- </XDSText>- )}- <div {...stylex.props(styles.listItem)}>{item}</div>- </XDSHStack>- ))}- </XDSVStack>- );-}--function ContentBlockRenderer({- block,- previewType,-}: {- block: ContentBlock;- previewType?: TokenPreviewType;-}) {- switch (block.type) {- case 'prose':- return <ProseBlock text={block.text} />;- case 'code':- return (- <CodeBlockRenderer- lang={block.lang}- code={block.code}- label={block.label}- />- );- case 'table':- return (- <TokenTable- headers={block.headers}- rows={block.rows}- previewType={previewType}- />- );- case 'list':- return <ListBlock items={block.items} listStyle={block.style} />;- case 'token-ref':- // Should already be resolved by the CLI — render nothing if unresolved- return null;- default:- return null;- }-}--// =============================================================================-// Section Renderer-// =============================================================================--function mergeDosDonts(blocks: ContentBlock[]): ContentBlock[] {- const merged: ContentBlock[] = [];- let pendingDo: string[] = [];- let pendingDont: string[] = [];-- const flush = () => {- if (pendingDo.length > 0 || pendingDont.length > 0) {- merged.push({- type: 'list' as const,- style: 'do-dont-merged' as 'do',- items: [- ...pendingDo.map(text => `do:${text}`),- ...pendingDont.map(text => `dont:${text}`),- ],- });- pendingDo = [];- pendingDont = [];- }- };-- for (const block of blocks) {- if (block.type === 'list' && block.style === 'do') {- pendingDo.push(...block.items);- } else if (block.type === 'list' && block.style === 'dont') {- pendingDont.push(...block.items);- } else {- flush();- merged.push(block);- }- }- flush();- return merged;-}--function SectionRenderer({section}: {section: ReferenceSection}) {- const mergedContent = useMemo(() => mergeDosDonts(section.content), [section.content]);-- return (- <XDSVStack gap={4}>- <XDSHeading- level={2}- id={section.title.toLowerCase().replace(/\s+/g, '-')}- xstyle={styles.sectionTitle}>- {section.title}- </XDSHeading>- {mergedContent.map((block, i) => (- <ContentBlockRenderer- key={i}- block={block}- previewType={section.previewType}- />- ))}- </XDSVStack>- );+ const Component = TOKEN_TABLE_BY_CATEGORY[category];+ if (!Component) return null;+ return <Component theme={theme} />;}// =============================================================================// DocPreview// =============================================================================-export function DocPreview({doc, version}: {doc: ReferenceDoc; version?: string}) {- // Group sections into: token tables, usage/code, best practices, and other- const {tokenSections, usageSections, practiceSections, overviewSections} =- useMemo(() => {- const token: ReferenceSection[] = [];- const usage: ReferenceSection[] = [];- const practice: ReferenceSection[] = [];- const other: ReferenceSection[] = [];-- for (const section of doc.sections) {- const titleLower = section.title.toLowerCase();- if (- section.previewType ||- section.content.some(b => b.type === 'table')- ) {- token.push(section);- } else if (titleLower.includes('usage')) {- usage.push(section);- } else if (- titleLower.includes('best practice') ||- titleLower.includes('guidance')- ) {- practice.push(section);- } else {- other.push(section);- }- }-- // Prepend the doc description into the first overview section- const overview = [...other];- if (overview.length > 0) {- overview[0] = {- ...overview[0],- content: [- {type: 'prose' as const, text: doc.description},- ...overview[0].content,- ],- };+export function DocPreview({+ doc,+ version,+ theme,+}: {+ doc: ReferenceDoc;+ version?: string;+ theme: XDSDefinedTheme;+}) {+ const {usageSections, practiceSections, overviewSections} = useMemo(() => {+ const usage: ReferenceSection[] = [];+ const practice: ReferenceSection[] = [];+ const other: ReferenceSection[] = [];++ for (const section of doc.sections) {+ const titleLower = section.title.toLowerCase();+ if (+ section.previewType ||+ section.content.some(b => b.type === 'table')+ ) {+ // Token sections — handled by ThemeTokenSection, skip+ continue;+ } else if (titleLower.includes('usage')) {+ usage.push(section);+ } else if (+ titleLower.includes('best practice') ||+ titleLower.includes('guidance')+ ) {+ practice.push(section);} else {- overview.push({- title: 'Overview',- content: [{type: 'prose' as const, text: doc.description}],- });+ other.push(section);}+ }- const sortedTokens = [...token].sort((a, b) => {- const aIsScale = a.title.toLowerCase().includes('type scale') ? 0 : 1;- const bIsScale = b.title.toLowerCase().includes('type scale') ? 0 : 1;- return aIsScale - bIsScale;+ // Prepend the doc description into the first overview section+ const overview = [...other];+ if (overview.length > 0) {+ overview[0] = {+ ...overview[0],+ content: [+ {type: 'prose' as const, text: doc.description},+ ...overview[0].content,+ ],+ };+ } else {+ overview.push({+ title: 'Overview',+ content: [{type: 'prose' as const, text: doc.description}],});+ }- return {- tokenSections: sortedTokens,- usageSections: usage,- practiceSections: practice,- overviewSections: overview,- };- }, [doc.sections, doc.description]);+ return {+ usageSections: usage,+ practiceSections: practice,+ overviewSections: overview,+ };+ }, [doc.sections, doc.description]);return (<div {...stylex.props(styles.root)}><XDSVStack gap={8}>{/* Title + Version */}<XDSVStack gap={1}>- <XDSText type="display-1" as="h1">{doc.title}</XDSText>+ <XDSText type="display-1" as="h1">+ {doc.title}+ </XDSText>{version && (- <XDSText type="supporting" color="secondary" xstyle={styles.version}>+ <XDSText+ type="supporting"+ color="secondary"+ xstyle={styles.version}>v{version}</XDSText>)}@@ -937,7 +144,7 @@ export function DocPreview({doc, version}: {doc: ReferenceDoc; version?: string}{/* Overview */}{overviewSections.map((section, i) => (- <SectionRenderer key={`other-${i}`} section={section} />+ <SectionRenderer key={`overview-${i}`} section={section} />))}{/* Usage */}@@ -961,12 +168,13 @@ export function DocPreview({doc, version}: {doc: ReferenceDoc; version?: string})}{/* Token tables */}- {tokenSections.length > 0 && (+ {doc.tokenCategory && (<><XDSDivider />- {tokenSections.map((section, i) => (- <SectionRenderer key={`token-${i}`} section={section} />- ))}+ <ThemeTokenSection+ category={doc.tokenCategory}+ theme={theme}+ /></>)}</XDSVStack>diff --git a/apps/sandbox/src/app/(sandbox)/pages/doc-preview/SectionRenderer.tsx b/apps/sandbox/src/app/(sandbox)/pages/doc-preview/SectionRenderer.tsxnew file mode 100644index 0000000000..50f6698037--- /dev/null+++ b/apps/sandbox/src/app/(sandbox)/pages/doc-preview/SectionRenderer.tsx@@ -0,0 +1,72 @@+'use client';++import {useMemo} from 'react';+import * as stylex from '@stylexjs/stylex';+import {XDSVStack} from '@xds/core/Layout';+import {XDSHeading} from '@xds/core/Text';+import type {ReferenceSection, ContentBlock} from '@xds/core';+import {ContentBlockRenderer} from './content-blocks';++const styles = stylex.create({+ sectionTitle: {+ scrollMarginTop: 80,+ },+});++/**+ * Merge adjacent do/dont list blocks into a single unified table.+ */+function mergeDosDonts(blocks: ContentBlock[]): ContentBlock[] {+ const merged: ContentBlock[] = [];+ let pendingDo: string[] = [];+ let pendingDont: string[] = [];++ const flush = () => {+ if (pendingDo.length > 0 || pendingDont.length > 0) {+ merged.push({+ type: 'list' as const,+ style: 'do-dont-merged' as 'do',+ items: [+ ...pendingDo.map(text => `do:${text}`),+ ...pendingDont.map(text => `dont:${text}`),+ ],+ });+ pendingDo = [];+ pendingDont = [];+ }+ };++ for (const block of blocks) {+ if (block.type === 'list' && block.style === 'do') {+ pendingDo.push(...block.items);+ } else if (block.type === 'list' && block.style === 'dont') {+ pendingDont.push(...block.items);+ } else {+ flush();+ merged.push(block);+ }+ }+ flush();+ return merged;+}++export function SectionRenderer({section}: {section: ReferenceSection}) {+ const mergedContent = useMemo(+ () => mergeDosDonts(section.content),+ [section.content],+ );++ return (+ <XDSVStack gap={4}>+ <XDSHeading+ level={2}+ id={section.title.toLowerCase().replace(/\s+/g, '-')}+ xstyle={styles.sectionTitle}>+ {section.title}+ </XDSHeading>+ {mergedContent.map((block, i) => (+ <ContentBlockRenderer key={i} block={block} />+ ))}+ </XDSVStack>+ );+}diff --git a/apps/sandbox/src/app/(sandbox)/pages/doc-preview/content-blocks/CodeBlock.tsx b/apps/sandbox/src/app/(sandbox)/pages/doc-preview/content-blocks/CodeBlock.tsxnew file mode 100644index 0000000000..74a108a55c--- /dev/null+++ b/apps/sandbox/src/app/(sandbox)/pages/doc-preview/content-blocks/CodeBlock.tsx@@ -0,0 +1,44 @@+'use client';++import * as stylex from '@stylexjs/stylex';+import {XDSVStack} from '@xds/core/Layout';+import {XDSText} from '@xds/core/Text';+import {XDSCodeBlock} from '@xds/core/CodeBlock';+import {XDSCard} from '@xds/core/Card';++const styles = stylex.create({+ root: {+ width: '100%',+ },+});++export function CodeBlock({+ lang,+ code,+ label,+}: {+ lang: string;+ code: string;+ label?: string;+}) {+ return (+ <XDSVStack gap={1}>+ {label && (+ <XDSText type="supporting" color="secondary">+ {label}+ </XDSText>+ )}+ <XDSCard variant="muted" xstyle={styles.root}>+ <XDSCodeBlock+ code={code}+ language={lang}+ hasCopyButton+ style={{+ '--color-syntax-background': 'transparent',+ width: '100%',+ } as React.CSSProperties}+ />+ </XDSCard>+ </XDSVStack>+ );+}diff --git a/apps/sandbox/src/app/(sandbox)/pages/doc-preview/content-blocks/ContentBlockRenderer.tsx b/apps/sandbox/src/app/(sandbox)/pages/doc-preview/content-blocks/ContentBlockRenderer.tsxnew file mode 100644index 0000000000..90ed096f72--- /dev/null+++ b/apps/sandbox/src/app/(sandbox)/pages/doc-preview/content-blocks/ContentBlockRenderer.tsx@@ -0,0 +1,27 @@+'use client';++import type {ContentBlock} from '@xds/core';+import {ProseBlock} from './ProseBlock';+import {CodeBlock} from './CodeBlock';+import {TableBlock} from './TableBlock';+import {ListBlock} from './ListBlock';++/**+ * Renders a single ContentBlock by dispatching to the appropriate component.+ */+export function ContentBlockRenderer({block}: {block: ContentBlock}) {+ switch (block.type) {+ case 'prose':+ return <ProseBlock text={block.text} />;+ case 'code':+ return <CodeBlock lang={block.lang} code={block.code} label={block.label} />;+ case 'table':+ return <TableBlock headers={block.headers} rows={block.rows} />;+ case 'list':+ return <ListBlock items={block.items} listStyle={block.style} />;+ case 'token-ref':+ return null;+ default:+ return null;+ }+}diff --git a/apps/sandbox/src/app/(sandbox)/pages/doc-preview/content-blocks/ListBlock.tsx b/apps/sandbox/src/app/(sandbox)/pages/doc-preview/content-blocks/ListBlock.tsxnew file mode 100644index 0000000000..9858a4f4ac--- /dev/null+++ b/apps/sandbox/src/app/(sandbox)/pages/doc-preview/content-blocks/ListBlock.tsx@@ -0,0 +1,71 @@+'use client';++import {XDSVStack, XDSHStack} from '@xds/core/Layout';+import {XDSText} from '@xds/core/Text';+import {XDSBadge} from '@xds/core/Badge';+import {XDSTable} from '@xds/core/Table';++/**+ * Renders list content blocks: ordered, unordered, do, dont,+ * and merged do-dont tables with badges.+ */+export function ListBlock({+ items,+ listStyle,+}: {+ items: string[];+ listStyle: 'ordered' | 'unordered' | 'do' | 'dont' | 'do-dont-merged';+}) {+ if (listStyle === ('do-dont-merged' as string)) {+ const data = items.map((item, i) => {+ const isDo = item.startsWith('do:');+ return {+ _idx: i,+ guidance: isDo ? 'Do' : "Don't",+ isDo,+ text: item.replace(/^(do|dont):/, ''),+ };+ });++ return (+ <XDSTable+ data={data as Record<string, unknown>[]}+ columns={[+ {+ key: 'guidance',+ header: 'Guidance',+ renderCell: (item: Record<string, unknown>) => (+ <XDSBadge+ label={item.guidance as string}+ variant={(item.isDo as boolean) ? 'success' : 'error'}+ />+ ),+ },+ {key: 'text', header: 'Practice'},+ ]}+ density="spacious"+ dividers="rows"+ />+ );+ }++ return (+ <XDSVStack gap={1}>+ {items.map((item, i) => (+ <XDSHStack key={i} gap={2} vAlign="center">+ {listStyle === 'ordered' && (+ <XDSText type="body" color="secondary">+ {i + 1}.+ </XDSText>+ )}+ {listStyle === 'unordered' && (+ <XDSText type="body" color="secondary">+ •+ </XDSText>+ )}+ <XDSText>{item}</XDSText>+ </XDSHStack>+ ))}+ </XDSVStack>+ );+}diff --git a/apps/sandbox/src/app/(sandbox)/pages/doc-preview/content-blocks/ProseBlock.tsx b/apps/sandbox/src/app/(sandbox)/pages/doc-preview/content-blocks/ProseBlock.tsxnew file mode 100644index 0000000000..9f75baba70--- /dev/null+++ b/apps/sandbox/src/app/(sandbox)/pages/doc-preview/content-blocks/ProseBlock.tsx@@ -0,0 +1,7 @@+'use client';++import {XDSText} from '@xds/core/Text';++export function ProseBlock({text}: {text: string}) {+ return <XDSText>{text}</XDSText>;+}diff --git a/apps/sandbox/src/app/(sandbox)/pages/doc-preview/content-blocks/TableBlock.tsx b/apps/sandbox/src/app/(sandbox)/pages/doc-preview/content-blocks/TableBlock.tsxnew file mode 100644index 0000000000..7258e59c6b--- /dev/null+++ b/apps/sandbox/src/app/(sandbox)/pages/doc-preview/content-blocks/TableBlock.tsx@@ -0,0 +1,42 @@+'use client';++import {XDSText} from '@xds/core/Text';+import {XDSTable} from '@xds/core/Table';++/**+ * Generic table renderer for ContentBlock type='table'.+ * Renders headers + rows as a simple data table.+ */+export function TableBlock({+ headers,+ rows,+}: {+ headers: string[];+ rows: string[][];+}) {+ const data = rows.map((row, i) => {+ const obj: Record<string, unknown> = {_idx: i};+ headers.forEach((h, j) => {+ obj[h] = row[j] ?? '';+ });+ return obj;+ });++ const columns = headers.map(h => ({+ key: h,+ header: h,+ renderCell: (item: Record<string, unknown>) => (+ <XDSText>{item[h] as string}</XDSText>+ ),+ }));++ return (+ <XDSTable+ data={data}+ columns={columns}+ density="spacious"+ dividers="rows"+ hasHover+ />+ );+}diff --git a/apps/sandbox/src/app/(sandbox)/pages/doc-preview/content-blocks/index.ts b/apps/sandbox/src/app/(sandbox)/pages/doc-preview/content-blocks/index.tsnew file mode 100644index 0000000000..fd3218ea9b--- /dev/null+++ b/apps/sandbox/src/app/(sandbox)/pages/doc-preview/content-blocks/index.ts@@ -0,0 +1,5 @@+export {ProseBlock} from './ProseBlock';+export {CodeBlock} from './CodeBlock';+export {TableBlock} from './TableBlock';+export {ListBlock} from './ListBlock';+export {ContentBlockRenderer} from './ContentBlockRenderer';diff --git a/apps/sandbox/src/app/(sandbox)/pages/doc-preview/page.tsx b/apps/sandbox/src/app/(sandbox)/pages/doc-preview/page.tsxindex 2355ea1223..e215b0cbdf 100644--- a/apps/sandbox/src/app/(sandbox)/pages/doc-preview/page.tsx+++ b/apps/sandbox/src/app/(sandbox)/pages/doc-preview/page.tsx@@ -11,6 +11,8 @@ import {import { XDSSpinner } from "@xds/core/Spinner";import type { ReferenceDoc } from "@xds/core";import { DocPreview } from "./DocPreview";+import { XDSThemeContext } from "@xds/core/theme";+import { useContext } from "react";const styles = stylex.create({page: {@@ -61,6 +63,7 @@ export default function DocPreviewPage() {.catch(() => setLoading(false));}, []);+ const ctx = useContext(XDSThemeContext);const doc = docs[topic] ?? null;return (@@ -91,7 +94,7 @@ export default function DocPreviewPage() {<XDSSpinner size="md" /></div>) : doc ? (- <DocPreview doc={doc} version={version} />+ ctx?.theme ? <DocPreview doc={doc} version={version} theme={ctx.theme} /> : null) : (<div {...stylex.props(styles.loading)}><XDSText color="secondary">No doc found for "{topic}"</XDSText>diff --git a/apps/sandbox/src/app/(sandbox)/pages/doc-preview/token-tables/ColorTokenTable.tsx b/apps/sandbox/src/app/(sandbox)/pages/doc-preview/token-tables/ColorTokenTable.tsxnew file mode 100644index 0000000000..22674f760d--- /dev/null+++ b/apps/sandbox/src/app/(sandbox)/pages/doc-preview/token-tables/ColorTokenTable.tsx@@ -0,0 +1,144 @@+'use client';++import * as stylex from '@stylexjs/stylex';+import {XDSHStack} from '@xds/core/Layout';+import {XDSText} from '@xds/core/Text';+import {XDSTable} from '@xds/core/Table';+import type {TokenTableProps} from './types';+import {resolveTokenForMode, hasDualMode, getTokensByPrefix} from './helpers';++const styles = stylex.create({+ swatch: {+ width: 28,+ height: 28,+ borderRadius: 'var(--radius-element)',+ flexShrink: 0,+ border: '1px solid var(--color-border)',+ },+ contextLight: {+ width: 28,+ height: 28,+ borderRadius: 'var(--radius-element)',+ backgroundColor: '#FFFFFF',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ flexShrink: 0,+ border: '1px solid var(--color-border)',+ },+ contextDark: {+ width: 28,+ height: 28,+ borderRadius: 'var(--radius-element)',+ backgroundColor: '#1C1C1E',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ flexShrink: 0,+ border: '1px solid var(--color-border)',+ },+ swatchInner: {+ width: 20,+ height: 20,+ borderRadius: 'var(--radius-inner)',+ },+});++function ContextSwatch({+ value,+ surface,+}: {+ value: string;+ surface: 'light' | 'dark';+}) {+ return (+ <div+ {...stylex.props(+ surface === 'light' ? styles.contextLight : styles.contextDark,+ )}>+ <div+ {...stylex.props(styles.swatchInner)}+ style={{backgroundColor: value}}+ />+ </div>+ );+}++function Swatch({value}: {value: string}) {+ return (+ <div {...stylex.props(styles.swatch)} style={{backgroundColor: value}} />+ );+}++export function ColorTokenTable({theme}: TokenTableProps) {+ const tokens = getTokensByPrefix(theme, '--color-');+ const isDual = hasDualMode(theme);++ const data = tokens.map(name => ({+ tokenName: name,+ light: resolveTokenForMode(theme, name, 'light'),+ dark: resolveTokenForMode(theme, name, 'dark'),+ }));++ if (isDual) {+ return (+ <XDSTable+ data={data as Record<string, unknown>[]}+ columns={[+ {key: 'tokenName', header: 'Token'},+ {+ key: 'light',+ header: 'Light',+ renderCell: (item: Record<string, unknown>) => (+ <XDSHStack gap={2} align="center">+ <ContextSwatch value={item.light as string} surface="light" />+ <XDSText type="code" color="secondary">+ {item.light as string}+ </XDSText>+ </XDSHStack>+ ),+ },+ {+ key: 'dark',+ header: 'Dark',+ renderCell: (item: Record<string, unknown>) => (+ <XDSHStack gap={2} align="center">+ <ContextSwatch value={item.dark as string} surface="dark" />+ <XDSText type="code" color="secondary">+ {item.dark as string}+ </XDSText>+ </XDSHStack>+ ),+ },+ ]}+ density="spacious"+ dividers="rows"+ hasHover+ />+ );+ }++ return (+ <XDSTable+ data={data as Record<string, unknown>[]}+ columns={[+ {key: 'tokenName', header: 'Token'},+ {+ key: 'light',+ header: 'Value',+ renderCell: (item: Record<string, unknown>) => (+ <XDSHStack gap={2} align="center">+ <Swatch value={item.light as string} />+ <XDSText type="code" color="secondary">+ {item.light as string}+ </XDSText>+ </XDSHStack>+ ),+ },+ ]}+ density="spacious"+ dividers="rows"+ hasHover+ />+ );+}diff --git a/apps/sandbox/src/app/(sandbox)/pages/doc-preview/token-tables/ElevationTokenTable.tsx b/apps/sandbox/src/app/(sandbox)/pages/doc-preview/token-tables/ElevationTokenTable.tsxnew file mode 100644index 0000000000..fdf8e61225--- /dev/null+++ b/apps/sandbox/src/app/(sandbox)/pages/doc-preview/token-tables/ElevationTokenTable.tsx@@ -0,0 +1,48 @@+'use client';++import * as stylex from '@stylexjs/stylex';+import {XDSHStack} from '@xds/core/Layout';+import {XDSText} from '@xds/core/Text';+import {XDSTable} from '@xds/core/Table';+import type {TokenTableProps} from './types';+import {resolveToken, getTokensByPrefix} from './helpers';++const styles = stylex.create({+ shadowBox: {+ width: 32,+ height: 24,+ borderRadius: 'var(--radius-element)',+ backgroundColor: 'var(--color-background-surface)',+ flexShrink: 0,+ },+});++export function ElevationTokenTable({theme}: TokenTableProps) {+ const tokens = getTokensByPrefix(theme, '--shadow-');+ const data = tokens.map(name => ({+ tokenName: name,+ value: resolveToken(theme, name),+ }));++ return (+ <XDSTable+ data={data as Record<string, unknown>[]}+ columns={[+ {key: 'tokenName', header: 'Token'},+ {+ key: 'value',+ header: 'Value',+ renderCell: (item: Record<string, unknown>) => (+ <XDSHStack gap={2} align="center">+ <div {...stylex.props(styles.shadowBox)} style={{boxShadow: item.value as string}} />+ <XDSText type="code" color="secondary">{item.value as string}</XDSText>+ </XDSHStack>+ ),+ },+ ]}+ density="spacious"+ dividers="rows"+ hasHover+ />+ );+}diff --git a/apps/sandbox/src/app/(sandbox)/pages/doc-preview/token-tables/MotionTokenTable.tsx b/apps/sandbox/src/app/(sandbox)/pages/doc-preview/token-tables/MotionTokenTable.tsxnew file mode 100644index 0000000000..61bd13b00f--- /dev/null+++ b/apps/sandbox/src/app/(sandbox)/pages/doc-preview/token-tables/MotionTokenTable.tsx@@ -0,0 +1,237 @@+'use client';++import {useState, useEffect, useRef} from 'react';+import * as stylex from '@stylexjs/stylex';+import {XDSVStack, XDSHStack} from '@xds/core/Layout';+import {XDSText, XDSHeading} from '@xds/core/Text';+import {XDSTable} from '@xds/core/Table';+import type {TokenTableProps} from './types';+import {resolveToken, getTokensByPrefix} from './helpers';++const styles = stylex.create({+ durationTrack: {+ width: 40,+ height: 8,+ borderRadius: 'var(--radius-element)',+ backgroundColor: 'var(--color-neutral)',+ overflow: 'hidden',+ flexShrink: 0,+ },+ durationFill: {+ height: '100%',+ borderRadius: 'var(--radius-element)',+ backgroundColor: 'var(--color-accent)',+ },+ easingTrack: {+ width: 40,+ height: 8,+ borderRadius: 'var(--radius-element)',+ backgroundColor: 'var(--color-neutral)',+ position: 'relative' as const,+ overflow: 'visible',+ flexShrink: 0,+ },+ easingDot: {+ position: 'absolute' as const,+ top: 0,+ width: 8,+ height: 8,+ borderRadius: 'var(--radius-full)',+ backgroundColor: 'var(--color-accent)',+ transform: 'translateX(-50%)',+ },+});++// =============================================================================+// Duration ordering: band-min, band, band-max+// =============================================================================++const DURATION_ORDER = [+ '--duration-fast-min',+ '--duration-fast',+ '--duration-fast-max',+ '--duration-medium-min',+ '--duration-medium',+ '--duration-medium-max',+ '--duration-slow-min',+ '--duration-slow',+ '--duration-slow-max',+];++function sortDurationTokens(tokens: string[]): string[] {+ const orderMap = new Map(DURATION_ORDER.map((k, i) => [k, i]));+ return [...tokens].sort((a, b) => {+ const ai = orderMap.get(a) ?? 99;+ const bi = orderMap.get(b) ?? 99;+ return ai - bi;+ });+}++// =============================================================================+// Preview components+// =============================================================================++function DurationBar({value}: {value: string}) {+ const [animate, setAnimate] = useState(false);+ useEffect(() => {+ const interval = setInterval(() => setAnimate(a => !a), 2000);+ return () => clearInterval(interval);+ }, []);+ return (+ <div {...stylex.props(styles.durationTrack)}>+ <div+ {...stylex.props(styles.durationFill)}+ style={{width: animate ? '100%' : '0%', transition: `width ${value} ease`}}+ />+ </div>+ );+}++function evaluateBezier(+ x1: number, y1: number, x2: number, y2: number, t: number,+): number {+ const cx = 3 * x1, bx = 3 * (x2 - x1) - cx, ax = 1 - cx - bx;+ const cy = 3 * y1, by = 3 * (y2 - y1) - cy, ay = 1 - cy - by;+ const sampleX = (s: number) => ((ax * s + bx) * s + cx) * s;+ const sampleY = (s: number) => ((ay * s + by) * s + cy) * s;+ const sampleXDeriv = (s: number) => (3 * ax * s + 2 * bx) * s + cx;+ let g = t;+ for (let i = 0; i < 8; i++) {+ const cur = sampleX(g) - t;+ if (Math.abs(cur) < 1e-6) break;+ const d = sampleXDeriv(g);+ if (Math.abs(d) < 1e-6) break;+ g -= cur / d;+ }+ return sampleY(Math.max(0, Math.min(1, g)));+}++function EasingCurve({value}: {value: string}) {+ const [progress, setProgress] = useState(0);+ const animRef = useRef<number | null>(null);+ const startRef = useRef<number>(0);+ const match = value.match(+ /cubic-bezier\(\s*([\d.]+)\s*,\s*([-\d.]+)\s*,\s*([\d.]+)\s*,\s*([-\d.]+)\s*\)/,+ );++ useEffect(() => {+ if (!match) return;+ let running = true;+ const duration = 1200, pause = 800, cycle = duration + pause;+ function tick(ts: number) {+ if (!running) return;+ if (!startRef.current) startRef.current = ts;+ const inCycle = (ts - startRef.current) % cycle;+ setProgress(inCycle < duration ? inCycle / duration : 1);+ if ((ts - startRef.current) % (cycle * 2) >= cycle * 2 - 16) startRef.current = ts;+ animRef.current = requestAnimationFrame(tick);+ }+ animRef.current = requestAnimationFrame(tick);+ return () => { running = false; if (animRef.current) cancelAnimationFrame(animRef.current); };+ }, [match]);++ if (!match) return null;+ const [, x1, y1, x2, y2] = match.map(Number);+ const easedY = evaluateBezier(x1, y1, x2, y2, progress);+ const pad = 0.12;++ return (+ <XDSHStack gap={2} align="center">+ <svg width={32} height={24} viewBox={`${-pad} ${-pad} ${1+pad*2} ${1+pad*2}`} style={{flexShrink: 0}}>+ <path d={`M 0 1 C ${x1} ${1-y1}, ${x2} ${1-y2}, 1 0`} fill="none" stroke="var(--color-neutral)" strokeWidth={0.04} />+ <path d={`M 0 1 C ${x1} ${1-y1}, ${x2} ${1-y2}, 1 0`} fill="none" stroke="var(--color-accent)" strokeWidth={0.06} strokeDasharray="1" strokeDashoffset={1-progress} pathLength={1} />+ <circle cx={progress} cy={1-easedY} r={0.06} fill="var(--color-accent)" />+ </svg>+ <div {...stylex.props(styles.easingTrack)}>+ <div {...stylex.props(styles.easingDot)} style={{left: `${easedY*100}%`}} />+ </div>+ </XDSHStack>+ );+}++// =============================================================================+// Duration Table+// =============================================================================++export function DurationTokenTable({theme}: TokenTableProps) {+ const tokens = sortDurationTokens(getTokensByPrefix(theme, '--duration-'));+ const data = tokens.map(name => ({+ tokenName: name,+ value: resolveToken(theme, name),+ }));++ return (+ <XDSTable+ data={data as Record<string, unknown>[]}+ columns={[+ {key: 'tokenName', header: 'Token'},+ {+ key: 'value',+ header: 'Value',+ renderCell: (item: Record<string, unknown>) => (+ <XDSHStack gap={2} align="center">+ <DurationBar value={item.value as string} />+ <XDSText type="code" color="secondary">{item.value as string}</XDSText>+ </XDSHStack>+ ),+ },+ ]}+ density="spacious"+ dividers="rows"+ hasHover+ />+ );+}++// =============================================================================+// Easing Table+// =============================================================================++export function EasingTokenTable({theme}: TokenTableProps) {+ const tokens = getTokensByPrefix(theme, '--ease-');+ const data = tokens.map(name => ({+ tokenName: name,+ value: resolveToken(theme, name),+ }));++ return (+ <XDSTable+ data={data as Record<string, unknown>[]}+ columns={[+ {key: 'tokenName', header: 'Token'},+ {+ key: 'value',+ header: 'Value',+ renderCell: (item: Record<string, unknown>) => (+ <XDSHStack gap={2} align="center">+ <EasingCurve value={item.value as string} />+ <XDSText type="code" color="secondary">{item.value as string}</XDSText>+ </XDSHStack>+ ),+ },+ ]}+ density="spacious"+ dividers="rows"+ hasHover+ />+ );+}++// =============================================================================+// Combined Motion Table (renders both with headings)+// =============================================================================++export function MotionTokenTable({theme}: TokenTableProps) {+ return (+ <XDSVStack gap={6}>+ <XDSVStack gap={3}>+ <XDSHeading level={3}>Duration</XDSHeading>+ <DurationTokenTable theme={theme} />+ </XDSVStack>+ <XDSVStack gap={3}>+ <XDSHeading level={3}>Easing</XDSHeading>+ <EasingTokenTable theme={theme} />+ </XDSVStack>+ </XDSVStack>+ );+}diff --git a/apps/sandbox/src/app/(sandbox)/pages/doc-preview/token-tables/ShapeTokenTable.tsx b/apps/sandbox/src/app/(sandbox)/pages/doc-preview/token-tables/ShapeTokenTable.tsxnew file mode 100644index 0000000000..8049f9e6f3--- /dev/null+++ b/apps/sandbox/src/app/(sandbox)/pages/doc-preview/token-tables/ShapeTokenTable.tsx@@ -0,0 +1,121 @@+'use client';++import * as stylex from '@stylexjs/stylex';+import {XDSVStack, XDSHStack} from '@xds/core/Layout';+import {XDSText, XDSHeading} from '@xds/core/Text';+import {XDSTable} from '@xds/core/Table';+import type {TokenTableProps} from './types';+import {resolveToken, getTokensByPrefix} from './helpers';++const styles = stylex.create({+ radiusBox: {+ width: 32,+ height: 32,+ backgroundColor: 'var(--color-accent-muted)',+ border: '2px solid var(--color-accent)',+ flexShrink: 0,+ },+ borderLine: {+ width: 32,+ height: 0,+ borderBottomStyle: 'solid',+ borderBottomColor: 'var(--color-border-emphasized)',+ flexShrink: 0,+ },+});++// Semantic ordering from the tokens doc+const RADIUS_ORDER = [+ '--radius-none',+ '--radius-inner',+ '--radius-element',+ '--radius-container',+ '--radius-page',+ '--radius-full',+];++function sortByOrder(tokens: string[], order: string[]): string[] {+ const orderMap = new Map(order.map((k, i) => [k, i]));+ return [...tokens].sort((a, b) => {+ const ai = orderMap.get(a) ?? 99;+ const bi = orderMap.get(b) ?? 99;+ return ai - bi;+ });+}++function RadiusTokenTable({theme}: TokenTableProps) {+ const tokens = sortByOrder(getTokensByPrefix(theme, '--radius-'), RADIUS_ORDER);+ const data = tokens.map(name => ({+ tokenName: name,+ value: resolveToken(theme, name),+ }));++ return (+ <XDSTable+ data={data as Record<string, unknown>[]}+ columns={[+ {key: 'tokenName', header: 'Token'},+ {+ key: 'value',+ header: 'Value',+ renderCell: (item: Record<string, unknown>) => (+ <XDSHStack gap={2} align="center">+ <div {...stylex.props(styles.radiusBox)} style={{borderRadius: item.value as string}} />+ <XDSText type="code" color="secondary">{item.value as string}</XDSText>+ </XDSHStack>+ ),+ },+ ]}+ density="spacious"+ dividers="rows"+ hasHover+ />+ );+}++function BorderTokenTable({theme}: TokenTableProps) {+ const tokens = getTokensByPrefix(theme, '--border-');+ if (tokens.length === 0) return null;++ const data = tokens.map(name => ({+ tokenName: name,+ value: resolveToken(theme, name),+ }));++ return (+ <XDSTable+ data={data as Record<string, unknown>[]}+ columns={[+ {key: 'tokenName', header: 'Token'},+ {+ key: 'value',+ header: 'Value',+ renderCell: (item: Record<string, unknown>) => (+ <XDSHStack gap={2} align="center">+ <div {...stylex.props(styles.borderLine)} style={{borderBottomWidth: item.value as string}} />+ <XDSText type="code" color="secondary">{item.value as string}</XDSText>+ </XDSHStack>+ ),+ },+ ]}+ density="spacious"+ dividers="rows"+ hasHover+ />+ );+}++export function ShapeTokenTable({theme}: TokenTableProps) {+ return (+ <XDSVStack gap={6}>+ <XDSVStack gap={3}>+ <XDSHeading level={3}>Radius</XDSHeading>+ <RadiusTokenTable theme={theme} />+ </XDSVStack>+ <XDSVStack gap={3}>+ <XDSHeading level={3}>Border</XDSHeading>+ <BorderTokenTable theme={theme} />+ </XDSVStack>+ </XDSVStack>+ );+}diff --git a/apps/sandbox/src/app/(sandbox)/pages/doc-preview/token-tables/SpacingTokenTable.tsx b/apps/sandbox/src/app/(sandbox)/pages/doc-preview/token-tables/SpacingTokenTable.tsxnew file mode 100644index 0000000000..8c85ed0326--- /dev/null+++ b/apps/sandbox/src/app/(sandbox)/pages/doc-preview/token-tables/SpacingTokenTable.tsx@@ -0,0 +1,50 @@+'use client';++import * as stylex from '@stylexjs/stylex';+import {XDSHStack} from '@xds/core/Layout';+import {XDSText} from '@xds/core/Text';+import {XDSTable} from '@xds/core/Table';+import type {TokenTableProps} from './types';+import {resolveToken, getTokensByPrefix} from './helpers';++const styles = stylex.create({+ bar: {+ minWidth: 2,+ maxWidth: 64,+ height: 12,+ borderRadius: 'var(--radius-element)',+ backgroundColor: 'var(--color-accent)',+ opacity: 0.6,+ flexShrink: 0,+ },+});++export function SpacingTokenTable({theme}: TokenTableProps) {+ const tokens = getTokensByPrefix(theme, '--spacing-');+ const data = tokens.map(name => ({+ tokenName: name,+ value: resolveToken(theme, name),+ }));++ return (+ <XDSTable+ data={data as Record<string, unknown>[]}+ columns={[+ {key: 'tokenName', header: 'Token'},+ {+ key: 'value',+ header: 'Value',+ renderCell: (item: Record<string, unknown>) => (+ <XDSHStack gap={2} align="center">+ <div {...stylex.props(styles.bar)} style={{width: item.value as string}} />+ <XDSText type="code" color="secondary">{item.value as string}</XDSText>+ </XDSHStack>+ ),+ },+ ]}+ density="spacious"+ dividers="rows"+ hasHover+ />+ );+}diff --git a/apps/sandbox/src/app/(sandbox)/pages/doc-preview/token-tables/TypographyTokenTable.tsx b/apps/sandbox/src/app/(sandbox)/pages/doc-preview/token-tables/TypographyTokenTable.tsxnew file mode 100644index 0000000000..30a2077c25--- /dev/null+++ b/apps/sandbox/src/app/(sandbox)/pages/doc-preview/token-tables/TypographyTokenTable.tsx@@ -0,0 +1,152 @@+'use client';++import * as stylex from '@stylexjs/stylex';+import {XDSTable, proportional} from '@xds/core/Table';+import type {XDSTextType} from '@xds/core';+import type {XDSHeadingLevel} from '@xds/core/Text';+import type {TokenTableProps} from './types';+import {resolveToken} from './helpers';++const styles = stylex.create({+ sample: {+ overflow: 'hidden',+ whiteSpace: 'nowrap' as const,+ textOverflow: 'ellipsis',+ display: 'block',+ },+});++const HEADING_LEVELS: XDSHeadingLevel[] = [1, 2, 3, 4, 5, 6];+const TEXT_TYPES: XDSTextType[] = [+ 'display-1',+ 'display-2',+ 'display-3',+ 'large',+ 'body',+ 'label',+ 'code',+ 'supporting',+];++const STYLE_LABEL: Record<string, string> = {+ 'display-1': 'Display 1',+ 'display-2': 'Display 2',+ 'display-3': 'Display 3',+ 'heading-1': 'H1',+ 'heading-2': 'H2',+ 'heading-3': 'H3',+ 'heading-4': 'H4',+ 'heading-5': 'H5',+ 'heading-6': 'H6',+ body: 'Body',+ large: 'Large',+ label: 'Label',+ code: 'Code',+ supporting: 'Supporting',+};++const SAMPLE_TEXT: Record<string, string> = {+ 'display-1': '$12,450',+ 'display-2': '98.7%',+ 'display-3': 'Welcome',+ 'heading-1': 'Page Title',+ 'heading-2': 'Section Title',+ 'heading-3': 'Card Heading',+ 'heading-4': 'Subsection',+ 'heading-5': 'Group Label',+ 'heading-6': 'Overline',+ body: 'Body text for reading',+ large: 'Intro paragraph',+ label: 'Form Label',+ code: 'const x = 42;',+ supporting: 'Helper text',+};++const FONT_FAMILY_MAP: Record<string, string> = {+ 'heading-1': '--font-family-heading',+ 'heading-2': '--font-family-heading',+ 'heading-3': '--font-family-heading',+ 'heading-4': '--font-family-heading',+ 'heading-5': '--font-family-heading',+ 'heading-6': '--font-family-heading',+ body: '--font-family-body',+ large: '--font-family-body',+ label: '--font-family-body',+ supporting: '--font-family-body',+ code: '--font-family-code',+ 'display-1': '--font-family-heading',+ 'display-2': '--font-family-heading',+ 'display-3': '--font-family-heading',+};++export function TypographyTokenTable({theme}: TokenTableProps) {+ const entries = [+ ...HEADING_LEVELS.map(level => `heading-${level}`),+ ...TEXT_TYPES,+ ];++ const data = entries.map(name => {+ const sizeToken = `--text-${name}-size`;+ const weightToken = `--text-${name}-weight`;+ const leadingToken = `--text-${name}-leading`;+ const fontFamilyToken = FONT_FAMILY_MAP[name] ?? '--font-family-body';++ const fontSize = resolveToken(theme, sizeToken);+ const fontWeight = resolveToken(theme, weightToken);+ const leading = resolveToken(theme, leadingToken);+ const fontFamily = resolveToken(theme, fontFamilyToken);++ const px =+ fontSize && leading+ ? Math.round(parseFloat(leading) * parseFloat(fontSize))+ : null;++ return {+ name,+ label: STYLE_LABEL[name] ?? name,+ sampleText: SAMPLE_TEXT[name] ?? name,+ fontFamily,+ fontSize,+ fontWeight,+ leading: px ? `${leading} (${px}px)` : leading,+ };+ });++ return (+ <XDSTable+ data={data as Record<string, unknown>[]}+ columns={[+ {+ key: 'label',+ header: 'Style',+ width: proportional(2),+ renderCell: (item: Record<string, unknown>) => (+ <span+ {...stylex.props(styles.sample)}+ style={{+ fontFamily: item.fontFamily as string,+ fontSize: item.fontSize as string,+ fontWeight: item.fontWeight as string,+ lineHeight: (item.leading as string)?.split(' ')[0],+ }}>+ {item.sampleText as string}+ </span>+ ),+ },+ {+ key: 'fontFamily',+ header: 'Font',+ renderCell: (item: Record<string, unknown>) => (+ <>{(item.fontFamily as string)?.split(',')[0]?.trim()}</>+ ),+ },+ {key: 'fontSize', header: 'Size'},+ {key: 'fontWeight', header: 'Weight'},+ {key: 'leading', header: 'Leading'},+ ]}+ density="spacious"+ dividers="rows"+ hasHover+ />+ );+}diff --git a/apps/sandbox/src/app/(sandbox)/pages/doc-preview/token-tables/helpers.ts b/apps/sandbox/src/app/(sandbox)/pages/doc-preview/token-tables/helpers.tsnew file mode 100644index 0000000000..597f376dd8--- /dev/null+++ b/apps/sandbox/src/app/(sandbox)/pages/doc-preview/token-tables/helpers.ts@@ -0,0 +1,113 @@+import type {XDSDefinedTheme} from '@xds/core/theme';+import {xdsTokenDefaults} from '@xds/core/theme';++/**+ * Parse a light-dark() CSS value into [light, dark] components.+ */+export function parseLightDark(value: string): [string, string] | null {+ const match = value.match(/^light-dark\(\s*([^,]+?)\s*,\s*(.+?)\s*\)$/);+ if (!match) return null;+ return [match[1], match[2]];+}++/**+ * Resolve a token's value for a specific mode from a defined theme.+ * Checks __inputTokens for [light, dark] tuples first,+ * then parses light-dark() from resolved tokens,+ * then falls back to xdsTokenDefaults.+ */+export function resolveTokenForMode(+ theme: XDSDefinedTheme,+ tokenName: string,+ mode: 'light' | 'dark',+): string {+ // 1. Check __inputTokens (preserves tuples)+ const inputTokens = theme.__inputTokens;+ if (inputTokens) {+ const val = inputTokens[tokenName];+ if (Array.isArray(val)) return mode === 'dark' ? val[1] : val[0];+ if (typeof val === 'string') {+ const parsed = parseLightDark(val);+ if (parsed) return mode === 'dark' ? parsed[1] : parsed[0];+ return val;+ }+ }+ // 2. Check theme.tokens (resolved, may contain light-dark())+ const resolved = theme.tokens[tokenName];+ if (resolved) {+ const parsed = parseLightDark(resolved);+ if (parsed) return mode === 'dark' ? parsed[1] : parsed[0];+ return resolved;+ }+ // 3. Fall back to defaults+ const def = xdsTokenDefaults[tokenName];+ if (def) {+ const parsed = parseLightDark(def);+ if (parsed) return mode === 'dark' ? parsed[1] : parsed[0];+ return def;+ }+ return '';+}++/**+ * Resolve a token for the current mode (resolves light-dark() to a single value).+ */+export function resolveToken(+ theme: XDSDefinedTheme,+ tokenName: string,+): string {+ const resolved = theme.tokens[tokenName];+ if (resolved) {+ const parsed = parseLightDark(resolved);+ // Default to light mode for display+ if (parsed) return parsed[0];+ return resolved;+ }+ const def = xdsTokenDefaults[tokenName];+ if (def) {+ const parsed = parseLightDark(def);+ if (parsed) return parsed[0];+ return def;+ }+ return '';+}++/**+ * Check if a theme has dual light/dark mode support.+ */+export function hasDualMode(theme: XDSDefinedTheme): boolean {+ const inputTokens = theme.__inputTokens;+ if (inputTokens) {+ return Object.values(inputTokens).some(v => Array.isArray(v));+ }+ return Object.values(theme.tokens).some(+ v => typeof v === 'string' && v.includes('light-dark('),+ );+}++/**+ * Get all token names matching a prefix from the theme + defaults.+ * Sorts numerically when tokens end with a number (e.g. --spacing-2 before --spacing-10).+ */+export function getTokensByPrefix(+ theme: XDSDefinedTheme,+ prefix: string,+): string[] {+ const allKeys = new Set([+ ...Object.keys(xdsTokenDefaults),+ ...Object.keys(theme.tokens),+ ]);+ return [...allKeys]+ .filter(k => k.startsWith(prefix))+ .sort((a, b) => {+ // Extract the suffix after the prefix+ const suffA = a.slice(prefix.length);+ const suffB = b.slice(prefix.length);+ // Try numeric comparison first+ const numA = parseFloat(suffA);+ const numB = parseFloat(suffB);+ if (!isNaN(numA) && !isNaN(numB)) return numA - numB;+ // Non-numeric suffixes: sort alphabetically+ return suffA.localeCompare(suffB);+ });+}diff --git a/apps/sandbox/src/app/(sandbox)/pages/doc-preview/token-tables/index.ts b/apps/sandbox/src/app/(sandbox)/pages/doc-preview/token-tables/index.tsnew file mode 100644index 0000000000..ff186f67d3--- /dev/null+++ b/apps/sandbox/src/app/(sandbox)/pages/doc-preview/token-tables/index.ts@@ -0,0 +1,7 @@+export {ColorTokenTable} from './ColorTokenTable';+export {SpacingTokenTable} from './SpacingTokenTable';+export {TypographyTokenTable} from './TypographyTokenTable';+export {ElevationTokenTable} from './ElevationTokenTable';+export {ShapeTokenTable} from './ShapeTokenTable';+export {MotionTokenTable, DurationTokenTable, EasingTokenTable} from './MotionTokenTable';+export type {TokenTableProps} from './types';diff --git a/apps/sandbox/src/app/(sandbox)/pages/doc-preview/token-tables/types.ts b/apps/sandbox/src/app/(sandbox)/pages/doc-preview/token-tables/types.tsnew file mode 100644index 0000000000..e8aba93afc--- /dev/null+++ b/apps/sandbox/src/app/(sandbox)/pages/doc-preview/token-tables/types.ts@@ -0,0 +1,6 @@+import type {XDSDefinedTheme} from '@xds/core/theme';++export interface TokenTableProps {+ /** The theme to display tokens for */+ theme: XDSDefinedTheme;+}diff --git a/packages/core/src/theme/defineTheme.ts b/packages/core/src/theme/defineTheme.tsindex 5b12fd50d0..4ccbd61c3c 100644--- a/packages/core/src/theme/defineTheme.ts+++ b/packages/core/src/theme/defineTheme.ts@@ -223,8 +223,8 @@ export interface XDSDefineThemeInput {* Radius configuration. Generates radius token overrides* from a base unit and multiplier.*- * radius-0 and radius-rounded are always fixed (never affected by multiplier).- * radius-1 through radius-4 = base * step * multiplier.+ * --radius-none and --radius-full are always fixed (never affected by multiplier).+ * --radius-inner through --radius-page = base * step * multiplier.** When omitted, themes use the hardcoded defaults (base=4, multiplier=1).* Explicit `tokens` overrides take precedence over radius-generated values.diff --git a/packages/core/src/theme/expandRadiusScale.ts b/packages/core/src/theme/expandRadiusScale.tsindex 36bf42a4a0..6f7ace000a 100644--- a/packages/core/src/theme/expandRadiusScale.ts+++ b/packages/core/src/theme/expandRadiusScale.ts@@ -5,8 +5,16 @@* @position Theme utility; consumed by defineTheme.ts** Computes border-radius values from a base unit and multiplier.- * radius-0 and radius-rounded are always fixed (never affected by multiplier).- * radius-1 through radius-4 = base * step * multiplier.+ * --radius-none and --radius-full are always fixed (never affected by multiplier).+ * --radius-inner through --radius-page = base * step * multiplier.+ *+ * Semantic scale:+ * --radius-none → 0px (fixed)+ * --radius-inner → base × 1 × multiplier (internal corners)+ * --radius-element → base × 2 × multiplier (buttons, inputs)+ * --radius-container → base × 3 × multiplier (cards, panels)+ * --radius-page → base × 7 × multiplier (page-level containers)+ * --radius-full → 9999px (fixed, pill shapes)** SYNC: When modified, update:* - /packages/core/src/theme/expandRadiusScale.test.ts@@ -35,7 +43,7 @@export interface XDSRadiusScaleConfig {/** Base radius unit in px. Default: 4 */base: number;- /** Multiplier applied to all scalable tokens. Default: 1. Range: 0-2 */+ /** Multiplier applied to scalable tokens (inner through page). Default: 1. Range: 0-2 */multiplier: number;}@@ -52,18 +60,21 @@ export type RadiusScaleTokens = Record<string, string>;/*** Expand a radius scale config into token overrides.*- * radius-0 and radius-rounded are always fixed (never affected by multiplier).- * radius-1 through radius-4 = base * step * multiplier+ * --radius-none and --radius-full are fixed anchors.+ * --radius-inner through --radius-page scale with base × step × multiplier.** @example* ```* const tokens = expandRadiusScale({ base: 4, multiplier: 1 });* // tokens['--radius-none'] === '0px'- * // tokens['--radius-inner'] === '4px'- * // tokens['--radius-element'] === '8px'- * // tokens['--radius-container'] === '12px'- * // tokens['--radius-page'] === '28px'+ * // tokens['--radius-inner'] === '4px' (4 × 1 × 1)+ * // tokens['--radius-element'] === '8px' (4 × 2 × 1)+ * // tokens['--radius-container'] === '12px' (4 × 3 × 1)+ * // tokens['--radius-page'] === '28px' (4 × 7 × 1)* // tokens['--radius-full'] === '9999px'+ *+ * const sharp = expandRadiusScale({ base: 4, multiplier: 0 });+ * // All scalable tokens become '0px', none and full unchanged* ```*/export function expandRadiusScale(diff --git a/packages/core/src/theme/index.ts b/packages/core/src/theme/index.tsindex 96cc9be0c7..c412e2b02f 100644--- a/packages/core/src/theme/index.ts+++ b/packages/core/src/theme/index.ts@@ -130,8 +130,8 @@ export type {TypeScaleVarName,} from './tokens.stylex';-export {useXDSTheme} from './useXDSTheme';-export type {UseXDSThemeReturn} from './useXDSTheme';+export {useXDSTheme, XDSThemeContext} from './useXDSTheme';+export type {UseXDSThemeReturn, XDSThemeContextValue} from './useXDSTheme';export type {ThemeMode,