An open source design system that's fully customizable and agent ready
TypeScript
feat(sandbox): polish doc preview with XDSTable, type scale labels, and embedded code blocks (#1848)
Ernestaa93b0e939f7
diff --git a/apps/sandbox/next.config.mjs b/apps/sandbox/next.config.mjsindex 1cb1786fe4..c46aea7437 100644--- a/apps/sandbox/next.config.mjs+++ b/apps/sandbox/next.config.mjs@@ -2,7 +2,7 @@ import {withXDS} from '@xds/build/next';/** @type {import('next').NextConfig} */const nextConfig = {- output: 'export',+ output: process.env.NODE_ENV === 'production' ? 'export' : undefined,reactStrictMode: false,trailingSlash: true,basePath: process.env.SANDBOX_BASE_PATH || '',diff --git a/apps/sandbox/src/app/(sandbox)/pages/doc-preview/DocPreview.tsx b/apps/sandbox/src/app/(sandbox)/pages/doc-preview/DocPreview.tsxindex 079458bd1e..e6f0fef97f 100644--- a/apps/sandbox/src/app/(sandbox)/pages/doc-preview/DocPreview.tsx+++ b/apps/sandbox/src/app/(sandbox)/pages/doc-preview/DocPreview.tsx@@ -5,7 +5,12 @@ 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 {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,@@ -36,26 +41,47 @@ const styles = stylex.create({textAlign: 'start',fontWeight: 600,fontSize: 12,- paddingBlock: 8,- paddingInline: 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: 8,- paddingInline: 12,+ 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,@@ -63,8 +89,35 @@ const styles = stylex.create({textOverflow: 'ellipsis',whiteSpace: 'nowrap' as const,},- previewCell: {- width: 48,+ 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,@@ -72,21 +125,20 @@ const styles = stylex.create({fontSize: 14,lineHeight: 1.5,},- doIcon: {- color: 'var(--color-success)',- flexShrink: 0,- fontWeight: 700,+ fullWidth: {+ width: '100%',},- dontIcon: {- color: 'var(--color-error)',- flexShrink: 0,- fontWeight: 700,+ codeBlockEmbed: {+ width: '100%',},prose: {fontSize: 14,lineHeight: 1.6,color: 'var(--color-text-primary)',},+ version: {+ fontFamily: 'var(--font-family-code)',+ },});// =============================================================================@@ -301,11 +353,290 @@ function TokenPreview({}}+// =============================================================================+// Typescale Table+// =============================================================================++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 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,+}: {+ rows: string[][];+ previewType?: TokenPreviewType;+ isDualColor: boolean;+}) {+ 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,}: {@@ -313,48 +644,18 @@ function TokenTable({rows: string[][];previewType?: TokenPreviewType;}) {- const {token} = useXDSTheme();+ if (isTypeScaleTable(rows, previewType)) {+ return <TypeScaleTable rows={rows} />;+ }++ const isDualColor = headers.length === 3 && previewType === 'swatch';return (- <div style={{overflowX: 'auto'}}>- <table {...stylex.props(styles.tokenTable)}>- <thead>- <tr>- {previewType && (- <th {...stylex.props(styles.th, styles.previewCell)} />- )}- <th {...stylex.props(styles.th)}>Token</th>- <th {...stylex.props(styles.th)}>Value</th>- </tr>- </thead>- <tbody>- {rows.map((row, i) => {- const tokenName = row[0];- // Resolve the live value from the current theme- const liveValue = token(tokenName) ?? row[1];- return (- <tr key={i}>- {previewType && (- <td {...stylex.props(styles.td, styles.previewCell)}>- <TokenPreview- type={previewType}- tokenName={tokenName}- value={liveValue}- />- </td>- )}- <td {...stylex.props(styles.td, styles.tokenName)}>- {tokenName}- </td>- <td {...stylex.props(styles.td, styles.tokenValue)}>- {liveValue}- </td>- </tr>- );- })}- </tbody>- </table>- </div>+ <TokenTableInner+ rows={rows}+ previewType={previewType}+ isDualColor={isDualColor}+ />);}@@ -376,14 +677,25 @@ function CodeBlockRenderer({label?: string;}) {return (- <XDSVStack gap={1}>- {label && (- <XDSText type="supporting" color="secondary">- {label}- </XDSText>- )}- <XDSCodeBlock code={code} language={lang} hasCopyButton />- </XDSVStack>+ <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>);}@@ -394,16 +706,46 @@ function ListBlock({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} align="start">- {listStyle === 'do' && (- <span {...stylex.props(styles.doIcon)}>✓</span>- )}- {listStyle === 'dont' && (- <span {...stylex.props(styles.dontIcon)}>✗</span>- )}+ <XDSHStack key={i} gap={2} vAlign="center">{listStyle === 'ordered' && (<XDSText type="body" color="secondary">{i + 1}.@@ -461,7 +803,43 @@ function ContentBlockRenderer({// 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@@ -470,7 +848,7 @@ function SectionRenderer({section}: {section: ReferenceSection}) {xstyle={styles.sectionTitle}>{section.title}</XDSHeading>- {section.content.map((block, i) => (+ {mergedContent.map((block, i) => (<ContentBlockRendererkey={i}block={block}@@ -485,9 +863,9 @@ function SectionRenderer({section}: {section: ReferenceSection}) {// DocPreview// =============================================================================-export function DocPreview({doc}: {doc: ReferenceDoc}) {+export function DocPreview({doc, version}: {doc: ReferenceDoc; version?: string}) {// Group sections into: token tables, usage/code, best practices, and other- const {tokenSections, usageSections, practiceSections, otherSections} =+ const {tokenSections, usageSections, practiceSections, overviewSections} =useMemo(() => {const token: ReferenceSection[] = [];const usage: ReferenceSection[] = [];@@ -513,40 +891,55 @@ export function DocPreview({doc}: {doc: ReferenceDoc}) {}}+ // 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}],+ });+ }++ 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;+ });+return {- tokenSections: token,+ tokenSections: sortedTokens,usageSections: usage,practiceSections: practice,- otherSections: other,+ overviewSections: overview,};- }, [doc.sections]);+ }, [doc.sections, doc.description]);return (<div {...stylex.props(styles.root)}><XDSVStack gap={8}>- {/* Title + Description */}- <XDSVStack gap={2}>- <XDSHeading level={1}>{doc.title}</XDSHeading>- <XDSText type="large" color="secondary">- {doc.description}- </XDSText>+ {/* Title + Version */}+ <XDSVStack gap={1}>+ <XDSText type="display-1" as="h1">{doc.title}</XDSText>+ {version && (+ <XDSText type="supporting" color="secondary" xstyle={styles.version}>+ v{version}+ </XDSText>+ )}</XDSVStack>- {/* Overview / other sections first */}- {otherSections.map((section, i) => (+ {/* Overview */}+ {overviewSections.map((section, i) => (<SectionRenderer key={`other-${i}`} section={section} />))}- {/* Token tables */}- {tokenSections.length > 0 && (- <>- <XDSDivider />- {tokenSections.map((section, i) => (- <SectionRenderer key={`token-${i}`} section={section} />- ))}- </>- )}-{/* Usage */}{usageSections.length > 0 && (<>@@ -566,6 +959,16 @@ export function DocPreview({doc}: {doc: ReferenceDoc}) {))}</>)}++ {/* Token tables */}+ {tokenSections.length > 0 && (+ <>+ <XDSDivider />+ {tokenSections.map((section, i) => (+ <SectionRenderer key={`token-${i}`} section={section} />+ ))}+ </>+ )}</XDSVStack></div>);diff --git a/apps/sandbox/src/app/(sandbox)/pages/doc-preview/page.tsx b/apps/sandbox/src/app/(sandbox)/pages/doc-preview/page.tsxindex a6c63e055d..2355ea1223 100644--- a/apps/sandbox/src/app/(sandbox)/pages/doc-preview/page.tsx+++ b/apps/sandbox/src/app/(sandbox)/pages/doc-preview/page.tsx@@ -45,13 +45,17 @@ const TOPICS = [export default function DocPreviewPage() {const [topic, setTopic] = useState<string>("color");const [docs, setDocs] = useState<Record<string, ReferenceDoc>>({});+ const [version, setVersion] = useState('');const [loading, setLoading] = useState(true);// Load pre-generated doc datauseEffect(() => {import("../../../../generated/foundationDocs.json").then((mod) => {- setDocs(mod.default as Record<string, ReferenceDoc>);+ const data = mod.default as Record<string, unknown>;+ setVersion((data.__version as string) ?? '');+ const {__version: _, ...topics} = data;+ setDocs(topics as Record<string, ReferenceDoc>);setLoading(false);}).catch(() => setLoading(false));@@ -87,7 +91,7 @@ export default function DocPreviewPage() {<XDSSpinner size="md" /></div>) : doc ? (- <DocPreview doc={doc} />+ <DocPreview doc={doc} version={version} />) : (<div {...stylex.props(styles.loading)}><XDSText color="secondary">No doc found for "{topic}"</XDSText>