An open source design system that's fully customizable and agent ready
TypeScript
feat(docsite): add theme playground tool at /themes/playground/[theme] (#2412)
Ernest26354e41b8d2
diff --git a/apps/docsite/next.config.mjs b/apps/docsite/next.config.mjsindex 67e72fcdcf..b42f9eb16a 100644--- a/apps/docsite/next.config.mjs+++ b/apps/docsite/next.config.mjs@@ -1,11 +1,26 @@// Copyright (c) Meta Platforms, Inc. and affiliates.+import {readdirSync} from 'fs';+import {resolve} from 'path';+/** @type {import('next').NextConfig} */const nextConfig = {webpack: (config) => {// Force ESM resolution for @xds/core — the CJS dist has a bug where// "use client" appears after Object.defineProperty(exports, "__esModule").config.resolve.conditionNames = ['import', 'module', 'require', 'default'];++ // Webpack's CSS @import resolver doesn't follow package.json "exports".+ // Map each theme's /theme.css subpath to the actual dist file.+ const themesDir = resolve(import.meta.dirname, '../../packages/themes');+ const themes = readdirSync(themesDir, {withFileTypes: true})+ .filter((d) => d.isDirectory())+ .map((d) => d.name);+ for (const t of themes) {+ config.resolve.alias[`@xds/theme-${t}/theme.css`] =+ resolve(themesDir, t, 'dist/theme.css');+ }+return config;},};diff --git a/apps/docsite/src/app/(site)/themes/editor/page.tsx b/apps/docsite/src/app/(site)/themes/editor/page.tsxdeleted file mode 100644index 7ff77a5bd6..0000000000--- a/apps/docsite/src/app/(site)/themes/editor/page.tsx+++ /dev/null@@ -1,26 +0,0 @@-// Copyright (c) Meta Platforms, Inc. and affiliates.--/**- * Page type: theme editor- * Live theme customization with token adjustments and preview.- * All client-side — no AI/inference needed.- * TODO: port ThemeEditorView from sandbox.- */--import {XDSHeading, XDSText} from '@xds/core/Text';-import {XDSVStack} from '@xds/core/Layout';-import {XDSSection} from '@xds/core/Section';--export default function ThemeEditorPage() {- return (- <XDSSection maxWidth="lg" padding={6}>- <XDSVStack gap={4}>- <XDSHeading level={1}>Theme Editor</XDSHeading>- <XDSText type="body" color="secondary">- Customize colors, typography, radius, and more. Preview changes live.- </XDSText>- {/* TODO: port theme editor controls + live preview */}- </XDSVStack>- </XDSSection>- );-}diff --git a/apps/docsite/src/app/(site)/themes/page.tsx b/apps/docsite/src/app/(site)/themes/page.tsxindex afe802b89e..ef04fbb7c7 100644--- a/apps/docsite/src/app/(site)/themes/page.tsx+++ b/apps/docsite/src/app/(site)/themes/page.tsx@@ -165,8 +165,8 @@ export default function ThemesPage() {</XDSText></XDSVStack>{/* Hero CTAs — two paths into theming. The primary- "Build a custom theme" sends users to the live- playground editor where they can fork any theme+ "Build a custom theme" opens the theme playground+ seeded with the neutral theme so users can fork itand tweak tokens with instant visual feedback;the secondary "How theming works" sends users tothe docs for the defineTheme + CLI wizard@@ -176,7 +176,7 @@ export default function ThemesPage() {variant="primary"size="lg"label="Build a custom theme"- href="/playground"+ href="/themes/playground/neutral"/><XDSButtonvariant="secondary"diff --git a/apps/docsite/src/app/themes/playground/[theme]/page.tsx b/apps/docsite/src/app/themes/playground/[theme]/page.tsxnew file mode 100644index 0000000000..8bdfe8daa6--- /dev/null+++ b/apps/docsite/src/app/themes/playground/[theme]/page.tsx@@ -0,0 +1,41 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * Page type: theme playground (full-bleed tool)+ * Live theme customization with token adjustments and live preview. Lives+ * outside the (site) route group so it renders full-screen without the+ * marketing top nav / footer chrome. The [theme] segment seeds the editor+ * with a full theme preset (default, neutral, gothic, matcha, stone).+ */++import {notFound} from 'next/navigation';+import {ThemeEditorView} from '../../../../components/themePlayground/ThemeEditorView';+import {+ getThemeList,+ getThemeByName,+} from '../../../../components/themePlayground/themeList';++export function generateStaticParams() {+ return getThemeList().map(entry => ({theme: entry.name}));+}++export default async function ThemePlaygroundPage({+ params,+}: {+ params: Promise<{theme: string}>;+}) {+ const {theme} = await params;+ const entry = getThemeByName(theme);++ if (!entry) {+ notFound();+ }++ return (+ <ThemeEditorView+ themeId={entry.name}+ themeLabel={entry.label}+ initialTheme={entry.theme}+ />+ );+}diff --git a/apps/docsite/src/components/ThemePackagePage.tsx b/apps/docsite/src/components/ThemePackagePage.tsxindex 379793ed19..fb49e5c91e 100644--- a/apps/docsite/src/components/ThemePackagePage.tsx+++ b/apps/docsite/src/components/ThemePackagePage.tsx@@ -251,7 +251,7 @@ export function ThemePackagePage({<XDSButtonlabel="Customize"variant="secondary"- href="/playground"+ href={`/themes/playground/${theme.name}`}/><XDSButtonlabel="Install"diff --git a/apps/docsite/src/components/ThemeShowcasePreview.tsx b/apps/docsite/src/components/ThemeShowcasePreview.tsxindex ed39a835a6..f92606868b 100644--- a/apps/docsite/src/components/ThemeShowcasePreview.tsx+++ b/apps/docsite/src/components/ThemeShowcasePreview.tsx@@ -68,6 +68,12 @@ const styles = stylex.create({maxWidth: 960,marginInline: 'auto',},+ // Fill the full available width instead of capping at 960. Used by the+ // theme playground where the preview pane is wider than the /themes/<name>+ // detail card and the grid should stretch edge-to-edge.+ contentFluid: {+ maxWidth: 'none',+ },});// Keys into the active ThemeImageSet, in the same order as PRODUCTS.@@ -101,9 +107,17 @@ const PRODUCTS = [interface ThemeShowcasePreviewProps {images: ThemeImageSet;+ /**+ * When true, the hero + product grid fill the full available width rather+ * than capping at 960px. Used by the theme playground preview pane.+ */+ fluid?: boolean;}-export function ThemeShowcasePreview({images}: ThemeShowcasePreviewProps) {+export function ThemeShowcasePreview({+ images,+ fluid = false,+}: ThemeShowcasePreviewProps) {return (<div data-theme-preview="true"><XDSVStack gap={0}>@@ -155,7 +169,9 @@ export function ThemeShowcasePreview({images}: ThemeShowcasePreviewProps) {/><XDSSection padding={8} variant="transparent">- <XDSVStack gap={10} xstyle={styles.content}>+ <XDSVStack+ gap={10}+ xstyle={fluid ? [styles.content, styles.contentFluid] : styles.content}><XDSCenter><XDSVStack gap={4} hAlign="center" xstyle={styles.heroText}><XDSText type="display-3">diff --git a/apps/docsite/src/components/themePlayground/ColorSwatch.tsx b/apps/docsite/src/components/themePlayground/ColorSwatch.tsxnew file mode 100644index 0000000000..f979af7893--- /dev/null+++ b/apps/docsite/src/components/themePlayground/ColorSwatch.tsx@@ -0,0 +1,123 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++import {XDSTextInput} from '@xds/core/TextInput';+import {TokenRow} from './TokenRow';+import {+ parseLightDark,+ parseColorWithAlpha,+ colorWithAlphaToString,+} from './helpers';++export function ColorSwatch({+ tokenName,+ value,+ onChange,+ mode,+}: {+ tokenName: string;+ value: string;+ onChange: (tokenName: string, value: string) => void;+ mode: 'light' | 'dark';+}) {+ const parsed = parseLightDark(value);+ const displayValue = parsed+ ? mode === 'light'+ ? parsed.light+ : parsed.dark+ : value;++ const colorParsed = parseColorWithAlpha(displayValue);+ const hasColorPicker = colorParsed !== null;++ const handleColorChange = (newHex: string, newAlpha?: number) => {+ const alpha = newAlpha ?? colorParsed?.alpha ?? 1;+ const newColor = colorWithAlphaToString(newHex, alpha);+ const newValue = parsed+ ? mode === 'light'+ ? `light-dark(${newColor}, ${parsed.dark})`+ : `light-dark(${parsed.light}, ${newColor})`+ : newColor;+ onChange(tokenName, newValue);+ };++ return (+ <TokenRow+ tokenName={tokenName}+ preview={+ <div+ style={{+ width: 28,+ height: 28,+ borderRadius: 6,+ backgroundColor: displayValue,+ border: '1px solid var(--color-border-emphasized)',+ flexShrink: 0,+ position: 'relative',+ cursor: hasColorPicker ? 'pointer' : undefined,+ }}>+ <div+ style={{+ width: '100%',+ height: '100%',+ borderRadius: 6,+ backgroundColor: displayValue,+ pointerEvents: 'none',+ }}+ />+ {hasColorPicker && colorParsed && (+ <input+ type="color"+ value={colorParsed.hex}+ onChange={e => handleColorChange(e.target.value)}+ style={{+ position: 'absolute',+ inset: 0,+ width: '100%',+ height: '100%',+ opacity: 0,+ cursor: 'pointer',+ border: 'none',+ padding: 0,+ zIndex: 1,+ }}+ />+ )}+ </div>+ }+ input={+ <XDSTextInput+ label={tokenName}+ isLabelHidden+ size="sm"+ value={+ hasColorPicker && colorParsed+ ? `${colorParsed.hex} ${Math.round(colorParsed.alpha * 100)}%`+ : displayValue+ }+ onChange={(val: string) => {+ const parts = val.trim().split(/\s+/);+ const hex = parts[0] || '';+ const pctStr = parts.find(p => p.endsWith('%'));+ const alpha = pctStr+ ? Math.min(100, Math.max(0, Number(pctStr.replace('%', '')))) /+ 100+ : (colorParsed?.alpha ?? 1);+ if (hex.startsWith('#') && hex.length >= 4) {+ handleColorChange(hex, alpha);+ } else {+ const newValue = parsed+ ? mode === 'light'+ ? `light-dark(${val}, ${parsed.dark})`+ : `light-dark(${parsed.light}, ${val})`+ : val;+ onChange(tokenName, newValue);+ }+ }}+ style={{width: 120}}+ />+ }+ />+ );+}diff --git a/apps/docsite/src/components/themePlayground/ComponentPreview.tsx b/apps/docsite/src/components/themePlayground/ComponentPreview.tsxnew file mode 100644index 0000000000..86c6edc679--- /dev/null+++ b/apps/docsite/src/components/themePlayground/ComponentPreview.tsx@@ -0,0 +1,944 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++import * as React from 'react';+import {useState, useEffect, useRef} from 'react';+import {XDSButton} from '@xds/core/Button';+import {XDSCard} from '@xds/core/Card';+import {XDSHStack, XDSVStack} from '@xds/core/Stack';+import {+ XDSLayout,+ XDSLayoutHeader,+ XDSLayoutContent,+ XDSLayoutFooter,+} from '@xds/core/Layout';+import {XDSText, XDSHeading} from '@xds/core/Text';+import {XDSSwitch} from '@xds/core/Switch';+import {XDSTextInput} from '@xds/core/TextInput';+import {XDSBadge} from '@xds/core/Badge';+import {XDSBanner} from '@xds/core/Banner';+import {XDSTabList, XDSTab} from '@xds/core/TabList';+import {XDSSelector} from '@xds/core/Selector';+import {XDSProgressBar} from '@xds/core/ProgressBar';+import {XDSCheckboxInput} from '@xds/core/CheckboxInput';+import {XDSDivider} from '@xds/core/Divider';+import {XDSAvatar} from '@xds/core/Avatar';+import {XDSLink} from '@xds/core/Link';+import {XDSTable} from '@xds/core/Table';+import type {XDSTableColumn} from '@xds/core/Table';+import {XDSSpinner} from '@xds/core/Spinner';+import {XDSSkeleton} from '@xds/core/Skeleton';+import {+ XDSSegmentedControl,+ XDSSegmentedControlItem,+} from '@xds/core/SegmentedControl';+import {XDSChatComposer, XDSChatComposerInput} from '@xds/core/Chat';+import {XDSSlider} from '@xds/core/Slider';+import {XDSRadioList, XDSRadioListItem} from '@xds/core/RadioList';+import {XDSToken} from '@xds/core/Token';+import {XDSTooltip} from '@xds/core/Tooltip';++import {XDSCodeBlock} from '@xds/core/CodeBlock';+import {XDSCollapsible, XDSCollapsibleGroup} from '@xds/core/Collapsible';+import {XDSStatusDot} from '@xds/core/StatusDot';+import {XDSTextArea} from '@xds/core/TextArea';+import {XDSSection} from '@xds/core/Section';++const ROW: React.CSSProperties = {+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ gap: 'var(--spacing-2)',+ flexWrap: 'wrap',+};+const FULL_W: React.CSSProperties = {width: '100%'};+const CHART: React.CSSProperties = {+ display: 'flex',+ alignItems: 'flex-end',+ gap: 'var(--spacing-1)',+ height: 80,+};+const BAR_BASE: React.CSSProperties = {+ flex: 1,+ borderRadius: 'var(--radius-inner)',+ backgroundColor: 'var(--color-accent)',+ minWidth: 0,+};+const SEC_BOX: React.CSSProperties = {+ backgroundColor: 'var(--color-background-muted)',+ borderRadius: 'var(--radius-container)',+ padding: 'var(--spacing-3)',+};+const CARD_WRAP: React.CSSProperties = {+ breakInside: 'avoid' as const,+ marginBottom: 'var(--spacing-4)',+ minWidth: 0,+ overflow: 'hidden',+};++interface TxRow extends Record<string, unknown> {+ id: string;+ name: string;+ date: string;+ amt: string;+}++const txColumns: XDSTableColumn<TxRow>[] = [+ {key: 'name', header: 'Name'},+ {key: 'date', header: 'Date'},+ {key: 'amt', header: 'Amount'},+];++const txData: TxRow[] = [+ {id: '1', name: 'Blue Bottle Coffee', date: 'Today, 10:24 AM', amt: '-$6.50'},+ {id: '2', name: 'Whole Foods Market', date: 'Yesterday', amt: '-$142.30'},+ {id: '3', name: 'Stripe Payout', date: 'Oct 12', amt: '+$4,200.00'},+ {id: '4', name: 'Netflix', date: 'Oct 10', amt: '-$15.99'},+];++export function ComponentPreview() {+ const [settingsTab, setSettingsTab] = React.useState('general');+ const [switch1, setSwitch1] = React.useState(false);+ const [switch2, setSwitch2] = React.useState(true);+ const [check1, setCheck1] = React.useState(false);+ const [check2, setCheck2] = React.useState(true);+ const containerRef = useRef<HTMLDivElement>(null);+ const [columns, setColumns] = useState(3);+ const [timeRange, setTimeRange] = useState('1M');+ const [riskTolerance, setRiskTolerance] = useState(65);+ const [rebalanceFreq, setRebalanceFreq] = useState('quarterly');+ const [composerValue, setComposerValue] = useState('');++ useEffect(() => {+ const el = containerRef.current;+ if (!el) {+ return;+ }+ const observer = new ResizeObserver(([entry]) => {+ const w = entry.contentRect.width;+ setColumns(w < 800 ? 1 : w < 1100 ? 2 : 3);+ });+ observer.observe(el);+ return () => observer.disconnect();+ }, []);++ return (+ <div+ ref={containerRef}+ style={{+ columnCount: columns,+ columnGap: 'var(--spacing-4)',+ minHeight: '100%',+ }}>+ {/* Contribution History */}+ <div style={CARD_WRAP}>+ <XDSCard>+ <XDSLayout+ height="auto"+ header={+ <XDSLayoutHeader>+ <XDSVStack gap={1}>+ <div style={ROW}>+ <XDSHeading level={3}>Contribution History</XDSHeading>+ <XDSBadge label="+12% vs last month" variant="info" />+ </div>+ <XDSText type="supporting" color="secondary">+ Last 6 months of activity+ </XDSText>+ </XDSVStack>+ </XDSLayoutHeader>+ }+ content={+ <XDSLayoutContent>+ <XDSVStack gap={3}>+ <XDSSection>+ <XDSVStack gap={3}>+ <div style={CHART}>+ {[40, 55, 60, 70, 55, 65].map((h, i) => (+ <div key={i} style={{...BAR_BASE, height: h}} />+ ))}+ </div>+ <XDSHStack gap={4} hAlign="between">+ {['Dec', 'Jan', 'Feb', 'Mar', 'Apr', 'May'].map(m => (+ <XDSText key={m} type="supporting" color="secondary">+ {m}+ </XDSText>+ ))}+ </XDSHStack>+ </XDSVStack>+ </XDSSection>+ <XDSHStack gap={3} wrap="wrap">+ <div style={{...SEC_BOX, flex: 1, minWidth: 140}}>+ <XDSVStack gap={1}>+ <XDSText type="supporting" color="secondary">+ UPCOMING+ </XDSText>+ <XDSText type="label">May 25, 2024</XDSText>+ <XDSText type="supporting" color="secondary">+ $1,000 scheduled+ </XDSText>+ </XDSVStack>+ </div>+ <div style={{...SEC_BOX, flex: 1, minWidth: 140}}>+ <XDSVStack gap={1}>+ <XDSText type="supporting" color="secondary">+ AUTO-SAVE PLAN+ </XDSText>+ <XDSText type="label">Accelerated</XDSText>+ <XDSText type="supporting" color="secondary">+ Recurring weekly+ </XDSText>+ </XDSVStack>+ </div>+ </XDSHStack>+ </XDSVStack>+ </XDSLayoutContent>+ }+ footer={+ <XDSLayoutFooter>+ <XDSButton+ label="View Full Report"+ variant="primary"+ style={FULL_W}+ />+ </XDSLayoutFooter>+ }+ />+ </XDSCard>+ </div>++ {/* Portfolio Performance — uses SegmentedControl */}+ <div style={CARD_WRAP}>+ <XDSCard>+ <XDSLayout+ height="auto"+ header={+ <XDSLayoutHeader>+ <div style={ROW}>+ <XDSHeading level={3}>Portfolio Performance</XDSHeading>+ <XDSBadge label="Live" variant="error" />+ </div>+ </XDSLayoutHeader>+ }+ content={+ <XDSLayoutContent>+ <XDSVStack gap={4}>+ <XDSVStack gap={1}>+ <XDSText type="display-2">$48,231.04</XDSText>+ <XDSHStack gap={2} vAlign="center">+ <XDSText type="body" color="secondary">+ +$3,412.50 (7.6%)+ </XDSText>+ <XDSText type="supporting" color="secondary">+ past{' '}+ {timeRange === '1W'+ ? 'week'+ : timeRange === '1M'+ ? 'month'+ : timeRange === '3M'+ ? '3 months'+ : timeRange === '1Y'+ ? 'year'+ : 'time'}+ </XDSText>+ </XDSHStack>+ </XDSVStack>+ <XDSSection>+ <div style={{...CHART, height: 100}}>+ {[30, 35, 28, 45, 42, 55, 60, 58, 65, 62, 70, 75].map(+ (h, i) => (+ <div key={i} style={{...BAR_BASE, height: `${h}%`}} />+ ),+ )}+ </div>+ </XDSSection>+ <XDSHStack hAlign="between" vAlign="center">+ <div style={{display: 'inline-flex'}}>+ <XDSSegmentedControl+ value={timeRange}+ onChange={setTimeRange}+ label="Time range">+ <XDSSegmentedControlItem value="1W" label="1W" />+ <XDSSegmentedControlItem value="1M" label="1M" />+ <XDSSegmentedControlItem value="3M" label="3M" />+ <XDSSegmentedControlItem value="1Y" label="1Y" />+ <XDSSegmentedControlItem value="ALL" label="All" />+ </XDSSegmentedControl>+ </div>+ <XDSText type="supporting" color="secondary">+ Updated just now+ </XDSText>+ </XDSHStack>+ </XDSVStack>+ </XDSLayoutContent>+ }+ />+ </XDSCard>+ </div>++ {/* Savings Targets */}+ <div style={CARD_WRAP}>+ <XDSCard>+ <XDSLayout+ height="auto"+ header={+ <XDSLayoutHeader>+ <div style={ROW}>+ <XDSHeading level={3}>Savings Targets</XDSHeading>+ <XDSButton label="New Goal" size="sm" />+ </div>+ </XDSLayoutHeader>+ }+ content={+ <XDSLayoutContent>+ <XDSVStack gap={4}>+ <XDSBanner+ status="info"+ title="On Track"+ description="Your retirement savings are ahead of schedule by $12,000 this quarter."+ />+ <XDSVStack gap={1}>+ <XDSText type="supporting" color="secondary">+ RETIREMENT+ </XDSText>+ <XDSHeading level={2}>$420,000</XDSHeading>+ <XDSProgressBar label="Retirement" value={65} />+ <div style={ROW}>+ <XDSText type="supporting" color="secondary">+ 65% achieved+ </XDSText>+ <XDSText type="supporting" color="secondary">+ $273,000+ </XDSText>+ </div>+ </XDSVStack>+ <XDSVStack gap={1}>+ <XDSText type="supporting" color="secondary">+ REAL ESTATE+ </XDSText>+ <XDSHeading level={2}>$85,000</XDSHeading>+ <XDSProgressBar label="Real Estate" value={32} />+ <div style={ROW}>+ <XDSText type="supporting" color="secondary">+ 32% achieved+ </XDSText>+ <XDSText type="supporting" color="secondary">+ $27,200+ </XDSText>+ </div>+ </XDSVStack>+ </XDSVStack>+ </XDSLayoutContent>+ }+ />+ </XDSCard>+ </div>++ {/* Buy Investment */}+ <div style={CARD_WRAP}>+ <XDSCard>+ <XDSLayout+ height="auto"+ header={+ <XDSLayoutHeader>+ <XDSHeading level={3}>Buy Investment</XDSHeading>+ </XDSLayoutHeader>+ }+ content={+ <XDSLayoutContent>+ <XDSVStack gap={4}>+ <XDSTextInput+ label="Amount to Invest"+ value="1,000.00"+ onChange={() => {}}+ />+ <XDSSelector+ label="Order Type"+ options={['Market Order', 'Limit Order', 'Stop Order']}+ value="Market Order"+ onChange={() => {}}+ />+ <XDSText type="supporting" color="secondary">+ Market orders execute at the current price.+ </XDSText>+ <XDSDivider variant="strong" />+ <div style={ROW}>+ <XDSText type="body">Estimated Shares</XDSText>+ <XDSText type="body" weight="bold">+ 1.95+ </XDSText>+ </div>+ <div style={ROW}>+ <XDSText type="body">Buying Power</XDSText>+ <XDSText type="body" weight="bold">+ $12,450.00+ </XDSText>+ </div>+ </XDSVStack>+ </XDSLayoutContent>+ }+ footer={+ <XDSLayoutFooter>+ <XDSButton+ label="Review Order"+ variant="primary"+ style={FULL_W}+ />+ </XDSLayoutFooter>+ }+ />+ </XDSCard>+ </div>++ {/* Advisor Chat — uses ChatComposer */}+ <div style={CARD_WRAP}>+ <XDSCard>+ <XDSLayout+ height="auto"+ header={+ <XDSLayoutHeader>+ <div style={ROW}>+ <XDSVStack gap={1}>+ <XDSHeading level={3}>Advisor Chat</XDSHeading>+ <XDSHStack gap={2} vAlign="center">+ <XDSStatusDot variant="success" label="Online" />+ <XDSText type="supporting" color="secondary">+ Sarah is available+ </XDSText>+ </XDSHStack>+ </XDSVStack>+ <XDSTooltip content="View chat history">+ <XDSButton label="History" variant="ghost" size="sm" />+ </XDSTooltip>+ </div>+ </XDSLayoutHeader>+ }+ content={+ <XDSLayoutContent>+ <XDSVStack gap={3}>+ <XDSSection>+ <XDSVStack gap={2}>+ <XDSText type="supporting" color="secondary">+ Sarah, Financial Advisor+ </XDSText>+ <XDSText type="body">+ Your portfolio is well-diversified. I'd recommend+ increasing your bond allocation by 5% given the current+ market conditions.+ </XDSText>+ </XDSVStack>+ </XDSSection>+ <XDSChatComposer+ onSubmit={() => setComposerValue('')}+ input={+ <XDSChatComposerInput+ placeholder="Ask your advisor..."+ value={composerValue}+ onChange={setComposerValue}+ />+ }+ />+ </XDSVStack>+ </XDSLayoutContent>+ }+ />+ </XDSCard>+ </div>++ {/* Account Activity — uses Skeleton for a loading row */}+ <div style={CARD_WRAP}>+ <XDSCard>+ <XDSLayout+ height="auto"+ header={+ <XDSLayoutHeader>+ <div style={ROW}>+ <XDSHeading level={3}>Account Activity</XDSHeading>+ <XDSHStack gap={2} vAlign="center">+ <XDSSpinner size="sm" />+ <XDSText type="supporting" color="secondary">+ Syncing...+ </XDSText>+ </XDSHStack>+ </div>+ </XDSLayoutHeader>+ }+ content={+ <XDSLayoutContent>+ <XDSVStack gap={3}>+ <XDSSection>+ <XDSVStack gap={3}>+ {[+ {+ name: 'Dividend — AAPL',+ time: '2 hours ago',+ amount: '+$32.40',+ },+ {+ name: 'Auto-invest — S&P 500',+ time: 'Yesterday',+ amount: '-$500.00',+ },+ ].map(item => (+ <XDSHStack+ key={item.name}+ gap={3}+ vAlign="center"+ hAlign="between">+ <XDSVStack gap={0}>+ <XDSText type="body">{item.name}</XDSText>+ <XDSText type="supporting" color="secondary">+ {item.time}+ </XDSText>+ </XDSVStack>+ <XDSText type="label" weight="bold">+ {item.amount}+ </XDSText>+ </XDSHStack>+ ))}+ </XDSVStack>+ </XDSSection>+ <XDSHStack gap={3} vAlign="center">+ <XDSSkeleton width={40} height={40} radius="rounded" />+ <XDSVStack gap={1} style={{flex: 1}}>+ <XDSSkeleton width="70%" height={14} radius={2} />+ <XDSSkeleton width="40%" height={10} radius={2} />+ </XDSVStack>+ <XDSSkeleton width={60} height={14} radius={2} />+ </XDSHStack>+ <XDSHStack gap={3} vAlign="center">+ <XDSSkeleton width={40} height={40} radius="rounded" />+ <XDSVStack gap={1} style={{flex: 1}}>+ <XDSSkeleton width="55%" height={14} radius={2} />+ <XDSSkeleton width="30%" height={10} radius={2} />+ </XDSVStack>+ <XDSSkeleton width={60} height={14} radius={2} />+ </XDSHStack>+ </XDSVStack>+ </XDSLayoutContent>+ }+ />+ </XDSCard>+ </div>++ {/* Recent Transactions */}+ <div style={CARD_WRAP}>+ <XDSCard padding={0}>+ <XDSLayout+ height="auto"+ header={+ <XDSLayoutHeader padding={4}>+ <div style={ROW}>+ <XDSVStack gap={1}>+ <XDSHeading level={3}>Recent Transactions</XDSHeading>+ <XDSText type="supporting" color="secondary">+ Your latest account activity.+ </XDSText>+ </XDSVStack>+ <XDSLink label="View All" href="#">+ View All+ </XDSLink>+ </div>+ </XDSLayoutHeader>+ }+ content={+ <XDSLayoutContent padding={0}>+ <div style={{overflowX: 'auto'}}>+ <XDSTable+ data={txData}+ columns={txColumns}+ textOverflow="truncate"+ />+ </div>+ </XDSLayoutContent>+ }+ />+ </XDSCard>+ </div>++ {/* Risk & Allocation — uses Slider, RadioList */}+ <div style={CARD_WRAP}>+ <XDSCard>+ <XDSLayout+ height="auto"+ header={+ <XDSLayoutHeader>+ <XDSHeading level={3}>Risk & Allocation</XDSHeading>+ </XDSLayoutHeader>+ }+ content={+ <XDSLayoutContent>+ <XDSVStack gap={4}>+ <XDSSection>+ <XDSVStack gap={1}>+ <div style={ROW}>+ <XDSText type="label">Risk Tolerance</XDSText>+ <XDSText type="supporting" color="secondary">+ {riskTolerance}%+ </XDSText>+ </div>+ <XDSSlider+ label="Risk tolerance"+ value={riskTolerance}+ onChange={setRiskTolerance}+ />+ <XDSHStack gap={0} hAlign="between">+ <XDSText type="supporting" color="secondary">+ Conservative+ </XDSText>+ <XDSText type="supporting" color="secondary">+ Aggressive+ </XDSText>+ </XDSHStack>+ </XDSVStack>+ </XDSSection>+ <XDSRadioList+ label="Rebalance frequency"+ value={rebalanceFreq}+ onChange={setRebalanceFreq}>+ <XDSRadioListItem value="monthly" label="Monthly" />+ <XDSRadioListItem value="quarterly" label="Quarterly" />+ <XDSRadioListItem value="annually" label="Annually" />+ </XDSRadioList>+ <XDSBanner+ status="warning"+ title="High allocation to tech"+ description="Consider diversifying — 62% of your portfolio is in technology stocks."+ />+ </XDSVStack>+ </XDSLayoutContent>+ }+ />+ </XDSCard>+ </div>++ {/* Team Members — uses Avatar, StatusDot */}+ <div style={CARD_WRAP}>+ <XDSCard>+ <XDSLayout+ height="auto"+ header={+ <XDSLayoutHeader>+ <div style={ROW}>+ <XDSHeading level={3}>Team Members</XDSHeading>+ <XDSButton label="Invite" size="sm" variant="secondary" />+ </div>+ </XDSLayoutHeader>+ }+ content={+ <XDSLayoutContent>+ <XDSVStack gap={3}>+ {[+ {+ name: 'Alice Chen',+ role: 'Engineering Lead',+ status: 'success' as const,+ },+ {+ name: 'Bob Martinez',+ role: 'Product Designer',+ status: 'warning' as const,+ },+ {+ name: 'Carol Wu',+ role: 'Backend Engineer',+ status: 'error' as const,+ },+ ].map(member => (+ <XDSHStack+ key={member.name}+ gap={3}+ vAlign="center"+ hAlign="between">+ <XDSHStack gap={3} vAlign="center">+ <XDSAvatar name={member.name} size="small" />+ <XDSVStack gap={0}>+ <XDSText type="body">{member.name}</XDSText>+ <XDSText type="supporting" color="secondary">+ {member.role}+ </XDSText>+ </XDSVStack>+ </XDSHStack>+ <XDSStatusDot+ variant={member.status}+ label={member.name}+ />+ </XDSHStack>+ ))}+ </XDSVStack>+ </XDSLayoutContent>+ }+ />+ </XDSCard>+ </div>++ {/* Settings */}+ <div style={CARD_WRAP}>+ <XDSCard>+ <XDSLayout+ height="auto"+ header={+ <XDSLayoutHeader>+ <XDSVStack gap={0}>+ <XDSTabList+ value={settingsTab}+ onChange={setSettingsTab}+ size="sm">+ <XDSTab value="general" label="General" />+ <XDSTab value="notifications" label="Notifications" />+ <XDSTab value="security" label="Security" />+ </XDSTabList>+ <XDSDivider />+ </XDSVStack>+ </XDSLayoutHeader>+ }+ content={+ <XDSLayoutContent>+ <XDSVStack gap={3}>+ <XDSSection>+ <XDSVStack gap={3}>+ <XDSHStack gap={3} vAlign="center" hAlign="between">+ <XDSVStack gap={0}>+ <XDSText type="body">Dark Mode</XDSText>+ <XDSText type="supporting" color="secondary">+ Enable dark theme+ </XDSText>+ </XDSVStack>+ <XDSSwitch+ label="Dark Mode"+ isLabelHidden+ value={switch1}+ onChange={setSwitch1}+ />+ </XDSHStack>+ <XDSHStack gap={3} vAlign="center" hAlign="between">+ <XDSVStack gap={0}>+ <XDSText type="body">Notifications</XDSText>+ <XDSText type="supporting" color="secondary">+ Push notifications+ </XDSText>+ </XDSVStack>+ <XDSSwitch+ label="Notifications"+ isLabelHidden+ value={switch2}+ onChange={setSwitch2}+ />+ </XDSHStack>+ </XDSVStack>+ </XDSSection>+ <XDSCheckboxInput+ label="Email updates"+ value={check1}+ onChange={setCheck1}+ />+ <XDSCheckboxInput+ label="Weekly digest"+ value={check2}+ onChange={setCheck2}+ />+ </XDSVStack>+ </XDSLayoutContent>+ }+ />+ </XDSCard>+ </div>++ {/* Tax Documents — uses Collapsible, Token, CodeBlock */}+ <div style={CARD_WRAP}>+ <XDSCard>+ <XDSLayout+ height="auto"+ header={+ <XDSLayoutHeader>+ <div style={ROW}>+ <XDSHeading level={3}>Tax Documents</XDSHeading>+ <XDSHStack gap={2} wrap="wrap">+ <XDSToken label="2024" />+ <XDSToken label="1099-B" />+ </XDSHStack>+ </div>+ </XDSLayoutHeader>+ }+ content={+ <XDSLayoutContent>+ <XDSVStack gap={3}>+ <XDSCollapsibleGroup type="single" defaultValue="summary">+ <XDSCollapsible+ trigger={+ <XDSText type="body" weight="bold">+ Capital Gains Summary+ </XDSText>+ }+ value="summary">+ <XDSVStack+ gap={3}+ style={{paddingBlock: 'var(--spacing-3)'}}>+ <div style={ROW}>+ <XDSText type="body">Short-term gains</XDSText>+ <XDSText type="body" weight="bold">+ $1,240.00+ </XDSText>+ </div>+ <div style={ROW}>+ <XDSText type="body">Long-term gains</XDSText>+ <XDSText type="body" weight="bold">+ $8,920.00+ </XDSText>+ </div>+ <XDSDivider />+ <div style={ROW}>+ <XDSText type="label">Total taxable</XDSText>+ <XDSText type="label" weight="bold">+ $10,160.00+ </XDSText>+ </div>+ </XDSVStack>+ </XDSCollapsible>+ <XDSCollapsible+ trigger={+ <XDSText type="body" weight="bold">+ Dividend Income+ </XDSText>+ }+ value="dividends">+ <XDSVStack+ gap={3}+ style={{paddingBlock: 'var(--spacing-3)'}}>+ <div style={ROW}>+ <XDSText type="body">Qualified dividends</XDSText>+ <XDSText type="body" weight="bold">+ $2,450.00+ </XDSText>+ </div>+ <div style={ROW}>+ <XDSText type="body">Ordinary dividends</XDSText>+ <XDSText type="body" weight="bold">+ $680.00+ </XDSText>+ </div>+ </XDSVStack>+ </XDSCollapsible>+ <XDSCollapsible+ trigger={+ <XDSText type="body" weight="bold">+ Export Format+ </XDSText>+ }+ value="export">+ <div style={{paddingBlock: 'var(--spacing-3)'}}>+ <XDSCodeBlock+ code={`Tax Year: 2024\nAccount: ***4821\nTotal Gains: $10,160.00\nDividends: $3,130.00`}+ language="text"+ size="sm"+ />+ </div>+ </XDSCollapsible>+ </XDSCollapsibleGroup>+ </XDSVStack>+ </XDSLayoutContent>+ }+ />+ </XDSCard>+ </div>++ {/* Support Ticket — uses TextArea, Section */}+ <div style={CARD_WRAP}>+ <XDSCard>+ <XDSLayout+ height="auto"+ header={+ <XDSLayoutHeader>+ <div style={ROW}>+ <XDSHeading level={3}>Submit a Request</XDSHeading>+ <XDSBadge label="Support" variant="info" />+ </div>+ </XDSLayoutHeader>+ }+ content={+ <XDSLayoutContent>+ <XDSVStack gap={4}>+ <XDSSelector+ label="Category"+ options={[+ 'Account Access',+ 'Transfers',+ 'Tax Forms',+ 'Other',+ ]}+ value="Account Access"+ onChange={() => {}}+ />+ <XDSTextInput+ label="Subject"+ value=""+ placeholder="Brief description"+ onChange={() => {}}+ />+ <XDSSection>+ <XDSTextArea+ label="Details"+ placeholder="Describe your issue..."+ value=""+ />+ </XDSSection>+ </XDSVStack>+ </XDSLayoutContent>+ }+ footer={+ <XDSLayoutFooter>+ <XDSHStack gap={2} hAlign="end">+ <XDSButton label="Cancel" variant="ghost" />+ <XDSButton label="Submit" variant="primary" />+ </XDSHStack>+ </XDSLayoutFooter>+ }+ />+ </XDSCard>+ </div>++ {/* Buttons */}+ <div style={CARD_WRAP}>+ <XDSCard>+ <XDSLayout+ height="auto"+ header={+ <XDSLayoutHeader>+ <XDSHeading level={3}>Quick Actions</XDSHeading>+ </XDSLayoutHeader>+ }+ content={+ <XDSLayoutContent>+ <XDSVStack gap={3}>+ <XDSHStack gap={2} wrap="wrap">+ <XDSButton label="Transfer" variant="primary" size="md" />+ <XDSButton label="Deposit" variant="secondary" size="md" />+ <XDSButton label="Statements" variant="ghost" size="md" />+ </XDSHStack>+ <XDSHStack gap={2} wrap="wrap">+ <XDSButton label="Small" variant="primary" size="sm" />+ <XDSButton label="Medium" variant="primary" size="md" />+ <XDSButton label="Large" variant="primary" size="lg" />+ </XDSHStack>+ <XDSHStack gap={2} wrap="wrap">+ <XDSButton+ label="Processing..."+ variant="primary"+ isDisabled+ />+ <XDSButton+ label="Unavailable"+ variant="secondary"+ isDisabled+ />+ </XDSHStack>+ </XDSVStack>+ </XDSLayoutContent>+ }+ />+ </XDSCard>+ </div>+ </div>+ );+}diff --git a/apps/docsite/src/components/themePlayground/ComponentTokensPanel.tsx b/apps/docsite/src/components/themePlayground/ComponentTokensPanel.tsxnew file mode 100644index 0000000000..e55066d502--- /dev/null+++ b/apps/docsite/src/components/themePlayground/ComponentTokensPanel.tsx@@ -0,0 +1,276 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++import * as React from 'react';+import * as stylex from '@stylexjs/stylex';+import {XDSText, XDSHeading} from '@xds/core/Text';+import {XDSVStack, XDSHStack} from '@xds/core/Stack';+import {XDSSelector} from '@xds/core/Selector';+import {XDSTextInput} from '@xds/core/TextInput';+import {XDSButton} from '@xds/core/Button';+import {XDSDivider} from '@xds/core/Divider';+import {+ COMPONENT_VARS,+ ALL_COMPONENT_NAMES,+ COMPONENT_VAR_TO_OVERRIDE,+ resolveOptionLabel,+} from './constants';++const styles = stylex.create({+ fullWidthField: {width: '100%'},+});++// Width of the value control column in each component-token row.+const CONTROL_WIDTH = 180;++/**+ * Read the value a seeded theme set for a component-token control, by reverse-+ * mapping the playground var (e.g. `--card-radius`) through+ * COMPONENT_VAR_TO_OVERRIDE to the component + CSS property it controls, then+ * looking it up in the theme's `base` overrides. Lets the controls reflect the+ * selected theme instead of always showing the generic default.+ */+function readSeededValue(+ baseComponents: Record<string, unknown>,+ varName: string,+): string | undefined {+ const mapping = COMPONENT_VAR_TO_OVERRIDE[varName]?.[0];+ if (!mapping) {+ return undefined;+ }+ const comp = baseComponents[mapping.component];+ if (!comp || typeof comp !== 'object') {+ return undefined;+ }+ const base = (comp as Record<string, unknown>).base;+ if (!base || typeof base !== 'object') {+ return undefined;+ }+ const value = (base as Record<string, unknown>)[mapping.cssProperty];+ return typeof value === 'string' ? value : undefined;+}++export interface CustomOverride {+ id: string;+ component: string;+ property: string;+ value: string;+}++interface ComponentTokensPanelProps {+ tokens: Record<string, string>;+ onTokenChange: (name: string, value: string) => void;+ customOverrides: CustomOverride[];+ onCustomOverridesChange: (overrides: CustomOverride[]) => void;+ /** Component overrides from the seeded preset theme (theme.components). */+ baseComponents: Record<string, unknown>;+}++export function ComponentTokensPanel({+ tokens,+ onTokenChange,+ customOverrides,+ onCustomOverridesChange,+ baseComponents,+}: ComponentTokensPanelProps) {+ const [customVars, setCustomVars] = React.useState<Set<string>>(new Set());+ const [newComponent, setNewComponent] = React.useState('button');+ const [newProperty, setNewProperty] = React.useState('');+ const [newValue, setNewValue] = React.useState('');+ // Initialize from existing overrides to avoid duplicate keys after remount+ const nextIdRef = React.useRef(+ customOverrides.reduce((max, o) => {+ const num = parseInt(o.id.replace('custom-', ''), 10);+ return isNaN(num) ? max : Math.max(max, num + 1);+ }, 0),+ );++ const handleAddCustom = React.useCallback(() => {+ if (!newComponent || !newProperty || !newValue) {return;}+ onCustomOverridesChange([+ ...customOverrides,+ {+ id: `custom-${nextIdRef.current++}`,+ component: newComponent,+ property: newProperty,+ value: newValue,+ },+ ]);+ setNewProperty('');+ setNewValue('');+ }, [+ newComponent,+ newProperty,+ newValue,+ customOverrides,+ onCustomOverridesChange,+ ]);++ const handleRemoveCustom = React.useCallback(+ (index: number) => {+ onCustomOverridesChange(customOverrides.filter((_, i) => i !== index));+ },+ [customOverrides, onCustomOverridesChange],+ );++ const handleUpdateCustomValue = React.useCallback(+ (index: number, value: string) => {+ const updated = [...customOverrides];+ updated[index] = {...updated[index], value};+ onCustomOverridesChange(updated);+ },+ [customOverrides, onCustomOverridesChange],+ );++ return (+ <XDSVStack gap={4}>+ {Object.entries(COMPONENT_VARS).map(([key, comp]) => (+ <XDSVStack key={key} gap={2}>+ <XDSHeading level={4}>{comp.label}</XDSHeading>+ <XDSVStack gap={1}>+ {comp.vars.map(v => {+ // Prefer an explicit token edit; otherwise fall back to the+ // value the seeded theme set for this control (if any).+ const currentValue =+ tokens[v.name] || readSeededValue(baseComponents, v.name) || '';+ const isCustom = customVars.has(v.name);+ const isPresetValue =+ !isCustom &&+ (!currentValue ||+ v.options.some(o => o.value === currentValue));++ return (+ <div+ key={v.name}+ style={{+ padding: '6px 0',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ gap: 10,+ }}>+ <div style={{flex: 1, minWidth: 0}}>+ <XDSText type="label" color="secondary" maxLines={1}>+ {v.description}+ </XDSText>+ </div>+ <div style={{flexShrink: 0, width: CONTROL_WIDTH}}>+ {!isPresetValue ? (+ <XDSTextInput+ label={v.name}+ isLabelHidden+ size="sm"+ value={currentValue}+ placeholder={v.default}+ onChange={(val: string) => {+ if (val.trim() === '') {+ onTokenChange(v.name, '');+ setCustomVars(prev => {+ const next = new Set(prev);+ next.delete(v.name);+ return next;+ });+ } else {+ onTokenChange(v.name, val);+ }+ }}+ />+ ) : (+ <XDSSelector+ label={v.name}+ isLabelHidden+ size="sm"+ xstyle={styles.fullWidthField}+ options={[+ ...v.options.map(o => ({+ value: o.value,+ label: resolveOptionLabel(o, tokens),+ })),+ {value: '__custom__', label: 'Custom...'},+ ]}+ value={currentValue || v.default}+ onChange={(val: string) => {+ if (val === '__custom__') {+ setCustomVars(prev => new Set(prev).add(v.name));+ } else {+ onTokenChange(v.name, val);+ }+ }}+ />+ )}+ </div>+ </div>+ );+ })}+ </XDSVStack>+ </XDSVStack>+ ))}++ <XDSDivider />++ <XDSVStack gap={3}>+ <XDSHeading level={4}>Custom Overrides</XDSHeading>+ <XDSText type="supporting" color="secondary">+ Override any CSS property on any component.+ </XDSText>++ {customOverrides.map((override, i) => (+ <XDSVStack key={override.id} gap={1}>+ <XDSHStack gap={2} vAlign="end">+ <div style={{flex: 1, minWidth: 0}}>+ <XDSText type="supporting" color="secondary" maxLines={1}>+ .xds-{override.component} → {override.property}+ </XDSText>+ </div>+ <XDSButton+ label="Remove"+ variant="ghost"+ size="sm"+ onClick={() => handleRemoveCustom(i)}+ />+ </XDSHStack>+ <XDSTextInput+ label={`${override.component} ${override.property}`}+ isLabelHidden+ size="sm"+ value={override.value}+ onChange={(val: string) => handleUpdateCustomValue(i, val)}+ />+ </XDSVStack>+ ))}++ <XDSVStack gap={2}>+ <XDSSelector+ label="Component"+ size="sm"+ value={newComponent}+ onChange={setNewComponent}+ options={ALL_COMPONENT_NAMES.map(n => ({value: n, label: n}))}+ />+ <XDSTextInput+ label="CSS property (camelCase)"+ size="sm"+ value={newProperty}+ placeholder="e.g. borderRadius"+ onChange={setNewProperty}+ />+ <XDSTextInput+ label="CSS value"+ size="sm"+ value={newValue}+ placeholder="e.g. 9999px"+ onChange={setNewValue}+ />+ <XDSButton+ label="Add Override"+ variant="secondary"+ size="sm"+ onClick={handleAddCustom}+ isDisabled={!newProperty || !newValue}+ />+ </XDSVStack>+ </XDSVStack>+ </XDSVStack>+ );+}diff --git a/apps/docsite/src/components/themePlayground/EditorSections.tsx b/apps/docsite/src/components/themePlayground/EditorSections.tsxnew file mode 100644index 0000000000..1a20b5459c--- /dev/null+++ b/apps/docsite/src/components/themePlayground/EditorSections.tsx@@ -0,0 +1,614 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++import * as React from 'react';+import * as stylex from '@stylexjs/stylex';+import {XDSText} from '@xds/core/Text';+import {XDSVStack, XDSHStack} from '@xds/core/Stack';+import {XDSSelector} from '@xds/core/Selector';+import {XDSNumberInput} from '@xds/core/NumberInput';+import {XDSSwitch} from '@xds/core/Switch';+import {XDSToggleButton, XDSToggleButtonGroup} from '@xds/core/ToggleButton';+import {XDSTooltip} from '@xds/core/Tooltip';+import {XDSIcon} from '@xds/core/Icon';+import {expandRadiusScale, expandTypeScale} from '@xds/core/theme';+import {ColorSwatch} from './ColorSwatch';+import {XDSSelectableCard} from '@xds/core/SelectableCard';+import {FONT_OPTIONS, RATIO_OPTIONS, UNIFIED_PRESETS} from './constants';++const styles = stylex.create({+ fullWidthField: {width: '100%'},+});++interface EditorSectionsProps {+ tokens: Record<string, string>;+ mode: 'light' | 'dark';+ typeScaleBase: number;+ typeScaleRatio: number;+ radiusBase: number;+ spacingBase: number;+ sizeBase: number;+ durationStep: number;+ activePreset: string | null;+ autoPickColors: boolean;+ onTokenChange: (name: string, value: string) => void;+ onApplyTypeScale: (base: number, ratio: number) => void;+ onApplyRadiusScale: (base: number) => void;+ onApplySpacingScale: (base: number) => void;+ onApplySizeScale: (base: number) => void;+ onApplyDurationScale: (multiplier: number) => void;+ onApplyUnifiedPreset: (key: string) => void;+ onSetAutoPickColors: (val: boolean) => void;+ onExpandColorScale: (accent: string) => void;+ onSetTokens: React.Dispatch<React.SetStateAction<Record<string, string>>>;+}++export function EditorSections({+ tokens,+ mode,+ typeScaleBase,+ typeScaleRatio,+ radiusBase,+ spacingBase,+ sizeBase,+ durationStep,+ activePreset,+ autoPickColors,+ onTokenChange,+ onApplyTypeScale,+ onApplyRadiusScale,+ onApplySpacingScale,+ onApplySizeScale,+ onApplyDurationScale,+ onApplyUnifiedPreset,+ onSetAutoPickColors,+ onExpandColorScale,+}: EditorSectionsProps) {+ // Reflect the active token values in the typography controls. Fonts map+ // directly to a token; the type scale ratio is derived from the raw+ // --font-size-* tokens (present only when a theme customizes its scale).+ const fontValue = (token: string): string | undefined =>+ FONT_OPTIONS.some(o => o.value === tokens[token])+ ? tokens[token]+ : undefined;++ const baseRem = parseFloat(tokens['--font-size-base'] ?? '');+ const lgRem = parseFloat(tokens['--font-size-lg'] ?? '');+ const tokenTypeRatio =+ Number.isFinite(baseRem) && Number.isFinite(lgRem) && baseRem > 0+ ? lgRem / baseRem+ : null;+ const tokenTypeBase =+ Number.isFinite(baseRem) && baseRem > 0+ ? Math.round(baseRem * 16)+ : typeScaleBase;+ const matchedRatio =+ tokenTypeRatio != null+ ? RATIO_OPTIONS.find(o => Math.abs(o.value - tokenTypeRatio) < 0.02)+ : undefined;++ // The scale controls below should only show a value when the seeded theme's+ // tokens actually follow the generator algorithm. A theme can ship hand-+ // tuned tokens that don't fit any base — in that case the matching base is+ // null and the control renders "unset" (no preset highlighted, empty input)+ // so it never implies a base the theme isn't really using.++ // Type size — matches when the raw font-size ramp follows the geometric+ // scale for the derived base + nearest standard ratio.+ const typeSizeMatch = (() => {+ if (tokenTypeRatio == null || !matchedRatio) {+ return null;+ }+ const expected = expandTypeScale({+ base: tokenTypeBase,+ ratio: matchedRatio.value,+ });+ const keys = [+ '--font-size-xs',+ '--font-size-sm',+ '--font-size-base',+ '--font-size-lg',+ '--font-size-xl',+ '--font-size-2xl',+ ];+ return keys.every(k => tokens[k] === expected[k]) ? tokenTypeBase : null;+ })();++ // Corner radius — linear scale anchored on --radius-inner (= base).+ const radiusMatch = (() => {+ const inner = parseInt(tokens['--radius-inner'] ?? '', 10);+ if (!Number.isFinite(inner)) {+ return null;+ }+ const expected = expandRadiusScale({base: inner, multiplier: 1});+ const keys = [+ '--radius-inner',+ '--radius-element',+ '--radius-container',+ '--radius-page',+ ];+ return keys.every(k => tokens[k] === expected[k]) ? inner : null;+ })();++ // Spacing — linear scale where step N = base × N (base = --spacing-1).+ const spacingMatch = (() => {+ const base = parseInt(tokens['--spacing-1'] ?? '', 10);+ if (!Number.isFinite(base)) {+ return null;+ }+ const steps: Record<string, number> = {+ '--spacing-0': 0,+ '--spacing-0-5': 0.5,+ '--spacing-1': 1,+ '--spacing-1-5': 1.5,+ '--spacing-2': 2,+ '--spacing-3': 3,+ '--spacing-4': 4,+ '--spacing-5': 5,+ '--spacing-6': 6,+ '--spacing-7': 7,+ '--spacing-8': 8,+ '--spacing-9': 9,+ '--spacing-10': 10,+ '--spacing-11': 11,+ '--spacing-12': 12,+ };+ const ok = Object.entries(steps).every(+ ([k, step]) => tokens[k] === `${Math.round(base * step)}px`,+ );+ return ok ? base : null;+ })();++ // Element size — md = base, sm = base − 4, lg = base + 4.+ const sizeMatch = (() => {+ const md = parseInt(tokens['--size-element-md'] ?? '', 10);+ const sm = parseInt(tokens['--size-element-sm'] ?? '', 10);+ const lg = parseInt(tokens['--size-element-lg'] ?? '', 10);+ if (!Number.isFinite(md)) {+ return null;+ }+ return sm === md - 4 && lg === md + 4 ? md : null;+ })();++ return (+ <XDSVStack gap={5}>+ {/* Color Section */}+ <XDSVStack gap={3}>+ <XDSHStack+ vAlign="center"+ style={{marginBottom: 4, justifyContent: 'space-between'}}>+ <XDSText type="label" color="secondary">+ Create from accent+ </XDSText>+ <XDSSwitch+ label="Create from accent"+ isLabelHidden+ value={autoPickColors}+ onChange={val => {+ onSetAutoPickColors(val);+ if (val) {+ const accentRaw = tokens['--color-accent'] || '';+ const parsed = accentRaw.match(+ /^light-dark\(([^,]+),\s*([^)]+)\)$/,+ );+ const accentHex = parsed ? parsed[1].trim() : accentRaw;+ if (accentHex && accentHex.startsWith('#')) {+ onExpandColorScale(accentHex);+ }+ }+ }}+ />+ </XDSHStack>+ <XDSVStack gap={0}>+ <ColorSwatch+ tokenName="--color-accent"+ value={tokens['--color-accent'] || ''}+ onChange={(name, value) => {+ onTokenChange(name, value);+ if (autoPickColors) {+ const parsed = value.match(+ /^light-dark\(([^,]+),\s*([^)]+)\)$/,+ );+ const hex = parsed ? parsed[1].trim() : value;+ if (hex && hex.startsWith('#') && hex.length >= 7) {+ onExpandColorScale(hex);+ }+ }+ }}+ mode={mode}+ />+ {!autoPickColors && (+ <>+ {[+ '--color-neutral',+ '--color-background-card',+ '--color-background-surface',+ '--color-text-primary',+ ].map(tokenName => (+ <ColorSwatch+ key={tokenName}+ tokenName={tokenName}+ value={tokens[tokenName] || ''}+ onChange={onTokenChange}+ mode={mode}+ />+ ))}+ </>+ )}+ </XDSVStack>+ </XDSVStack>++ {/* Presets Section */}+ <XDSVStack gap={3}>+ <XDSText type="label" color="secondary">+ Preset+ </XDSText>+ <div+ style={{+ display: 'grid',+ gridTemplateColumns: 'repeat(4, 1fr)',+ gap: 8,+ }}>+ {Object.entries(UNIFIED_PRESETS).map(([key]) => {+ const isSelected = activePreset === key;+ const gap =+ key === 'compact'+ ? 1+ : key === 'default'+ ? 2+ : key === 'comfortable'+ ? 3+ : 4;+ const cornerR =+ key === 'compact'+ ? 1+ : key === 'default'+ ? 2+ : key === 'comfortable'+ ? 3+ : 5;+ const fillColor = isSelected+ ? 'var(--color-accent)'+ : 'var(--color-text-disabled)';+ return (+ <XDSSelectableCard+ key={key}+ label={`${key.charAt(0).toUpperCase() + key.slice(1)} preset`}+ isSelected={isSelected}+ onChange={() => onApplyUnifiedPreset(key)}+ padding={2}>+ <div+ style={{+ display: 'flex',+ flexDirection: 'column' as const,+ alignItems: 'center',+ gap: 6,+ }}>+ <svg width={32} height={32} viewBox="0 0 32 32">+ <rect+ x={0}+ y={0}+ width={32}+ height={8}+ rx={cornerR}+ fill={fillColor}+ opacity={0.5}+ />+ <rect+ x={0}+ y={8 + gap}+ width={15 - gap / 2}+ height={32 - 8 - gap}+ rx={cornerR}+ fill={fillColor}+ />+ <rect+ x={15 + gap / 2}+ y={8 + gap}+ width={32 - 15 - gap / 2}+ height={(32 - 8 - gap * 2) / 2}+ rx={cornerR}+ fill={fillColor}+ opacity={0.7}+ />+ <rect+ x={15 + gap / 2}+ y={8 + gap + (32 - 8 - gap * 2) / 2 + gap}+ width={32 - 15 - gap / 2}+ height={(32 - 8 - gap * 2) / 2}+ rx={cornerR}+ fill={fillColor}+ opacity={0.7}+ />+ </svg>+ <XDSText+ type="supporting"+ color={isSelected ? 'primary' : 'secondary'}>+ {key.charAt(0).toUpperCase() + key.slice(1)}+ </XDSText>+ </div>+ </XDSSelectableCard>+ );+ })}+ </div>+ </XDSVStack>++ {/* Typography Section */}+ <XDSVStack gap={3}>+ <XDSVStack gap={4}>+ <XDSVStack gap={3}>+ {[+ {token: '--font-family-heading', label: 'Heading Font'},+ {token: '--font-family-body', label: 'Body Font'},+ ].map(({token, label}) => (+ <div key={token}>+ <XDSText+ type="label"+ color="secondary"+ style={{marginBottom: 4, display: 'block'}}>+ {label}+ </XDSText>+ <XDSSelector+ label={label}+ isLabelHidden+ size="sm"+ placeholder="Custom"+ xstyle={styles.fullWidthField}+ options={FONT_OPTIONS}+ value={fontValue(token)}+ onChange={(val: string) => onTokenChange(token, val)}+ />+ </div>+ ))}+ <div>+ <XDSText+ type="label"+ color="secondary"+ style={{marginBottom: 4, display: 'block'}}>+ Type Scale+ </XDSText>+ <XDSSelector+ label="Type Scale"+ isLabelHidden+ size="sm"+ placeholder="Default"+ xstyle={styles.fullWidthField}+ options={[+ ...RATIO_OPTIONS.map(opt => ({+ value: String(opt.value),+ label: opt.label,+ })),+ ...(tokenTypeRatio != null && !matchedRatio+ ? [+ {+ value: 'custom',+ label: `Custom — ${tokenTypeRatio.toFixed(3)}`,+ },+ ]+ : []),+ ]}+ value={+ tokenTypeRatio == null+ ? undefined+ : matchedRatio+ ? String(matchedRatio.value)+ : 'custom'+ }+ onChange={(v: string) => {+ if (v !== 'custom') {+ onApplyTypeScale(tokenTypeBase, Number(v));+ }+ }}+ />+ </div>+ </XDSVStack>+ <div>+ <XDSHStack gap={1} vAlign="center" style={{marginBottom: 4}}>+ <XDSText type="label" color="secondary">+ Type Size+ </XDSText>+ <XDSTooltip+ content={`Geometric scale: size = round(base × ratio^step). Base = ${typeSizeMatch ?? typeScaleBase}px, ratio = ${typeScaleRatio.toFixed(3)}.`}>+ <XDSIcon icon="info" size="sm" color="secondary" />+ </XDSTooltip>+ </XDSHStack>+ <div style={{display: 'flex', alignItems: 'center', gap: 8}}>+ <XDSToggleButtonGroup+ label="Type size preset"+ type="single"+ size="sm"+ value={typeSizeMatch != null ? String(typeSizeMatch) : null}+ onChange={(v: string | null) => {+ if (v != null) {onApplyTypeScale(Number(v), typeScaleRatio);}+ }}>+ <XDSToggleButton label="S" value="12" />+ <XDSToggleButton label="M" value="14" />+ <XDSToggleButton label="L" value="16" />+ <XDSToggleButton label="XL" value="18" />+ </XDSToggleButtonGroup>+ <div style={{flex: 1}} />+ <XDSNumberInput+ label="Type size"+ isLabelHidden+ value={typeSizeMatch ?? null}+ placeholder="—"+ onChange={(v: number) => onApplyTypeScale(v, typeScaleRatio)}+ min={10}+ max={24}+ step={1}+ units="px"+ size="sm"+ />+ </div>+ </div>+ </XDSVStack>+ </XDSVStack>++ {/* Shape & Layout Section */}+ <XDSVStack gap={3}>+ <XDSVStack gap={4}>+ <div>+ <XDSHStack gap={1} vAlign="center" style={{marginBottom: 4}}>+ <XDSText type="label" color="secondary">+ Corner Radius+ </XDSText>+ <XDSTooltip+ content={`Linear scale: inner = ${radiusMatch ?? radiusBase}px, element = ${(radiusMatch ?? radiusBase) * 2}px, container = ${(radiusMatch ?? radiusBase) * 3}px, page = ${Math.round((radiusMatch ?? radiusBase) * 7)}px.`}>+ <XDSIcon icon="info" size="sm" color="secondary" />+ </XDSTooltip>+ </XDSHStack>+ <div style={{display: 'flex', alignItems: 'center', gap: 8}}>+ <XDSToggleButtonGroup+ label="Radius preset"+ type="single"+ size="sm"+ value={radiusMatch != null ? String(radiusMatch) : null}+ onChange={(v: string | null) => {+ if (v != null) {onApplyRadiusScale(Number(v));}+ }}>+ <XDSToggleButton label="S" value="2" />+ <XDSToggleButton label="M" value="4" />+ <XDSToggleButton label="L" value="6" />+ <XDSToggleButton label="XL" value="12" />+ </XDSToggleButtonGroup>+ <div style={{flex: 1}} />+ <XDSNumberInput+ label="Radius"+ isLabelHidden+ value={radiusMatch ?? null}+ placeholder="—"+ onChange={(v: number) => onApplyRadiusScale(v)}+ min={0}+ max={18}+ step={2}+ units="px"+ size="sm"+ />+ </div>+ </div>+ <div>+ <XDSHStack gap={1} vAlign="center" style={{marginBottom: 4}}>+ <XDSText type="label" color="secondary">+ Spacing+ </XDSText>+ <XDSTooltip+ content={`Linear scale: step N = ${spacingMatch ?? spacingBase}px × N.`}>+ <XDSIcon icon="info" size="sm" color="secondary" />+ </XDSTooltip>+ </XDSHStack>+ <div style={{display: 'flex', alignItems: 'center', gap: 8}}>+ <XDSToggleButtonGroup+ label="Spacing preset"+ type="single"+ size="sm"+ value={spacingMatch != null ? String(spacingMatch) : null}+ onChange={(v: string | null) => {+ if (v != null) {onApplySpacingScale(Number(v));}+ }}>+ <XDSToggleButton label="S" value="2" />+ <XDSToggleButton label="M" value="4" />+ <XDSToggleButton label="L" value="6" />+ <XDSToggleButton label="XL" value="8" />+ </XDSToggleButtonGroup>+ <div style={{flex: 1}} />+ <XDSNumberInput+ label="Spacing"+ isLabelHidden+ value={spacingMatch ?? null}+ placeholder="—"+ onChange={(v: number) => onApplySpacingScale(v)}+ min={0}+ max={16}+ step={2}+ units="px"+ size="sm"+ />+ </div>+ </div>+ <div>+ <XDSHStack gap={1} vAlign="center" style={{marginBottom: 4}}>+ <XDSText type="label" color="secondary">+ Element Size+ </XDSText>+ <XDSTooltip+ content={`sm = ${(sizeMatch ?? sizeBase) - 4}px, md = ${sizeMatch ?? sizeBase}px, lg = ${(sizeMatch ?? sizeBase) + 4}px.`}>+ <XDSIcon icon="info" size="sm" color="secondary" />+ </XDSTooltip>+ </XDSHStack>+ <div style={{display: 'flex', alignItems: 'center', gap: 8}}>+ <XDSToggleButtonGroup+ label="Element size preset"+ type="single"+ size="sm"+ value={sizeMatch != null ? String(sizeMatch) : null}+ onChange={(v: string | null) => {+ if (v != null) {onApplySizeScale(Number(v));}+ }}>+ <XDSToggleButton label="S" value="28" />+ <XDSToggleButton label="M" value="32" />+ <XDSToggleButton label="L" value="40" />+ <XDSToggleButton label="XL" value="48" />+ </XDSToggleButtonGroup>+ <div style={{flex: 1}} />+ <XDSNumberInput+ label="Element size"+ isLabelHidden+ value={sizeMatch ?? null}+ placeholder="—"+ onChange={(v: number) => onApplySizeScale(v)}+ min={24}+ max={56}+ step={2}+ units="px"+ size="sm"+ />+ </div>+ </div>+ </XDSVStack>+ </XDSVStack>++ {/* Motion Section */}+ <XDSVStack gap={3}>+ <XDSHStack gap={1} vAlign="center" style={{marginBottom: 4}}>+ <XDSText type="label" color="secondary">+ Duration+ </XDSText>+ <XDSTooltip+ content={`Speed multiplier for all motion. Current: ${durationStep}× (e.g. medium = ${Math.round(410 / durationStep)}ms).`}>+ <XDSIcon icon="info" size="sm" color="secondary" />+ </XDSTooltip>+ </XDSHStack>+ <div style={{display: 'flex', alignItems: 'center', gap: 8}}>+ <XDSToggleButtonGroup+ label="Duration preset"+ type="single"+ size="sm"+ value={String(durationStep)}+ onChange={(v: string | null) => {+ if (v != null) {onApplyDurationScale(Number(v));}+ }}>+ <XDSToggleButton label="0.5×" value="0.5" />+ <XDSToggleButton label="1×" value="1" />+ <XDSToggleButton label="1.5×" value="1.5" />+ <XDSToggleButton label="2×" value="2" />+ </XDSToggleButtonGroup>+ <div style={{flex: 1}} />+ <XDSNumberInput+ label="Duration"+ isLabelHidden+ value={durationStep}+ onChange={(v: number) =>+ onApplyDurationScale(Math.round(v * 10) / 10)+ }+ min={0.5}+ max={2}+ step={0.1}+ units="×"+ size="sm"+ />+ </div>+ </XDSVStack>+ </XDSVStack>+ );+}diff --git a/apps/docsite/src/components/themePlayground/RawTokensPanel.tsx b/apps/docsite/src/components/themePlayground/RawTokensPanel.tsxnew file mode 100644index 0000000000..2232ab4eb0--- /dev/null+++ b/apps/docsite/src/components/themePlayground/RawTokensPanel.tsx@@ -0,0 +1,348 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++import * as React from 'react';+import {XDSText} from '@xds/core/Text';+import {XDSVStack} from '@xds/core/Stack';+import {XDSTextInput} from '@xds/core/TextInput';+import {XDSToggleButton, XDSToggleButtonGroup} from '@xds/core/ToggleButton';+import {+ PaletteOutline16Icon,+ FourRectangleGridOutline16Icon,+ FrameDashedOutline16Icon,+ BigALittleAOutline16Icon,+ AspectRatioOutline16Icon,+ SquareOutline16Icon,+ StopwatchOutline16Icon,+ BoltOutline16Icon,+} from './icons';+import {+ colorDefaults,+ spacingDefaults,+ radiusDefaults,+ typographyDefaults,+ textSizeDefaults,+ fontWeightDefaults,+ sizeDefaults,+ shadowDefaults,+ durationDefaults,+ easeDefaults,+} from '@xds/core/theme';+import {ColorSwatch} from './ColorSwatch';+import {TokenRow} from './TokenRow';+import {COLOR_CATEGORIES, TYPOGRAPHY_CATEGORIES} from './constants';++const TOKEN_GROUPS = {+ colors: {label: 'Colors', tokens: colorDefaults},+ spacing: {label: 'Spacing', tokens: spacingDefaults},+ radius: {label: 'Radius', tokens: radiusDefaults},+ typography: {+ label: 'Typography',+ tokens: {...typographyDefaults, ...textSizeDefaults, ...fontWeightDefaults},+ },+ size: {label: 'Size', tokens: sizeDefaults},+ shadow: {label: 'Elevation', tokens: shadowDefaults},+ duration: {label: 'Duration', tokens: durationDefaults},+ easing: {label: 'Easing', tokens: easeDefaults},+} as const;++type TokenGroupKey = keyof typeof TOKEN_GROUPS;++const TOKEN_ICONS: Record<TokenGroupKey, React.ReactNode> = {+ colors: <PaletteOutline16Icon />,+ spacing: <FourRectangleGridOutline16Icon />,+ radius: <FrameDashedOutline16Icon />,+ typography: <BigALittleAOutline16Icon />,+ size: <AspectRatioOutline16Icon />,+ shadow: <SquareOutline16Icon />,+ duration: <StopwatchOutline16Icon />,+ easing: <BoltOutline16Icon />,+};++function SpacingEditor({+ tokenName,+ value,+ onChange,+}: {+ tokenName: string;+ value: string;+ onChange: (name: string, value: string) => void;+}) {+ const numValue = parseInt(value, 10);+ return (+ <TokenRow+ tokenName={tokenName}+ preview={+ <div+ style={{+ width: Math.min(numValue, 48),+ height: 24,+ backgroundColor: 'var(--color-accent)',+ borderRadius: 4,+ flexShrink: 0,+ }}+ />+ }+ input={+ <div style={{width: 80}}>+ <XDSTextInput+ label="Value"+ isLabelHidden+ value={value}+ onChange={val => onChange(tokenName, val)}+ size="sm"+ />+ </div>+ }+ />+ );+}++function RadiusEditor({+ tokenName,+ value,+ onChange,+}: {+ tokenName: string;+ value: string;+ onChange: (name: string, value: string) => void;+}) {+ return (+ <TokenRow+ tokenName={tokenName}+ preview={+ <div+ style={{+ width: 32,+ height: 32,+ backgroundColor: 'var(--color-accent)',+ borderRadius: value,+ flexShrink: 0,+ }}+ />+ }+ input={+ <div style={{width: 80}}>+ <XDSTextInput+ label="Value"+ isLabelHidden+ value={value}+ onChange={val => onChange(tokenName, val)}+ size="sm"+ />+ </div>+ }+ />+ );+}++function TypographyEditor({+ tokenName,+ value,+ onChange,+}: {+ tokenName: string;+ value: string;+ onChange: (name: string, value: string) => void;+}) {+ const isFont = tokenName.includes('font-') && !tokenName.includes('weight');+ const isSize = tokenName.includes('text-') && tokenName.includes('size');+ const isWeight = tokenName.includes('weight');++ return (+ <TokenRow+ tokenName={tokenName}+ preview={+ <div+ style={{+ width: 48,+ height: 32,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ fontSize: isSize ? value : '14px',+ fontWeight: isWeight ? value : 400,+ fontFamily: isFont ? value : 'inherit',+ color: 'var(--color-text-primary)',+ flexShrink: 0,+ }}>+ Aa+ </div>+ }+ input={+ <div style={{width: 200}}>+ <XDSTextInput+ label="Value"+ isLabelHidden+ value={value}+ onChange={val => onChange(tokenName, val)}+ size="sm"+ />+ </div>+ }+ />+ );+}++function GenericEditor({+ tokenName,+ value,+ onChange,+}: {+ tokenName: string;+ value: string;+ onChange: (name: string, value: string) => void;+}) {+ return (+ <TokenRow+ tokenName={tokenName}+ input={+ <div style={{width: 200}}>+ <XDSTextInput+ label="Value"+ isLabelHidden+ value={value}+ onChange={val => onChange(tokenName, val)}+ size="sm"+ />+ </div>+ }+ />+ );+}++interface RawTokensPanelProps {+ tokens: Record<string, string>;+ mode: 'light' | 'dark';+ onTokenChange: (name: string, value: string) => void;+}++export function RawTokensPanel({+ tokens,+ mode,+ onTokenChange,+}: RawTokensPanelProps) {+ const [activeGroup, setActiveGroup] = React.useState<TokenGroupKey>('colors');++ return (+ <XDSVStack gap={3}>+ <div style={{overflowX: 'auto'}}>+ <XDSToggleButtonGroup+ label="Token category"+ type="single"+ size="sm"+ value={activeGroup}+ onChange={(v: string | null) => {+ if (v != null) {+ setActiveGroup(v as TokenGroupKey);+ }+ }}>+ {(Object.keys(TOKEN_GROUPS) as TokenGroupKey[]).map(groupKey => (+ <XDSToggleButton+ key={groupKey}+ label={TOKEN_GROUPS[groupKey].label}+ value={groupKey}+ icon={TOKEN_ICONS[groupKey]}+ isIconOnly={activeGroup !== groupKey}+ />+ ))}+ </XDSToggleButtonGroup>+ </div>++ <XDSVStack gap={1}>+ {activeGroup === 'colors' &&+ Object.entries(COLOR_CATEGORIES).map(([category, tokenNames]) => {+ const seen = new Set<string>();+ return (+ <XDSVStack key={category} gap={0}>+ <XDSText+ type="label"+ color="primary"+ weight="semibold"+ style={{+ padding: '8px 0 4px',+ display: 'block',+ }}>+ {category}+ </XDSText>+ {tokenNames+ .filter(t => {+ if (seen.has(t)) {+ return false;+ }+ seen.add(t);+ return true;+ })+ .map(tokenName => (+ <ColorSwatch+ key={tokenName}+ tokenName={tokenName}+ value={tokens[tokenName] || ''}+ onChange={onTokenChange}+ mode={mode}+ />+ ))}+ </XDSVStack>+ );+ })}++ {(activeGroup === 'spacing' || activeGroup === 'size') &&+ Object.keys(TOKEN_GROUPS[activeGroup].tokens).map(tokenName => (+ <SpacingEditor+ key={tokenName}+ tokenName={tokenName}+ value={tokens[tokenName] || ''}+ onChange={onTokenChange}+ />+ ))}++ {activeGroup === 'radius' &&+ Object.keys(TOKEN_GROUPS.radius.tokens).map(tokenName => (+ <RadiusEditor+ key={tokenName}+ tokenName={tokenName}+ value={tokens[tokenName] || ''}+ onChange={onTokenChange}+ />+ ))}++ {activeGroup === 'typography' &&+ Object.entries(TYPOGRAPHY_CATEGORIES).map(([category, config]) => {+ const tokenNames = Array.isArray(config) ? config : config.tokens;+ return (+ <XDSVStack key={category} gap={2}>+ <XDSText+ type="label"+ color="primary"+ weight="semibold"+ style={{padding: '8px 0 4px', display: 'block'}}>+ {category}+ </XDSText>+ {tokenNames.map(tokenName => (+ <TypographyEditor+ key={tokenName}+ tokenName={tokenName}+ value={tokens[tokenName] || ''}+ onChange={onTokenChange}+ />+ ))}+ </XDSVStack>+ );+ })}++ {(activeGroup === 'shadow' ||+ activeGroup === 'duration' ||+ activeGroup === 'easing') &&+ Object.keys(TOKEN_GROUPS[activeGroup].tokens).map(tokenName => (+ <GenericEditor+ key={tokenName}+ tokenName={tokenName}+ value={tokens[tokenName] || ''}+ onChange={onTokenChange}+ />+ ))}+ </XDSVStack>+ </XDSVStack>+ );+}diff --git a/apps/docsite/src/components/themePlayground/ThemeEditorView.tsx b/apps/docsite/src/components/themePlayground/ThemeEditorView.tsxnew file mode 100644index 0000000000..565954de6d--- /dev/null+++ b/apps/docsite/src/components/themePlayground/ThemeEditorView.tsx@@ -0,0 +1,698 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++import * as React from 'react';+import {useRouter} from 'next/navigation';+import {XDSButton} from '@xds/core/Button';+import {XDSCard} from '@xds/core/Card';+import {XDSHStack, XDSVStack} from '@xds/core/Stack';+import {XDSText} from '@xds/core/Text';+import {XDSCodeBlock} from '@xds/core/CodeBlock';+import {XDSDropdownMenu} from '@xds/core/DropdownMenu';+import {+ ArrowLeftFilled16Icon as ArrowLeftIcon,+ LargeHalfCircle8RaysLargeOutline16Icon,+ CrescentOutline16Icon,+} from './icons';+import {XDSTabList, XDSTab} from '@xds/core/TabList';+import {XDSDialog, XDSDialogHeader} from '@xds/core/Dialog';+import {useXDSResizable} from '@xds/core/Resizable';+import {XDSResizeHandle} from '@xds/core/Resizable';+import {+ XDSTheme,+ defineTheme,+ expandTypeScale,+ expandRadiusScale,+ expandColorScale,+ colorDefaults,+ spacingDefaults,+ radiusDefaults,+ typographyDefaults,+ textSizeDefaults,+ fontWeightDefaults,+ typeScaleDefaults,+ sizeDefaults,+ shadowDefaults,+ durationDefaults,+ easeDefaults,+} from '@xds/core/theme';+import type {XDSDefinedTheme} from '@xds/core/theme';+import {EditorSections} from './EditorSections';+import {ComponentTokensPanel} from './ComponentTokensPanel';+import type {CustomOverride} from './ComponentTokensPanel';+import {RawTokensPanel} from './RawTokensPanel';+import {ThemeShowcasePreview} from '../ThemeShowcasePreview';+import {ThemeCardShowcase} from '../ThemeCardShowcase';+import {getThemeImages} from '../themeImages';+import {TokenScalePreview} from './TokenScalePreview';+import {+ UNIFIED_PRESETS,+ GOOGLE_FONTS_URL,+ COMPONENT_VAR_NAMES,+} from './constants';+import {+ generateThemeCode,+ buildComponentOverrides,+ mergeComponentStyleMaps,+} from './helpers';+import {getThemeList} from './themeList';+import type {ThemeListEntry} from './themeList';++const ALL_DEFAULTS: Record<string, string> = {+ ...colorDefaults,+ ...spacingDefaults,+ ...radiusDefaults,+ ...typographyDefaults,+ ...textSizeDefaults,+ ...fontWeightDefaults,+ ...typeScaleDefaults,+ ...sizeDefaults,+ ...shadowDefaults,+ ...durationDefaults,+ ...easeDefaults,+};++interface ThemeEditorViewProps {+ themeId: string;+ themeLabel: string;+ initialTheme: XDSDefinedTheme;+}++export function ThemeEditorView({+ themeId,+ themeLabel,+ initialTheme,+}: ThemeEditorViewProps) {+ const router = useRouter();+ const themeList = React.useMemo(() => getThemeList(), []);+ const [tokens, setTokens] = React.useState<Record<string, string>>(() => ({+ ...ALL_DEFAULTS,+ ...initialTheme.tokens,+ }));+ // Component-level overrides from the seeded preset (e.g. button/badge/banner+ // variant styling). Kept separate from token state so they form the base+ // layer the editor's token + custom overrides compose on top of.+ const [baseComponents, setBaseComponents] = React.useState<+ Record<string, unknown>+ >(() => initialTheme.components ?? {});+ const [mode, setMode] = React.useState<'light' | 'dark'>('light');+ const [panelTab, setPanelTab] = React.useState<+ 'theme' | 'components' | 'tokens'+ >('theme');+ const [showExportDialog, setShowExportDialog] = React.useState(false);+ const [activePreview, setActivePreview] = React.useState<+ 'preview' | 'tokens'+ >('preview');+ const [typeScaleBase, setTypeScaleBase] = React.useState(14);+ const [typeScaleRatio, setTypeScaleRatio] = React.useState(1.2);+ const [radiusBase, setRadiusBase] = React.useState(4);+ const [spacingBase, setSpacingBase] = React.useState(4);+ const [sizeBase, setSizeBase] = React.useState(32);+ const [durationStep, setDurationStep] = React.useState(1);+ // A unified preset (Compact/Default/Comfortable/Gigantic) is only "active"+ // when the user explicitly applies one. A theme selection does not map to a+ // preset, so this stays null until applyUnifiedPreset runs.+ const [activePreset, setActivePreset] = React.useState<string | null>(null);+ const [autoPickColors, setAutoPickColors] = React.useState(false);+ const [customOverrides, setCustomOverrides] = React.useState<+ CustomOverride[]+ >([]);+ // The preset the editor is currently based on. Switching themes reseeds the+ // token state from this preset; edits that deviate flip the selector to+ // "Custom" (see isCustom below).+ const [selectedThemeId, setSelectedThemeId] = React.useState(themeId);+ const editor = useXDSResizable({+ defaultSize: 400,+ minSizePx: 320,+ maxSizePx: 600,+ autoSaveId: 'theme-editor-panel',+ });++ const currentTheme = React.useMemo(() => {+ const coreTokens: Record<string, string> = {};+ const componentTokens: Record<string, string> = {};+ for (const [key, value] of Object.entries(tokens)) {+ if (COMPONENT_VAR_NAMES.has(key)) {+ componentTokens[key] = value;+ } else {+ coreTokens[key] = value;+ }+ }+ const customMap: Record<string, {base: Record<string, string>}> = {};+ for (const override of customOverrides) {+ customMap[override.component] ??= {base: {}};+ customMap[override.component].base[override.property] = override.value;+ }+ // Layer order: preset component overrides (base) → token-derived overrides+ // → freeform custom overrides. Later layers win at the leaf level.+ const components = mergeComponentStyleMaps(+ baseComponents,+ buildComponentOverrides(componentTokens),+ customMap,+ ) as XDSDefinedTheme['components'];+ return defineTheme({name: 'custom', tokens: coreTokens, components});+ }, [tokens, customOverrides, baseComponents]);++ // Product imagery for the live preview. Tracks the selected base theme+ // (falls back to neutral) so the showcase photos match the theme the+ // user started from, even after they tweak tokens into "Custom".+ const previewImages = React.useMemo(+ () => getThemeImages(selectedThemeId),+ [selectedThemeId],+ );++ const handleTokenChange = React.useCallback((name: string, value: string) => {+ setTokens(prev => ({...prev, [name]: value}));+ }, []);++ // Baseline token set for the currently-selected preset.+ const selectedThemeBaseline = React.useMemo(() => {+ const entry = themeList.find(t => t.name === selectedThemeId);+ return {...ALL_DEFAULTS, ...(entry?.theme.tokens ?? {})};+ }, [themeList, selectedThemeId]);++ const selectedThemeLabel = React.useMemo(() => {+ const entry = themeList.find(t => t.name === selectedThemeId);+ return entry?.label ?? themeLabel;+ }, [themeList, selectedThemeId, themeLabel]);++ // The editor is "custom" once any token deviates from the selected preset's+ // baseline, or once a component-level override is added.+ const isCustom = React.useMemo(() => {+ if (customOverrides.length > 0) {+ return true;+ }+ for (const key of Object.keys(selectedThemeBaseline)) {+ if (tokens[key] !== selectedThemeBaseline[key]) {+ return true;+ }+ }+ return false;+ }, [tokens, selectedThemeBaseline, customOverrides]);++ // Reseed the entire editor from a theme preset (in place — no navigation).+ const selectTheme = React.useCallback((entry: ThemeListEntry) => {+ setTokens({...ALL_DEFAULTS, ...entry.theme.tokens});+ setBaseComponents(entry.theme.components ?? {});+ setSelectedThemeId(entry.name);+ setTypeScaleBase(14);+ setTypeScaleRatio(1.2);+ setRadiusBase(4);+ setSpacingBase(4);+ setSizeBase(32);+ setDurationStep(1);+ setActivePreset(null);+ setAutoPickColors(false);+ setCustomOverrides([]);+ }, []);++ const handleReset = React.useCallback(() => {+ setTokens({...ALL_DEFAULTS, ...selectedThemeBaseline});+ const entry = themeList.find(t => t.name === selectedThemeId);+ setBaseComponents(entry?.theme.components ?? {});+ setTypeScaleBase(14);+ setTypeScaleRatio(1.2);+ setRadiusBase(4);+ setSpacingBase(4);+ setSizeBase(32);+ setDurationStep(1);+ setActivePreset(null);+ setAutoPickColors(false);+ setCustomOverrides([]);+ }, [selectedThemeBaseline, themeList, selectedThemeId]);++ const applyTypeScale = React.useCallback((base: number, ratio: number) => {+ setActivePreset(null);+ setTypeScaleBase(base);+ setTypeScaleRatio(ratio);+ setTokens(prev => ({...prev, ...expandTypeScale({base, ratio})}));+ }, []);++ const applySpacingScale = React.useCallback((base: number) => {+ setActivePreset(null);+ setSpacingBase(base);+ const steps = [0, 0.5, 1, 1.5, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];+ const keys = [+ '0',+ '0-5',+ '1',+ '1-5',+ '2',+ '3',+ '4',+ '5',+ '6',+ '7',+ '8',+ '9',+ '10',+ '11',+ '12',+ ];+ const patch: Record<string, string> = {};+ steps.forEach((step, i) => {+ patch[`--spacing-${keys[i]}`] = `${Math.round(base * step)}px`;+ });+ setTokens(prev => ({...prev, ...patch}));+ }, []);++ const applySizeScale = React.useCallback((base: number) => {+ setActivePreset(null);+ setSizeBase(base);+ setTokens(prev => ({+ ...prev,+ '--size-element-sm': `${base - 4}px`,+ '--size-element-md': `${base}px`,+ '--size-element-lg': `${base + 4}px`,+ }));+ }, []);++ const applyRadiusScale = React.useCallback((base: number) => {+ setActivePreset(null);+ setRadiusBase(base);+ setTokens(prev => ({+ ...prev,+ ...expandRadiusScale({base, multiplier: 1}),+ }));+ }, []);++ const applyDurationScale = React.useCallback((multiplier: number) => {+ setDurationStep(multiplier);+ const defaults: Record<string, number> = {+ '--duration-fast-min': 130,+ '--duration-fast': 175,+ '--duration-fast-max': 230,+ '--duration-medium-min': 310,+ '--duration-medium': 410,+ '--duration-medium-max': 550,+ '--duration-slow-min': 730,+ '--duration-slow': 975,+ '--duration-slow-max': 1300,+ };+ const patch: Record<string, string> = {};+ for (const [key, base] of Object.entries(defaults)) {+ patch[key] = `${Math.round(base / multiplier)}ms`;+ }+ setTokens(prev => ({...prev, ...patch}));+ }, []);++ const applyUnifiedPreset = React.useCallback((presetKey: string) => {+ const p = UNIFIED_PRESETS[presetKey as keyof typeof UNIFIED_PRESETS];+ if (!p) {return;}+ setActivePreset(presetKey);+ setTypeScaleBase(p.typeBase);+ setTypeScaleRatio(p.typeRatio);+ setSpacingBase(p.spacing);+ setRadiusBase(p.radius);+ setSizeBase(p.sizeMd);+ setTokens(prev => {+ const spacingSteps = [0, 0.5, 1, 1.5, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];+ const spacingKeys = [+ '0',+ '0-5',+ '1',+ '1-5',+ '2',+ '3',+ '4',+ '5',+ '6',+ '7',+ '8',+ '9',+ '10',+ '11',+ '12',+ ];+ const spacingPatch: Record<string, string> = {};+ spacingSteps.forEach((step, i) => {+ spacingPatch[`--spacing-${spacingKeys[i]}`] =+ `${Math.round(p.spacing * step)}px`;+ });+ return {+ ...prev,+ ...expandTypeScale({base: p.typeBase, ratio: p.typeRatio}),+ ...spacingPatch,+ ...expandRadiusScale({base: p.radius, multiplier: 1}),+ '--size-element-sm': `${p.sizeMd - p.spacing}px`,+ '--size-element-md': `${p.sizeMd}px`,+ '--size-element-lg': `${p.sizeMd + p.spacing}px`,+ };+ });+ }, []);++ const handleExpandColorScale = React.useCallback((accentHex: string) => {+ const derived = expandColorScale({accent: accentHex});+ let hex = accentHex.replace('#', '');+ // Normalize 3-char short hex (e.g. "f00") to 6-char ("ff0000")+ if (hex.length === 3) {+ hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];+ }+ // Guard against invalid hex — fall back to black+ if (hex.length !== 6 || !/^[0-9a-fA-F]{6}$/.test(hex)) {+ hex = '000000';+ }+ const r = parseInt(hex.slice(0, 2), 16);+ const g = parseInt(hex.slice(2, 4), 16);+ const b = parseInt(hex.slice(4, 6), 16);+ derived['--shadow-inset-hover'] =+ `inset 0px 0px 0px 2px rgba(${r}, ${g}, ${b}, 0.3)`;+ derived['--shadow-inset-selected'] =+ `inset 0px 0px 0px 2px rgba(${r}, ${g}, ${b}, 0.5)`;+ setTokens(prev => ({...prev, ...derived}));+ }, []);++ const themeCode = React.useMemo(+ () =>+ generateThemeCode(+ themeId,+ tokens,+ ALL_DEFAULTS,+ typeScaleBase,+ typeScaleRatio,+ customOverrides,+ baseComponents,+ ),+ [+ themeId,+ tokens,+ typeScaleBase,+ typeScaleRatio,+ customOverrides,+ baseComponents,+ ],+ );++ // Runnable usage snippet shown alongside the exported theme. Mirrors the+ // theme package README's "wrap your app with XDSTheme" guidance, adapted+ // for a locally-authored theme file.+ const usageSnippet = React.useMemo(+ () =>+ [+ "import {XDSTheme} from '@xds/core/theme';",+ `import {${themeId}Theme} from './${themeId}-theme';`,+ '',+ 'export function App() {',+ ` return <XDSTheme theme={${themeId}Theme}>{/* your app */}</XDSTheme>;`,+ '}',+ ].join('\n'),+ [themeId],+ );++ return (+ <div+ style={{+ display: 'flex',+ height: '100vh',+ overflow: 'hidden',+ backgroundColor: 'var(--color-background-surface)',+ }}>+ <style>{`@import url("${GOOGLE_FONTS_URL}");`}</style>++ {/* Left Panel — Editor */}+ <div+ style={{+ width: editor.size || 400,+ minWidth: 348,+ maxWidth: 600,+ flexShrink: 0,+ display: 'flex',+ flexDirection: 'column' as const,+ overflow: 'hidden',+ }}>+ {/* Panel Header: back button + tabs */}+ <div style={{flexShrink: 0}}>+ <XDSHStack gap={2} vAlign="center" style={{padding: '8px 12px 0'}}>+ <XDSButton+ label="Back"+ variant="ghost"+ size="md"+ isIconOnly+ icon={<ArrowLeftIcon />}+ onClick={() => router.push('/themes')}+ />+ <XDSTabList+ value={panelTab}+ onChange={v =>+ setPanelTab(v as 'theme' | 'components' | 'tokens')+ }+ style={{flex: 1}}>+ <XDSTab value="theme" label="Theme" style={{flex: 1}} />+ <XDSTab value="components" label="Components" style={{flex: 1}} />+ <XDSTab value="tokens" label="Tokens" style={{flex: 1}} />+ </XDSTabList>+ </XDSHStack>+ </div>++ {/* Scrollable editor content */}+ <div style={{flex: 1, overflow: 'auto', padding: 16}}>+ {panelTab === 'theme' && (+ <EditorSections+ tokens={tokens}+ mode={mode}+ typeScaleBase={typeScaleBase}+ typeScaleRatio={typeScaleRatio}+ radiusBase={radiusBase}+ spacingBase={spacingBase}+ sizeBase={sizeBase}+ durationStep={durationStep}+ activePreset={activePreset}+ autoPickColors={autoPickColors}+ onTokenChange={handleTokenChange}+ onApplyTypeScale={applyTypeScale}+ onApplyRadiusScale={applyRadiusScale}+ onApplySpacingScale={applySpacingScale}+ onApplySizeScale={applySizeScale}+ onApplyDurationScale={applyDurationScale}+ onApplyUnifiedPreset={applyUnifiedPreset}+ onSetAutoPickColors={setAutoPickColors}+ onExpandColorScale={handleExpandColorScale}+ onSetTokens={setTokens}+ />+ )}+ {panelTab === 'components' && (+ <ComponentTokensPanel+ tokens={tokens}+ onTokenChange={handleTokenChange}+ customOverrides={customOverrides}+ onCustomOverridesChange={setCustomOverrides}+ baseComponents={baseComponents}+ />+ )}+ {panelTab === 'tokens' && (+ <RawTokensPanel+ tokens={tokens}+ mode={mode}+ onTokenChange={handleTokenChange}+ />+ )}+ </div>+ </div>++ {/* Resize Handle */}+ <XDSResizeHandle resizable={editor.props} pillPlacement="center" />++ {/* Right Panel — Preview */}+ <div+ style={{+ flex: 1,+ display: 'flex',+ flexDirection: 'column' as const,+ minWidth: 0,+ overflow: 'hidden',+ }}>+ {/* Preview toolbar */}+ <div+ style={{+ padding: '8px 16px',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ flexShrink: 0,+ }}>+ {/* Left: theme selector + dark mode toggle */}+ <XDSHStack+ gap={2}+ vAlign="center"+ style={{flex: 1, justifyContent: 'flex-start'}}>+ <XDSDropdownMenu+ hasAutoFocus={false}+ button={{+ label: isCustom ? 'Custom' : selectedThemeLabel,+ variant: 'ghost',+ size: 'md',+ }}+ items={themeList.map(entry => ({+ label: entry.label,+ onClick: () => selectTheme(entry),+ }))}+ />+ <XDSButton+ label={+ mode === 'light'+ ? 'Switch to dark mode'+ : 'Switch to light mode'+ }+ tooltip={mode === 'light' ? 'Dark mode' : 'Light mode'}+ variant="ghost"+ size="md"+ icon={+ mode === 'light' ? (+ <LargeHalfCircle8RaysLargeOutline16Icon />+ ) : (+ <CrescentOutline16Icon />+ )+ }+ isIconOnly+ onClick={() => setMode(m => (m === 'light' ? 'dark' : 'light'))}+ />+ </XDSHStack>+ {/* Center: component / token preview selector */}+ <XDSHStack gap={2} vAlign="center" style={{justifyContent: 'center'}}>+ <XDSDropdownMenu+ hasAutoFocus={false}+ button={{+ label:+ activePreview === 'tokens' ? 'Token Preview' : 'App Preview',+ variant: 'ghost',+ size: 'md',+ }}+ items={[+ {+ label: 'Token Preview',+ onClick: () => setActivePreview('tokens'),+ },+ {+ label: 'App Preview',+ onClick: () => setActivePreview('preview'),+ },+ ]}+ />+ </XDSHStack>+ {/* Right: reset + export */}+ <XDSHStack+ gap={2}+ vAlign="center"+ style={{flex: 1, justifyContent: 'flex-end'}}>+ <XDSButton+ label="Reset"+ variant="ghost"+ size="md"+ onClick={handleReset}+ />+ <XDSButton+ label="Export Theme"+ variant="secondary"+ size="md"+ onClick={() => setShowExportDialog(true)}+ />+ </XDSHStack>+ </div>++ {/* Preview content wrapped in theme */}+ <div+ style={{+ flex: 1,+ minHeight: 0,+ display: 'flex',+ flexDirection: 'column' as const,+ backgroundColor: 'var(--color-background-surface)',+ paddingBlockStart: 0,+ paddingBlockEnd: 'var(--spacing-4)',+ paddingInline: 'var(--spacing-4)',+ }}>+ <XDSCard+ padding={0}+ style={{+ flex: 1,+ minHeight: 0,+ overflow: 'auto',+ scrollbarWidth: 'thin',+ colorScheme: mode,+ }}>+ <XDSTheme theme={currentTheme} mode={mode}>+ {activePreview === 'tokens' ? (+ <div+ style={{+ padding: 24,+ minHeight: '100%',+ backgroundColor: 'var(--color-background-body)',+ }}>+ <TokenScalePreview tokens={tokens} />+ </div>+ ) : (+ <div+ style={{+ minHeight: '100%',+ backgroundColor: 'var(--color-background-body)',+ }}>+ {/* Landing surface — top nav + hero + product grid,+ rendered flush so the nav reads as real product+ chrome (same component used on /themes/<name>). */}+ <ThemeShowcasePreview images={previewImages} fluid />+ {/* Real-world card showcase — Checkout + Chat ++ Inventory + Revenue. Sits on the lifted surface+ tone below the landing, mirroring the theme+ detail page composition. */}+ <div+ style={{+ padding: 'var(--spacing-6)',+ backgroundColor: 'var(--color-background-surface)',+ }}>+ <ThemeCardShowcase+ theme={currentTheme}+ images={previewImages}+ mode={mode}+ />+ </div>+ </div>+ )}+ </XDSTheme>+ </XDSCard>+ </div>+ </div>++ {/* Export Theme Dialog */}+ <XDSDialog+ isOpen={showExportDialog}+ onOpenChange={setShowExportDialog}+ width={720}>+ <XDSDialogHeader title="Exporting a theme" />+ <div+ style={{+ padding: 'var(--spacing-4)',+ overflow: 'auto',+ maxHeight: '70vh',+ }}>+ <XDSVStack gap={5}>+ <XDSText type="body" color="secondary">+ Your theme is a plain object — no build step or package install+ required. Save the code below to a file, then wrap your app with{' '}+ <code>XDSTheme</code> to apply it.+ </XDSText>++ <XDSVStack gap={2}>+ <XDSText type="label">+ 1. Save as a theme file (e.g. {themeId}-theme.ts)+ </XDSText>+ <XDSCodeBlock code={themeCode} language="typescript" size="sm" />+ </XDSVStack>++ <XDSVStack gap={2}>+ <XDSText type="label">2. Wrap your app with the theme</XDSText>+ <XDSCodeBlock code={usageSnippet} language="tsx" size="sm" />+ <XDSText type="supporting" color="secondary">+ Token and component overrides apply at runtime through{' '}+ <code>XDSTheme</code>. To consume the theme as a stylesheet+ instead, build a CSS file with{' '}+ <code>xds theme build {themeId}-theme.ts -o theme.css</code> and{' '}+ <code>@import</code> it.+ </XDSText>+ </XDSVStack>+ </XDSVStack>+ </div>+ </XDSDialog>+ </div>+ );+}diff --git a/apps/docsite/src/components/themePlayground/TokenRow.tsx b/apps/docsite/src/components/themePlayground/TokenRow.tsxnew file mode 100644index 0000000000..986749089a--- /dev/null+++ b/apps/docsite/src/components/themePlayground/TokenRow.tsx@@ -0,0 +1,50 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++import type {ReactNode} from 'react';+import {XDSText} from '@xds/core/Text';+import {getTokenLabel} from './helpers';++/**+ * Standard token-editor row. Left: readable token name (body/primary). Right:+ * optional visual preview followed by the input. No row background — the only+ * fills are the preview swatches themselves.+ */+export function TokenRow({+ tokenName,+ preview,+ input,+}: {+ tokenName: string;+ preview?: ReactNode;+ input: ReactNode;+}) {+ return (+ <div+ style={{+ padding: '8px 0',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ gap: 12,+ }}>+ <div style={{flex: 1, minWidth: 0}}>+ <XDSText type="body" color="primary" maxLines={1}>+ {getTokenLabel(tokenName)}+ </XDSText>+ </div>+ <div+ style={{+ display: 'flex',+ alignItems: 'center',+ gap: 8,+ flexShrink: 0,+ justifyContent: 'flex-end',+ }}>+ {preview}+ {input}+ </div>+ </div>+ );+}diff --git a/apps/docsite/src/components/themePlayground/TokenScalePreview.tsx b/apps/docsite/src/components/themePlayground/TokenScalePreview.tsxnew file mode 100644index 0000000000..81cfbb50db--- /dev/null+++ b/apps/docsite/src/components/themePlayground/TokenScalePreview.tsx@@ -0,0 +1,251 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++import {XDSText, XDSHeading} from '@xds/core/Text';+import {parseLightDark} from './helpers';++const SECTION_STYLE: React.CSSProperties = {+ display: 'flex',+ flexDirection: 'column',+ gap: 12,+};++const SECTION_TITLE: React.CSSProperties = {+ fontSize: 11,+ fontWeight: 600,+ textTransform: 'uppercase',+ letterSpacing: '0.05em',+ color: 'var(--color-text-disabled)',+};++const SCALE_ROW: React.CSSProperties = {+ display: 'grid',+ gridTemplateColumns: '1fr 200px 200px',+ alignItems: 'center',+ gap: 8,+};++const CODE_LABEL: React.CSSProperties = {+ fontSize: 12,+ fontFamily: 'monospace',+ color: 'var(--color-text-secondary)',+ whiteSpace: 'nowrap',+ overflow: 'hidden',+ textOverflow: 'ellipsis',+};++export function TokenScalePreview({tokens}: {tokens: Record<string, string>}) {+ const resolveSize = (raw: string) => {+ if (!raw) {return raw;}+ return raw.startsWith('var(') ? tokens[raw.slice(4, -1)] || raw : raw;+ };+ const toPx = (raw: string) => {+ const resolved = resolveSize(raw);+ if (resolved?.endsWith('rem'))+ {return `${Math.round(parseFloat(resolved) * 16)}px`;}+ return resolved;+ };++ const colorsSection = (+ <div style={SECTION_STYLE}>+ <span style={SECTION_TITLE}>Colors</span>+ <div style={{display: 'flex', flexDirection: 'column', gap: 4}}>+ {[+ {token: '--color-accent', label: 'accent'},+ {token: '--color-accent-muted', label: 'accent-muted'},+ {token: '--color-neutral', label: 'neutral'},+ {token: '--color-background-card', label: 'card'},+ {token: '--color-background-surface', label: 'surface'},+ {token: '--color-text-primary', label: 'text'},+ {token: '--color-text-secondary', label: 'text-secondary'},+ {token: '--color-border', label: 'border'},+ ].map(({token, label}) => {+ const raw = tokens[token] || '';+ const parsed = parseLightDark(raw);+ const displayVal = parsed ? parsed.light : raw;+ return (+ <div key={token} style={SCALE_ROW}>+ <div+ style={{+ width: 48,+ height: 48,+ borderRadius: 8,+ backgroundColor: `var(${token})`,+ border: '1px solid var(--color-border)',+ flexShrink: 0,+ }}+ />+ <span style={CODE_LABEL}>{label}</span>+ <span style={CODE_LABEL}>{displayVal}</span>+ </div>+ );+ })}+ </div>+ </div>+ );++ const typographySection = (+ <div style={SECTION_STYLE}>+ <span style={SECTION_TITLE}>Typography</span>+ <div style={{display: 'flex', flexDirection: 'column', gap: 8}}>+ {(['display-1', 'display-2', 'display-3'] as const).map(type => (+ <div key={type} style={SCALE_ROW}>+ <div style={{overflow: 'hidden'}}>+ <XDSText type={type} maxLines={1}>+ Display+ </XDSText>+ </div>+ <span style={CODE_LABEL}>{type}</span>+ <span style={CODE_LABEL}>+ {toPx(tokens[`--text-${type}-size`] || '')}+ </span>+ </div>+ ))}+ {([1, 2, 3, 4] as const).map(level => (+ <div key={level} style={SCALE_ROW}>+ <div style={{overflow: 'hidden'}}>+ <XDSHeading level={level} maxLines={1}>+ Heading {level}+ </XDSHeading>+ </div>+ <span style={CODE_LABEL}>h{level}</span>+ <span style={CODE_LABEL}>+ {toPx(tokens[`--text-heading-${level}-size`] || '')}+ </span>+ </div>+ ))}+ {(['large', 'body', 'label', 'supporting', 'code'] as const).map(+ type => (+ <div key={type} style={SCALE_ROW}>+ <div style={{overflow: 'hidden'}}>+ <XDSText type={type} maxLines={1}>+ {type === 'code'+ ? 'const theme = defineTheme()'+ : 'The quick brown fox'}+ </XDSText>+ </div>+ <span style={CODE_LABEL}>{type}</span>+ <span style={CODE_LABEL}>+ {toPx(tokens[`--text-${type}-size`] || '')}+ </span>+ </div>+ ),+ )}+ </div>+ </div>+ );++ const spacingSection = (+ <div style={SECTION_STYLE}>+ <span style={SECTION_TITLE}>Spacing</span>+ <div style={{display: 'flex', flexDirection: 'column', gap: 4}}>+ {[0.5, 1, 2, 3, 4, 6, 8, 12].map(step => {+ const key = String(step).replace('.', '-');+ const val = tokens[`--spacing-${key}`] || '0px';+ return (+ <div key={step} style={SCALE_ROW}>+ <div style={{display: 'flex', alignItems: 'center'}}>+ <div+ style={{+ width: val,+ height: val,+ backgroundColor: 'var(--color-accent-muted)',+ border: '1px dashed var(--color-accent)',+ transition: 'width 200ms ease, height 200ms ease',+ }}+ />+ </div>+ <span style={CODE_LABEL}>{step}</span>+ <span style={CODE_LABEL}>{val}</span>+ </div>+ );+ })}+ </div>+ </div>+ );++ const radiusSection = (+ <div style={SECTION_STYLE}>+ <span style={SECTION_TITLE}>Corner Radius</span>+ <div style={{display: 'flex', flexDirection: 'column', gap: 8}}>+ {(['none', 'inner', 'element', 'container', 'page'] as const).map(+ name => {+ const val = tokens[`--radius-${name}`] || '0px';+ return (+ <div key={name} style={SCALE_ROW}>+ <div+ style={{+ width: 48,+ height: 48,+ backgroundColor: 'var(--color-accent-muted)',+ border: '1px dashed var(--color-accent)',+ borderRadius: val,+ flexShrink: 0,+ transition: 'border-radius 200ms ease',+ }}+ />+ <span style={CODE_LABEL}>{name}</span>+ <span style={CODE_LABEL}>{val}</span>+ </div>+ );+ },+ )}+ </div>+ </div>+ );++ const sizeSection = (+ <div style={SECTION_STYLE}>+ <span style={SECTION_TITLE}>Element Size</span>+ <div style={{display: 'flex', flexDirection: 'column', gap: 8}}>+ {(['sm', 'md', 'lg'] as const).map(size => {+ const val = tokens[`--size-element-${size}`] || '32px';+ return (+ <div key={size} style={SCALE_ROW}>+ <div+ style={{+ width: `calc(${val} * 2.4)`,+ height: val,+ backgroundColor: 'var(--color-accent-muted)',+ border: '1px dashed var(--color-accent)',+ borderRadius: 8,+ flexShrink: 0,+ transition: 'width 200ms ease, height 200ms ease',+ }}+ />+ <span style={CODE_LABEL}>{size}</span>+ <span style={CODE_LABEL}>{val}</span>+ </div>+ );+ })}+ </div>+ </div>+ );++ return (+ <div style={{containerType: 'inline-size'}}>+ <style>+ {'@container (min-width: 720px) { .token-scale-grid { grid-template-columns: 1fr auto 1fr !important; } }' ++ '@container (max-width: 719px) { .token-scale-divider { display: none !important; } }'}+ </style>+ <div+ className="token-scale-grid"+ style={{display: 'grid', gridTemplateColumns: '1fr', gap: 32}}>+ <div style={{display: 'flex', flexDirection: 'column', gap: 32}}>+ {colorsSection}+ {spacingSection}+ {sizeSection}+ </div>+ <div+ className="token-scale-divider"+ style={{width: 1, backgroundColor: 'var(--color-border)'}}+ />+ <div style={{display: 'flex', flexDirection: 'column', gap: 32}}>+ {typographySection}+ {radiusSection}+ </div>+ </div>+ </div>+ );+}diff --git a/apps/docsite/src/components/themePlayground/constants.ts b/apps/docsite/src/components/themePlayground/constants.tsnew file mode 100644index 0000000000..f1659d1472--- /dev/null+++ b/apps/docsite/src/components/themePlayground/constants.ts@@ -0,0 +1,471 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++export const FONT_OPTIONS = [+ {+ value:+ '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif',+ label: 'System (Default)',+ },+ {value: '"Inter", -apple-system, sans-serif', label: 'Inter'},+ {value: '"Roboto", -apple-system, sans-serif', label: 'Roboto'},+ {value: '"DM Sans", -apple-system, sans-serif', label: 'DM Sans'},+ {value: '"Figtree", -apple-system, sans-serif', label: 'Figtree'},+ {value: '"Poppins", -apple-system, sans-serif', label: 'Poppins'},+ {+ value: '"IBM Plex Sans", -apple-system, sans-serif',+ label: 'IBM Plex Sans',+ },+ {+ value: '"Source Sans 3", -apple-system, sans-serif',+ label: 'Source Sans',+ },+ {value: '"Noto Sans", -apple-system, sans-serif', label: 'Noto Sans'},+ {value: 'Georgia, "Times New Roman", serif', label: 'Georgia (Serif)'},+];++export const RATIO_OPTIONS = [+ {value: 1.067, label: '1.067 — Minor Second'},+ {value: 1.125, label: '1.125 — Major Second'},+ {value: 1.2, label: '1.200 — Minor Third'},+ {value: 1.25, label: '1.250 — Major Third'},+ {value: 1.333, label: '1.333 — Perfect Fourth'},+ {value: 1.414, label: '1.414 — Augmented Fourth'},+ {value: 1.5, label: '1.500 — Perfect Fifth'},+ {value: 1.618, label: '1.618 — Golden Ratio'},+];++export const UNIFIED_PRESETS = {+ compact: {+ typeBase: 12,+ typeRatio: 1.125,+ spacing: 2,+ radius: 2,+ sizeMd: 28,+ },+ default: {+ typeBase: 14,+ typeRatio: 1.2,+ spacing: 4,+ radius: 4,+ sizeMd: 32,+ },+ comfortable: {+ typeBase: 16,+ typeRatio: 1.25,+ spacing: 6,+ radius: 6,+ sizeMd: 40,+ },+ gigantic: {+ typeBase: 18,+ typeRatio: 1.414,+ spacing: 8,+ radius: 12,+ sizeMd: 48,+ },+} as const;++export const RADIUS_OPTIONS = [+ {value: 'var(--radius-none)', token: '--radius-none', label: 'None'},+ {value: 'var(--radius-inner)', token: '--radius-inner', label: 'Inner'},+ {value: 'var(--radius-element)', token: '--radius-element', label: 'Element'},+ {+ value: 'var(--radius-container)',+ token: '--radius-container',+ label: 'Container',+ },+ {value: 'var(--radius-page)', token: '--radius-page', label: 'Page'},+ {value: 'var(--radius-full)', token: '--radius-full', label: 'Full'},+];++export const SPACING_OPTIONS = [+ {value: 'var(--spacing-0-5)', token: '--spacing-0-5', label: '0.5'},+ {value: 'var(--spacing-1)', token: '--spacing-1', label: '1'},+ {value: 'var(--spacing-2)', token: '--spacing-2', label: '2'},+ {value: 'var(--spacing-3)', token: '--spacing-3', label: '3'},+ {value: 'var(--spacing-4)', token: '--spacing-4', label: '4'},+ {value: 'var(--spacing-6)', token: '--spacing-6', label: '6'},+ {value: 'var(--spacing-8)', token: '--spacing-8', label: '8'},+];++export function resolveOptionLabel(+ option: {label: string; token?: string},+ tokens: Record<string, string>,+): string {+ if (!option.token) {return option.label;}+ const resolved = tokens[option.token];+ if (resolved) {return `${option.label} — ${resolved}`;}+ return option.label;+}++export interface ComponentVar {+ name: string;+ default: string;+ description: string;+ options: Array<{value: string; label: string}>;+}++export const COMPONENT_VARS: Record<+ string,+ {label: string; vars: ComponentVar[]}+> = {+ button: {+ label: 'Button',+ vars: [+ {+ name: '--button-radius',+ default: 'var(--radius-element)',+ description: 'Border radius',+ options: RADIUS_OPTIONS,+ },+ ],+ },+ card: {+ label: 'Card',+ vars: [+ {+ name: '--card-radius',+ default: 'var(--radius-container)',+ description: 'Border radius',+ options: RADIUS_OPTIONS,+ },+ {+ name: '--card-padding',+ default: 'var(--spacing-4)',+ description: 'Padding',+ options: SPACING_OPTIONS,+ },+ ],+ },+ field: {+ label: 'Field / Input',+ vars: [+ {+ name: '--input-radius',+ default: 'var(--radius-element)',+ description: 'Border radius',+ options: RADIUS_OPTIONS,+ },+ ],+ },+ banner: {+ label: 'Banner',+ vars: [+ {+ name: '--banner-radius',+ default: 'var(--radius-container)',+ description: 'Border radius',+ options: RADIUS_OPTIONS,+ },+ ],+ },+ 'segmented-control': {+ label: 'Segmented Control',+ vars: [+ {+ name: '--segmented-control-radius',+ default: 'var(--radius-element)',+ description: 'Border radius',+ options: RADIUS_OPTIONS,+ },+ {+ name: '--segmented-control-padding',+ default: 'var(--spacing-0-5)',+ description: 'Padding',+ options: SPACING_OPTIONS,+ },+ ],+ },+ dialog: {+ label: 'Dialog',+ vars: [+ {+ name: '--dialog-radius',+ default: 'var(--radius-container)',+ description: 'Border radius',+ options: RADIUS_OPTIONS,+ },+ {+ name: '--dialog-padding',+ default: 'var(--spacing-4)',+ description: 'Padding',+ options: SPACING_OPTIONS,+ },+ ],+ },+ 'dropdown-menu': {+ label: 'Dropdown Menu',+ vars: [+ {+ name: '--dropdown-radius',+ default: 'var(--radius-element)',+ description: 'Border radius',+ options: RADIUS_OPTIONS,+ },+ {+ name: '--dropdown-padding',+ default: 'var(--spacing-1)',+ description: 'Inner padding',+ options: SPACING_OPTIONS,+ },+ ],+ },+ section: {+ label: 'Section',+ vars: [+ {+ name: '--section-padding',+ default: 'var(--spacing-4)',+ description: 'Padding',+ options: SPACING_OPTIONS,+ },+ ],+ },+ popover: {+ label: 'Popover',+ vars: [+ {+ name: '--popover-radius',+ default: 'var(--radius-element)',+ description: 'Border radius',+ options: RADIUS_OPTIONS,+ },+ ],+ },+ hovercard: {+ label: 'Hover Card',+ vars: [+ {+ name: '--hovercard-radius',+ default: 'var(--radius-container)',+ description: 'Border radius',+ options: RADIUS_OPTIONS,+ },+ ],+ },+ 'chat-composer': {+ label: 'Chat Composer',+ vars: [+ {+ name: '--composer-radius',+ default: 'var(--radius-page)',+ description: 'Border radius',+ options: RADIUS_OPTIONS,+ },+ {+ name: '--composer-padding',+ default: 'var(--spacing-3)',+ description: 'Padding',+ options: SPACING_OPTIONS,+ },+ ],+ },+};++// Maps component CSS var names to defineTheme() components entries.+// Most use the derivedVarRegistry keys (which match CSS class names).+// Some components set internal --_ vars via StyleX on a child element,+// so we target the child class directly with the internal var name.+export const COMPONENT_VAR_TO_OVERRIDE: Record<+ string,+ {component: string; cssProperty: string}[]+> = {+ '--button-radius': [{component: 'button', cssProperty: 'borderRadius'}],+ '--card-radius': [{component: 'card', cssProperty: 'borderRadius'}],+ '--card-padding': [{component: 'card', cssProperty: 'padding'}],+ '--input-radius': [+ {component: 'text-input', cssProperty: '--_field-radius'},+ {component: 'textarea', cssProperty: '--_field-radius'},+ {component: 'selector', cssProperty: '--_field-radius'},+ ],+ '--banner-radius': [{component: 'banner', cssProperty: 'borderRadius'}],+ '--segmented-control-radius': [+ {component: 'segmented-control', cssProperty: 'borderRadius'},+ ],+ '--segmented-control-padding': [+ {component: 'segmented-control', cssProperty: 'padding'},+ ],+ '--dialog-radius': [{component: 'dialog', cssProperty: 'borderRadius'}],+ '--dialog-padding': [{component: 'dialog', cssProperty: 'padding'}],+ '--dropdown-radius': [+ {component: 'dropdown-menu', cssProperty: 'borderRadius'},+ ],+ '--dropdown-padding': [{component: 'dropdown-menu', cssProperty: 'padding'}],+ '--section-padding': [{component: 'section', cssProperty: 'padding'}],+ '--popover-radius': [{component: 'popover', cssProperty: 'borderRadius'}],+ '--hovercard-radius': [{component: 'hovercard', cssProperty: 'borderRadius'}],+ '--composer-radius': [+ {component: 'chat-composer', cssProperty: '--_chat-composer-radius'},+ ],+ '--composer-padding': [+ {component: 'chat-composer', cssProperty: '--_chat-composer-padding'},+ ],+};++export const COMPONENT_VAR_NAMES = new Set(+ Object.keys(COMPONENT_VAR_TO_OVERRIDE),+);++export const ALL_COMPONENT_NAMES = [+ 'alert-dialog',+ 'app-shell',+ 'avatar',+ 'badge',+ 'banner',+ 'button',+ 'calendar',+ 'card',+ 'chat-composer',+ 'chat-message',+ 'chat-message-bubble',+ 'checkbox',+ 'clickable-card',+ 'codeblock',+ 'collapsible',+ 'dialog',+ 'divider',+ 'dropdown-menu',+ 'emptystate',+ 'field',+ 'heading',+ 'hovercard',+ 'icon',+ 'link',+ 'list',+ 'markdown',+ 'popover',+ 'progressbar',+ 'radio',+ 'section',+ 'segmented-control',+ 'selector',+ 'side-nav',+ 'skeleton',+ 'slider',+ 'spinner',+ 'switch',+ 'tab',+ 'tab-list',+ 'table',+ 'text',+ 'text-input',+ 'textarea',+ 'toast',+ 'token',+ 'tooltip',+ 'top-nav',+] as const;++export const COLOR_CATEGORIES = {+ 'Core Semantic': [+ '--color-accent',+ '--color-accent-muted',+ '--color-on-accent',+ '--color-neutral',+ '--color-overlay',+ '--color-overlay-hover',+ '--color-overlay-pressed',+ ],+ Text: [+ '--color-text-primary',+ '--color-text-secondary',+ '--color-text-disabled',+ '--color-text-accent',+ '--color-on-dark',+ '--color-on-light',+ ],+ Icon: [+ '--color-icon-primary',+ '--color-icon-secondary',+ '--color-icon-disabled',+ ],+ 'Surface Variants': [+ '--color-background-surface',+ '--color-background-body',+ '--color-background-muted',+ '--color-background-card',+ '--color-background-popover',+ '--color-background-inverted',+ '--color-background-error-inverted',+ ],+ 'Category Colors': [+ '--color-background-blue',+ '--color-background-cyan',+ '--color-background-gray',+ '--color-background-green',+ '--color-background-orange',+ '--color-background-pink',+ '--color-background-purple',+ '--color-background-red',+ '--color-background-teal',+ '--color-background-yellow',+ ],+ 'Status/Sentiment': [+ '--color-success',+ '--color-success-muted',+ '--color-error',+ '--color-error-muted',+ '--color-warning',+ '--color-warning-muted',+ ],+ Divider: ['--color-border', '--color-border-emphasized'],+ Effects: ['--color-skeleton', '--color-shadow', '--color-tint-hover'],+} as const;++export const TYPOGRAPHY_CATEGORIES: Record<+ string,+ string[] | {description: string; tokens: string[]}+> = {+ 'Font Families': [+ '--font-family-body',+ '--font-family-heading',+ '--font-family-code',+ ],+ 'Heading 1': {+ description: 'Primary page title',+ tokens: [+ '--text-heading-1-size',+ '--text-heading-1-weight',+ '--text-heading-1-leading',+ ],+ },+ 'Heading 2': {+ description: 'Section title',+ tokens: [+ '--text-heading-2-size',+ '--text-heading-2-weight',+ '--text-heading-2-leading',+ ],+ },+ 'Heading 3': {+ description: 'Subsection title',+ tokens: [+ '--text-heading-3-size',+ '--text-heading-3-weight',+ '--text-heading-3-leading',+ ],+ },+ 'Body Text': {+ description: 'Default paragraph text',+ tokens: ['--text-body-size', '--text-body-weight', '--text-body-leading'],+ },+ 'Label Text': {+ description: 'Form labels, UI labels',+ tokens: [+ '--text-label-size',+ '--text-label-weight',+ '--text-label-leading',+ ],+ },+ 'Supporting Text': {+ description: 'Captions, helper text',+ tokens: [+ '--text-supporting-size',+ '--text-supporting-weight',+ '--text-supporting-leading',+ ],+ },+} as const;++export const GOOGLE_FONTS_URL =+ 'https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=Roboto:wght@400;500;700&family=DM+Sans:wght@400;500;600;700&family=Figtree:wght@400;500;600;700&family=Poppins:wght@400;500;600;700&family=IBM+Plex+Sans:wght@400;500;600;700&family=Source+Sans+3:wght@400;500;600;700&family=Noto+Sans:wght@400;500;600;700&display=swap';diff --git a/apps/docsite/src/components/themePlayground/helpers.ts b/apps/docsite/src/components/themePlayground/helpers.tsnew file mode 100644index 0000000000..0d05054787--- /dev/null+++ b/apps/docsite/src/components/themePlayground/helpers.ts@@ -0,0 +1,223 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {COMPONENT_VAR_TO_OVERRIDE, COMPONENT_VAR_NAMES} from './constants';++export function parseLightDark(+ value: string,+): {light: string; dark: string} | null {+ const match = value.match(/^light-dark\(([^,]+),\s*([^)]+)\)$/);+ if (match) {+ return {light: match[1].trim(), dark: match[2].trim()};+ }+ return null;+}++export function parseColorWithAlpha(+ value: string,+): {hex: string; alpha: number} | null {+ const hex8Match = value.match(/^#([0-9A-Fa-f]{8})$/);+ if (hex8Match) {+ const hex = '#' + hex8Match[1].slice(0, 6);+ const alpha = parseInt(hex8Match[1].slice(6, 8), 16) / 255;+ return {hex, alpha: Math.round(alpha * 100) / 100};+ }+ const hex6Match = value.match(/^#([0-9A-Fa-f]{6})$/);+ if (hex6Match) {+ return {hex: value, alpha: 1};+ }+ const hex3Match = value.match(/^#([0-9A-Fa-f]{3})$/);+ if (hex3Match) {+ const r = hex3Match[1][0];+ const g = hex3Match[1][1];+ const b = hex3Match[1][2];+ return {hex: `#${r}${r}${g}${g}${b}${b}`, alpha: 1};+ }+ const rgbaMatch = value.match(+ /rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/,+ );+ if (rgbaMatch) {+ const r = parseInt(rgbaMatch[1], 10).toString(16).padStart(2, '0');+ const g = parseInt(rgbaMatch[2], 10).toString(16).padStart(2, '0');+ const b = parseInt(rgbaMatch[3], 10).toString(16).padStart(2, '0');+ const alpha = rgbaMatch[4] ? parseFloat(rgbaMatch[4]) : 1;+ return {hex: `#${r}${g}${b}`, alpha};+ }+ return null;+}++export function colorWithAlphaToString(hex: string, alpha: number): string {+ if (alpha >= 1) {+ return hex.toUpperCase();+ }+ const alphaHex = Math.round(alpha * 255)+ .toString(16)+ .padStart(2, '0');+ return `${hex}${alphaHex}`.toUpperCase();+}++export function getTokenLabel(tokenName: string): string {+ return tokenName+ .replace(/^--/, '')+ .replace(/-/g, ' ')+ .replace(/\bbackground /gi, '')+ .replace(/\b\w/g, c => c.toUpperCase());+}++type ComponentStyleMap = Record<string, Record<string, Record<string, string>>>;++export function buildComponentOverrides(+ componentTokens: Record<string, string>,+): ComponentStyleMap {+ const components: ComponentStyleMap = {};+ for (const [varName, value] of Object.entries(componentTokens)) {+ const mappings = COMPONENT_VAR_TO_OVERRIDE[varName];+ if (!mappings) {+ continue;+ }+ for (const {component, cssProperty} of mappings) {+ components[component] ??= {};+ components[component].base ??= {};+ components[component].base[cssProperty] = value;+ }+ }+ return components;+}++/**+ * Deep-merge any number of component style maps into a fresh object. Later+ * maps win at the leaf level; nested selector objects (e.g. `variant:ghost`+ * → `:hover`) are merged recursively rather than replaced wholesale. Used to+ * layer a preset theme's component overrides under the editor's own token-+ * and custom-overrides so all three sources compose correctly.+ */+export function mergeComponentStyleMaps(+ ...maps: Array<Record<string, unknown> | undefined>+): Record<string, unknown> {+ const result: Record<string, unknown> = {};+ for (const map of maps) {+ if (!map) {+ continue;+ }+ for (const [key, value] of Object.entries(map)) {+ const existing = result[key];+ if (+ value &&+ typeof value === 'object' &&+ existing &&+ typeof existing === 'object'+ ) {+ result[key] = mergeComponentStyleMaps(+ existing as Record<string, unknown>,+ value as Record<string, unknown>,+ );+ } else if (value && typeof value === 'object') {+ result[key] = mergeComponentStyleMaps(value as Record<string, unknown>);+ } else {+ result[key] = value;+ }+ }+ }+ return result;+}++/**+ * Serialize a nested style object to indented `defineTheme`-style source+ * lines. Handles arbitrary selector nesting (base, `variant:*`, `:hover`,+ * etc.) so the exported code matches what the live preview renders.+ */+function serializeStyleObject(+ obj: Record<string, unknown>,+ indentLevel: number,+): string[] {+ const pad = ' '.repeat(indentLevel);+ const lines: string[] = [];+ for (const [key, value] of Object.entries(obj)) {+ const escapedKey = key.replace(/\\/g, '\\\\').replace(/'/g, "\\'");+ if (value && typeof value === 'object') {+ lines.push(`${pad}'${escapedKey}': {`);+ lines.push(+ ...serializeStyleObject(value as Record<string, unknown>, indentLevel + 1),+ );+ lines.push(`${pad}},`);+ } else {+ const escapedVal = String(value)+ .replace(/\\/g, '\\\\')+ .replace(/'/g, "\\'");+ lines.push(`${pad}'${escapedKey}': '${escapedVal}',`);+ }+ }+ return lines;+}++export interface CustomOverrideEntry {+ component: string;+ property: string;+ value: string;+}++export function generateThemeCode(+ themeName: string,+ tokens: Record<string, string>,+ allDefaults: Record<string, string>,+ typeScaleBase: number,+ typeScaleRatio: number,+ customOverrides: CustomOverrideEntry[] = [],+ baseComponents: Record<string, unknown> = {},+): string {+ const changedTokens: Record<string, string> = {};+ const changedComponentTokens: Record<string, string> = {};+ for (const [key, value] of Object.entries(tokens)) {+ if (allDefaults[key] !== value) {+ if (COMPONENT_VAR_NAMES.has(key)) {+ changedComponentTokens[key] = value;+ } else {+ changedTokens[key] = value;+ }+ }+ }++ // Custom overrides are flat (component → base → property). Build them as a+ // map so they can be merged on top of the preset + token-derived overrides.+ const customMap: Record<string, {base: Record<string, string>}> = {};+ for (const override of customOverrides) {+ customMap[override.component] ??= {base: {}};+ customMap[override.component].base[override.property] = override.value;+ }+ const components = mergeComponentStyleMaps(+ baseComponents,+ buildComponentOverrides(changedComponentTokens),+ customMap,+ );++ const lines: string[] = [+ "import {defineTheme} from '@xds/core/theme';",+ '',+ `export const ${themeName}Theme = defineTheme({`,+ ` name: '${themeName}',`,+ ];++ if (typeScaleBase !== 14 || typeScaleRatio !== 1.2) {+ lines.push(' typography: {');+ lines.push(+ ` scale: {base: ${typeScaleBase}, ratio: ${typeScaleRatio}},`,+ );+ lines.push(' },');+ }++ if (Object.keys(changedTokens).length > 0) {+ lines.push(' tokens: {');+ for (const [key, value] of Object.entries(changedTokens)) {+ lines.push(` '${key}': '${value}',`);+ }+ lines.push(' },');+ }++ if (Object.keys(components).length > 0) {+ lines.push(' components: {');+ lines.push(...serializeStyleObject(components, 2));+ lines.push(' },');+ }++ lines.push('});');+ return lines.join('\n');+}diff --git a/apps/docsite/src/components/themePlayground/icons.tsx b/apps/docsite/src/components/themePlayground/icons.tsxnew file mode 100644index 0000000000..846b0d1d83--- /dev/null+++ b/apps/docsite/src/components/themePlayground/icons.tsx@@ -0,0 +1,46 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * Icon shim for the theme playground. The tool was authored against internal+ * `@xds/*` icon packages; the OSS docsite uses Heroicons. Each export keeps+ * the original icon name (aliased to the closest Heroicon) and renders at the+ * 16px size the editor expects, so the ported component code stays unchanged.+ */++import * as React from 'react';+import {+ ArrowLeftIcon,+ SunIcon,+ MoonIcon,+ SwatchIcon,+ Squares2X2Icon,+ Square2StackIcon,+ LanguageIcon,+ ArrowsPointingOutIcon,+ Square3Stack3DIcon,+ ClockIcon,+ BoltIcon,+} from '@heroicons/react/24/outline';++type IconProps = React.SVGProps<SVGSVGElement>;++const sized =+ (Icon: React.ComponentType<IconProps>) =>+ (props: IconProps): React.ReactElement => (+ <Icon width={16} height={16} {...props} />+ );++// ThemeEditorView+export const ArrowLeftFilled16Icon = sized(ArrowLeftIcon);+export const LargeHalfCircle8RaysLargeOutline16Icon = sized(SunIcon);+export const CrescentOutline16Icon = sized(MoonIcon);++// RawTokensPanel token-category icons+export const PaletteOutline16Icon = sized(SwatchIcon);+export const FourRectangleGridOutline16Icon = sized(Squares2X2Icon);+export const FrameDashedOutline16Icon = sized(Square2StackIcon);+export const BigALittleAOutline16Icon = sized(LanguageIcon);+export const AspectRatioOutline16Icon = sized(ArrowsPointingOutIcon);+export const SquareOutline16Icon = sized(Square3Stack3DIcon);+export const StopwatchOutline16Icon = sized(ClockIcon);+export const BoltOutline16Icon = sized(BoltIcon);diff --git a/apps/docsite/src/components/themePlayground/themeList.ts b/apps/docsite/src/components/themePlayground/themeList.tsnew file mode 100644index 0000000000..f5977dd0da--- /dev/null+++ b/apps/docsite/src/components/themePlayground/themeList.ts@@ -0,0 +1,30 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * Theme presets available to the playground, derived from the docsite's+ * generated theme registry. The [theme] route segment maps to one of these by+ * name and seeds the editor with the full theme object.+ */++import type {XDSDefinedTheme} from '@xds/core/theme';+import {themeObjects} from '../../generated/themeRegistry';++export interface ThemeListEntry {+ name: string;+ label: string;+ theme: XDSDefinedTheme;+}++export function getThemeList(): ThemeListEntry[] {+ return Object.values(themeObjects)+ .map(theme => ({+ name: theme.name,+ label: theme.name.charAt(0).toUpperCase() + theme.name.slice(1),+ theme,+ }))+ .sort((a, b) => a.name.localeCompare(b.name));+}++export function getThemeByName(name: string): ThemeListEntry | undefined {+ return getThemeList().find(entry => entry.name === name);+}diff --git a/apps/docsite/src/themes/astryxTheme.ts b/apps/docsite/src/themes/astryxTheme.tsindex 35b4e69cce..16c46c94ab 100644--- a/apps/docsite/src/themes/astryxTheme.ts+++ b/apps/docsite/src/themes/astryxTheme.ts@@ -24,6 +24,14 @@ export const astryxTheme = defineTheme({// other token at the XDS default.tokens: {'--color-accent': '#292724',+ // Setting --color-accent alone leaves the *derived* accent tokens+ // (text/icon/muted) at the XDS default blue, so links and accent icons+ // across the docsite stayed blue. Point them at the brand accent too.+ // light-dark() keeps dark mode legible (near-black is invisible on dark).+ '--color-text-accent': 'light-dark(#292724, #E8E3DA)',+ '--color-icon-accent': 'light-dark(#292724, #E8E3DA)',+ '--color-accent-muted':+ 'light-dark(rgba(41, 39, 36, 0.12), rgba(232, 227, 218, 0.16))','--color-background-body': '#F8F4ED',// Astryx display headings render semibold (XDS default is normal weight).'--text-display-1-weight': 'var(--font-weight-semibold)',