Skip to content

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

TypeScript

Playground code clean up (#2895)

Kenton Quatman43af6ffa4e91
diff --git a/apps/docsite/src/app/(preview)/playground-preview/layout.tsx b/apps/docsite/src/app/(preview)/playground-preview/layout.tsx
deleted file mode 100644
index 6676f99ca3..0000000000
--- a/apps/docsite/src/app/(preview)/playground-preview/layout.tsx
+++ /dev/null
@@ -1,73 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-export default function PreviewLayout({children}: {children: React.ReactNode}) {
- return (
- <>
- <style>{`
- html, body { height: 100%; margin: 0; }
-
- /* ── Targeting overlay ── */
- .pg-targeting { cursor: crosshair !important; }
- .pg-targeting * { cursor: crosshair !important; }
-
- .pg-target-overlay {
- position: fixed;
- pointer-events: none;
- z-index: 999999;
- border: 2px solid var(--color-border-focus, #1877f2);
- border-radius: var(--radius-element, 6px);
- background: rgba(24, 119, 242, 0.06);
- transition: top 80ms ease-out, left 80ms ease-out,
- width 80ms ease-out, height 80ms ease-out;
- display: none;
- }
- .pg-target-overlay[data-visible="true"] { display: block; }
-
- .pg-target-label {
- position: absolute;
- bottom: 100%;
- left: -2px;
- margin-bottom: var(--spacing-1, 4px);
- padding: var(--spacing-0-5, 2px) var(--spacing-3, 12px);
- font: 500 11px/16px ui-sans-serif, system-ui, sans-serif;
- background: var(--color-border-focus, #1877f2);
- border-radius: var(--radius-corner, 4px);
- white-space: nowrap;
- user-select: none;
- pointer-events: auto;
- }
- .pg-target-label-bottom {
- top: 100%;
- bottom: auto;
- margin-top: 4px;
- margin-bottom: 0;
- }
-
- .pg-target-selection {
- position: fixed;
- pointer-events: none;
- z-index: 999998;
- border: 2px solid var(--color-border-focus, #1877f2);
- border-radius: var(--radius-element, 6px);
- background: rgba(24, 119, 242, 0.06);
- display: none;
- }
- .pg-target-selection[data-visible="true"] { display: block; }
-
- .pg-target-selection .pg-target-label {
- position: absolute;
- bottom: 100%;
- left: -2px;
- margin-bottom: 4px;
- }
- .pg-target-selection .pg-target-label-bottom {
- top: 100%;
- bottom: auto;
- margin-top: 4px;
- margin-bottom: 0;
- }
- `}</style>
- {children}
- </>
- );
-}
diff --git a/apps/docsite/src/app/(site)/themes/[name]/page.tsx b/apps/docsite/src/app/(site)/themes/[name]/page.tsx
deleted file mode 100644
index a31e99ee38..0000000000
--- a/apps/docsite/src/app/(site)/themes/[name]/page.tsx
+++ /dev/null
@@ -1,34 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-/**
- * Deep-link redirect — /themes/<name> → /themes?theme=<name>
- *
- * The themes surface was consolidated into a single state-driven
- * explorer at /themes (see ./page.tsx). To keep existing deep links
- * working (docs cross-links, shared URLs, search bookmarks), this
- * route accepts the original `/themes/<slug>` shape and redirects to
- * the canonical query-param form `/themes?theme=<slug>`, which the
- * explorer reads on mount to preselect the right theme in its
- * sidebar picker.
- *
- * Only known theme slugs are statically generated; any other slug
- * falls through Next's default routing and returns a 404, matching
- * the pre-consolidation behavior of the deleted per-theme page.
- */
-import {redirect} from 'next/navigation';
-import {packages} from '../../../../generated/packageRegistry';
-
-export function generateStaticParams() {
- return packages
- .filter(p => p.name.startsWith('@xds/theme-'))
- .map(p => ({name: p.name.replace('@xds/theme-', '')}));
-}
-
-export default async function ThemeRedirectPage({
- params,
-}: {
- params: Promise<{name: string}>;
-}) {
- const {name: slug} = await params;
- redirect(`/themes?theme=${encodeURIComponent(slug)}`);
-}
diff --git a/apps/docsite/src/app/playground/ConfirmDialog.tsx b/apps/docsite/src/app/playground/ConfirmDialog.tsx
index bca0c13bec..6d88c66c3f 100644
--- a/apps/docsite/src/app/playground/ConfirmDialog.tsx
+++ b/apps/docsite/src/app/playground/ConfirmDialog.tsx
@@ -11,7 +11,7 @@
* user's current code or theme.
*/
-import {type ReactNode} from 'react';
+import type {ReactNode} from 'react';
import {XDSButton} from '@xds/core/Button';
import {
XDSHStack,
@@ -22,7 +22,7 @@ import {
import {XDSText} from '@xds/core/Text';
import {XDSDialog, XDSDialogHeader} from '@xds/core/Dialog';
-export interface ConfirmDialogProps {
+interface ConfirmDialogProps {
/** Whether the dialog is open. */
isOpen: boolean;
/** Dialog title shown in the header. */
@@ -68,7 +68,7 @@ export function ConfirmDialog({
</XDSLayoutContent>
}
footer={
- <XDSLayoutFooter hasDivider>
+ <XDSLayoutFooter>
<XDSHStack gap={2} justify="end" width="100%">
<XDSButton
variant="secondary"
@@ -87,5 +87,3 @@ export function ConfirmDialog({
</XDSDialog>
);
}
-
-ConfirmDialog.displayName = 'ConfirmDialog';
diff --git a/apps/docsite/src/app/playground/PlaygroundClient.tsx b/apps/docsite/src/app/playground/PlaygroundClient.tsx
index 1f710a607d..03a55316d1 100644
--- a/apps/docsite/src/app/playground/PlaygroundClient.tsx
+++ b/apps/docsite/src/app/playground/PlaygroundClient.tsx
@@ -13,7 +13,7 @@
* - Property: component selector + instance picker + knobs that edit the code.
* Right panel: toolbar (dark mode · target element · viewport
* segmented control · share · expand) over a responsive
- * /playground-preview iframe.
+ * /playground/preview iframe.
*
* The preview iframe is driven via postMessage (preview-code / preview-theme);
* code lives in React state and is the single source of truth shared by Monaco,
@@ -25,13 +25,14 @@
import {useCallback, useEffect, useMemo, useRef, useState} from 'react';
import {useSearchParams} from 'next/navigation';
import dynamic from 'next/dynamic';
-import {loader} from '@monaco-editor/react';
import * as stylex from '@stylexjs/stylex';
import {XDSAppShell} from '@xds/core/AppShell';
import {compressCode, decompressCode} from '../../lib/compress';
import {XDSButton} from '@xds/core/Button';
import {XDSLink} from '@xds/core/Link';
import {XDSHStack, XDSVStack} from '@xds/core/Layout';
+import {XDSCenter} from '@xds/core/Center';
+import {XDSSpinner} from '@xds/core/Spinner';
import {XDSPopover} from '@xds/core/Popover';
import {XDSTextInput} from '@xds/core/TextInput';
import {
@@ -68,74 +69,41 @@ import {
RotateCw,
Crosshair,
} from 'lucide-react';
-import githubLight from './themes/github-light.json';
-import githubDark from './themes/github-dark.json';
+import githubLight from './codeEditorThemes/github-light.json';
+import githubDark from './codeEditorThemes/github-dark.json';
import {useThemeMode} from '../providers';
import {
DEFAULT_PLAYGROUND_THEME,
PLAYGROUND_THEME_OPTIONS,
themeByValue,
-} from './playgroundThemes';
+} from './previewThemes';
import {templates} from '../../generated/templateRegistry';
import {PreviewStage, type Viewport} from './PreviewStage';
import {ConfirmDialog} from './ConfirmDialog';
import {BRAND_ICON} from '../../components/XDSWordmark';
-import {annotateInstanceIds} from './babelParser';
+import {annotateInstanceIds} from './propertyEditor/componentInstances';
import {trackCopy} from '../../lib/analytics';
-import {PlaygroundThemeEditor} from '../../components/themePlayground/PlaygroundThemeEditor';
-import {generateThemeCode} from '../../components/themePlayground/helpers';
+import {ThemeEditor} from './themeEditor/ThemeEditor';
+import {generateThemeCode} from './themeEditor/helpers';
import {DEFAULT_CODE} from './defaultCode';
import {stripCodeExampleCopyrightHeader} from '../../lib/codeExamples';
+import {configureMonaco, type MonacoInstance} from './monacoSetup';
import type * as MonacoTypes from 'monaco-editor';
import type {XDSDefinedTheme} from '@xds/core/theme';
import {xdsTokenDefaults} from '@xds/core/theme';
-// Source of the theme-showcase template — a set of real product surfaces
-// (store, checkout, chat, inventory) used to preview a theme. It's hidden
-// from the generated templates registry (isHiddenFromOverview), so it's added
+// Hidden from the generated registry (isHiddenFromOverview), so it's added
// explicitly as the first entry in the Templates dropdown.
const THEME_SHOWCASE_SOURCE =
templates.find(t => t.slug === 'theme-showcase')?.source ?? '';
-// Self-host Monaco from public/monaco/vs — corpnet blocks the default
-// jsdelivr CDN. Configure the singleton loader before the editor initializes.
-if (typeof window !== 'undefined') {
- loader.config({paths: {vs: '/monaco/vs'}});
-}
-
-/** Monaco instance type — the full runtime object passed to onMount */
-type MonacoInstance = typeof MonacoTypes & {
- languages: typeof MonacoTypes.languages & {
- typescript: {
- typescriptDefaults: {
- setCompilerOptions: (options: Record<string, unknown>) => void;
- setDiagnosticsOptions: (options: Record<string, unknown>) => void;
- addExtraLib: (content: string, filePath: string) => void;
- };
- ScriptTarget: Record<string, number>;
- ModuleKind: Record<string, number>;
- JsxEmit: Record<string, number>;
- ModuleResolutionKind: Record<string, number>;
- };
- };
- editor: typeof MonacoTypes.editor & {
- defineTheme: (name: string, data: Record<string, unknown>) => void;
- };
-};
-
const MonacoEditor = dynamic(() => import('@monaco-editor/react'), {
ssr: false,
loading: () => (
- <div
- style={{
- flex: 1,
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
- }}>
- <XDSText color="secondary">Loading editor…</XDSText>
- </div>
+ <XDSCenter height="100%">
+ <XDSSpinner label="Loading editor…" />
+ </XDSCenter>
),
});
@@ -164,128 +132,6 @@ function updateURL(code: string) {
window.history.replaceState(null, '', `#code=${compressed}`);
}
-/**
- * Configure Monaco's TypeScript service with real XDS type definitions.
- * Loads .d.ts files from a pre-built JSON bundle (generated at build time).
- */
-function configureMonaco(monaco: MonacoInstance) {
- const ts = monaco.languages.typescript.typescriptDefaults;
-
- ts.setCompilerOptions({
- target: monaco.languages.typescript.ScriptTarget.ESNext,
- module: monaco.languages.typescript.ModuleKind.ESNext,
- jsx: monaco.languages.typescript.JsxEmit.ReactJSX,
- esModuleInterop: true,
- allowSyntheticDefaultImports: true,
- moduleResolution: monaco.languages.typescript.ModuleResolutionKind.NodeJs,
- allowJs: true,
- strict: false,
- });
-
- ts.setDiagnosticsOptions({
- noSemanticValidation: true,
- noSyntaxValidation: false,
- });
-
- // Global declarations for React hooks (available without import in playground)
- ts.addExtraLib(
- `declare function useState<T>(init: T | (() => T)): [T, (v: T | ((prev: T) => T)) => void];
- declare function useEffect(fn: () => void | (() => void), deps?: readonly unknown[]): void;
- declare function useCallback<T extends Function>(fn: T, deps: readonly unknown[]): T;
- declare function useMemo<T>(fn: () => T, deps: readonly unknown[]): T;
- declare function useRef<T>(init: T): { current: T };
- declare function useReducer<S, A>(reducer: (state: S, action: A) => S, init: S): [S, (action: A) => void];
- declare function useContext<T>(ctx: unknown): T;`,
- 'file:///globals.d.ts',
- );
-
- // Lucide icons wildcard stub — gives Monaco a sense of the
- // module's shape so import { Icon } from 'lucide-react' doesn't
- // light up with red squigglies in the playground editor.
- ts.addExtraLib(
- `declare module 'lucide-react' { const icons: Record<string, React.ComponentType<{size?: number | string; color?: string; strokeWidth?: number | string; className?: string}>>; export = icons; }`,
- 'file:///node_modules/lucide-react/index.d.ts',
- );
-
- // Load real type definitions from the pre-built JSON bundle
- fetch('/playground-types.json')
- .then(r => r.json())
- .then((packages: Record<string, Record<string, string>>) => {
- const reactFiles = packages['react'] ?? {};
- for (const [fileName, content] of Object.entries(reactFiles)) {
- ts.addExtraLib(
- content,
- `file:///node_modules/@types/react/${fileName}`,
- );
- // Also register react/jsx-runtime as a resolvable module path
- if (fileName === 'jsx-runtime.d.ts') {
- ts.addExtraLib(
- content,
- 'file:///node_modules/react/jsx-runtime.d.ts',
- );
- }
- }
-
- const stylexFiles = packages['@stylexjs/stylex'] ?? {};
- for (const [fileName, content] of Object.entries(stylexFiles)) {
- ts.addExtraLib(
- content,
- `file:///node_modules/@stylexjs/stylex/${fileName}`,
- );
- }
-
- // Heroicons ambient declarations, one per size/style variant. Template
- // and example code imports icons by name from
- // '@heroicons/react/{16,20,24}/{outline,solid}', so each declaration
- // exposes the variant's icons as named exports. Without these, every
- // heroicons import lights up with a "Cannot find module" red squiggle
- // once semantic validation turns on below.
- const heroiconFiles = packages['@heroicons/react'] ?? {};
- for (const [fileName, content] of Object.entries(heroiconFiles)) {
- const variant = fileName.replace(/\.d\.ts$/, '');
- ts.addExtraLib(
- content,
- `file:///node_modules/@heroicons/react/${variant}/index.d.ts`,
- );
- }
-
- const xdsFiles = packages['@xds/core'] ?? {};
- const submoduleReexports: string[] = [];
-
- for (const [relPath, content] of Object.entries(xdsFiles)) {
- ts.addExtraLib(
- content,
- `file:///node_modules/@xds/core/dist/${relPath}`,
- );
-
- if (relPath.endsWith('/index.d.ts')) {
- const moduleName = relPath.replace('/index.d.ts', '');
- ts.addExtraLib(
- content,
- `file:///node_modules/@xds/core/${moduleName}/index.d.ts`,
- );
- submoduleReexports.push(moduleName);
- }
- }
-
- const barrelContent = submoduleReexports
- .map(m => `export * from '@xds/core/${m}';`)
- .join('\n');
- ts.addExtraLib(
- `declare module '@xds/core' {\n${barrelContent}\n}`,
- 'file:///node_modules/@xds/core/index.d.ts',
- );
-
- ts.setDiagnosticsOptions({
- noSemanticValidation: false,
- noSyntaxValidation: false,
- });
- })
- .catch(() => {
- // Types unavailable — keep semantic validation disabled
- });
-}
-
type LeftView = 'code' | 'theme';
type MobileTopTab = 'preview' | 'code' | 'theme';
type BuildStatus = 'idle' | 'building' | 'finished' | 'error';
@@ -336,21 +182,12 @@ const s = stylex.create({
tabBody: {
flex: 1,
minHeight: 0,
- display: 'flex',
- flexDirection: 'column',
overflow: 'hidden',
},
- codePane: {
- flex: 1,
- minHeight: 0,
- minWidth: 0,
- },
- themePane: {
+ pane: {
flex: 1,
minHeight: 0,
minWidth: 0,
- display: 'flex',
- flexDirection: 'column',
},
rightPanel: {
flex: 1,
@@ -361,13 +198,13 @@ const s = stylex.create({
backgroundColor: 'var(--color-background-muted)',
},
buildStatus: {
- display: 'flex',
- alignItems: 'center',
- gap: 'var(--spacing-2)',
transitionProperty: 'opacity',
transitionDuration: '0.5s',
transitionTimingFunction: 'ease',
},
+ buildStatusFaded: {
+ opacity: 0,
+ },
sideNavHeading: {
paddingInline: {
default: null,
@@ -395,22 +232,17 @@ export function PlaygroundClient({defaultIsMobile}: PlaygroundClientProps) {
const [code, setCode] = useState(getInitialCode);
const [mode, setMode] = useState<'light' | 'dark'>('light');
// A ?theme=<value> query param (e.g. from the themes gallery's "Open in
- // Playground") seeds the Theme view with that theme and applies it to the
- // preview. useSearchParams reads it reliably across App Router client-side
- // navigation (a window.location read at mount can be stale on soft nav).
- // Validated against the registered themes; null when absent or unknown so
- // the playground keeps its default, unseeded behavior.
+ // Playground") seeds the Theme view and preview. useSearchParams reads it
+ // reliably across soft navigation; validated against registered themes.
const searchParams = useSearchParams();
const rawThemeParam = searchParams.get('theme');
const themeParam =
rawThemeParam && rawThemeParam in themeByValue ? rawThemeParam : null;
const theme = themeParam ?? DEFAULT_PLAYGROUND_THEME;
- // The theme whose values seed the Theme editor: the ?theme= theme on first
- // load, then whichever theme the user picks from the "Themes" dropdown.
- // Changing it remounts the editor (via key) so it re-populates from that theme.
+ // The theme that seeds the Theme editor: the ?theme= theme on first load, then
+ // whichever theme the user picks from "Themes". Changing it remounts the
+ // editor (via key) so it re-populates.
const [selectedTheme, setSelectedTheme] = useState(theme);
- // The theme object the editor is seeded from. Always defined so the always-
- // mounted Theme editor reflects the active theme and stays the source of truth.
const editorInitialTheme =
themeByValue[selectedTheme] ?? themeByValue[DEFAULT_PLAYGROUND_THEME];
const [activeView, setActiveView] = useState<LeftView>('code');
@@ -423,26 +255,18 @@ export function PlaygroundClient({defaultIsMobile}: PlaygroundClientProps) {
const [copied, setCopied] = useState(false);
const [shareUrl, setShareUrl] = useState('');
const [themeName, setThemeName] = useState('');
- // Snapshot of the theme to export, captured when the Export popover opens.
- // The live theme lives in customThemeRef (a ref, updated as the user edits
- // tokens without re-rendering the playground); we copy it into state on
- // open so the download link below can be built declaratively from reactive
- // state. The popover is in the toolbar, so the theme isn't being edited
- // while it's open — the snapshot stays current.
+ // Snapshot of the theme to export, captured when the Export popover opens, so
+ // the download link can be built declaratively from reactive state (the live
+ // theme lives in customThemeRef and changes without re-rendering).
const [exportTheme, setExportTheme] = useState<XDSDefinedTheme | null>(null);
const [previewReady, setPreviewReady] = useState(false);
const [isTargeting, setIsTargeting] = useState(false);
- // The theme value awaiting confirmation from the "Example themes" dropdown.
- // Applying an example theme re-seeds the Theme editor and discards the
- // current theme, so we hold the pending choice until the user confirms.
- // The dialog is open whenever this is non-null.
+ // Pending confirmations: applying an example theme / loading a template both
+ // discard the user's current work, so the choice is held until they confirm.
+ // The matching dialog is open whenever the value is non-null.
const [pendingExampleTheme, setPendingExampleTheme] = useState<string | null>(
null,
);
- // The template source awaiting confirmation from the "Templates" dropdown.
- // Loading a template overwrites the code editor, so we hold the pending
- // choice until the user confirms. The dialog is open whenever this is
- // non-null.
const [pendingTemplateSource, setPendingTemplateSource] = useState<
string | null
>(null);
@@ -454,12 +278,10 @@ export function PlaygroundClient({defaultIsMobile}: PlaygroundClientProps) {
const editorRef = useRef<MonacoTypes.editor.IStandaloneCodeEditor | null>(
null,
);
- // Points at the declaratively-rendered theme-export download link (below).
- // The Download button triggers it so we get native download behavior from a
- // normally-rendered <a> rather than fabricating one in a click handler.
+ // Points at the hidden theme-export download link (below); the Download button
+ // clicks it for native download behavior from a real <a>.
const downloadLinkRef = useRef<HTMLAnchorElement>(null);
- // Mirror activeView in a ref so onMount can read the current view without
- // re-creating the (stable) mount callback.
+ // Mirror activeView in a ref so the stable onMount callback can read it.
const activeViewRef = useRef(activeView);
activeViewRef.current = activeView;
// Latest theme authored in the Theme view, retained so a mode toggle can
@@ -473,11 +295,8 @@ export function PlaygroundClient({defaultIsMobile}: PlaygroundClientProps) {
autoSaveId: 'xds-playground-left-width',
});
- // Seed the initial preview mode from the docsite's mode so the preview opens
- // consistent with the rest of the site. (The toolbar toggle can still switch
- // the preview independently afterward.)
- // Seed once on mount with the current docsite mode; afterward the preview
- // toggle owns this state, so siteMode is intentionally read only initially.
+ // Seed the preview mode once from the docsite's mode; afterward the toolbar
+ // toggle owns it, so siteMode is intentionally read only on mount.
const initialSiteModeRef = useRef(siteMode);
useEffect(() => {
setMode(initialSiteModeRef.current);
@@ -495,14 +314,10 @@ export function PlaygroundClient({defaultIsMobile}: PlaygroundClientProps) {
return () => window.removeEventListener('hashchange', onHashChange);
}, []);
- // Re-read the hash once on mount. When arriving via a soft (client-side)
- // navigation — e.g. the Themes page's "Open in Playground" link routed
- // through Next's <Link> — the App Router commits the new URL slightly
- // after this component first renders, so the synchronous getInitialCode()
- // seed for `code` above can miss the fragment and fall back to
- // DEFAULT_CODE. A hashchange event isn't emitted for that navigation
- // (the page itself changes, not just the fragment), so we read the
- // committed hash here, after mount, and adopt the seeded code if present.
+ // Re-read the hash once on mount. On soft navigation (e.g. the Themes page's
+ // "Open in Playground" <Link>) the App Router commits the URL after first
+ // render, so the synchronous seed above can miss the fragment, and no
+ // hashchange fires. Adopt the committed hash's code here if present.
useEffect(() => {
const seeded = getInitialCode();
if (seeded !== DEFAULT_CODE) {
@@ -521,17 +336,23 @@ export function PlaygroundClient({defaultIsMobile}: PlaygroundClientProps) {
}
}, [themeParam]);
- const send = useCallback((c: string, source?: string) => {
- const win = iframeRef.current?.contentWindow;
- if (!win) {
- return;
- }
- win.postMessage(
- c ? {type: 'preview-code', code: c, source} : {type: 'preview-clear'},
+ // Single channel to the preview iframe; no-ops until the iframe exists.
+ const postToPreview = useCallback((message: unknown) => {
+ iframeRef.current?.contentWindow?.postMessage(
+ message,
window.location.origin,
);
}, []);
+ const send = useCallback(
+ (c: string, source?: string) => {
+ postToPreview(
+ c ? {type: 'preview-code', code: c, source} : {type: 'preview-clear'},
+ );
+ },
+ [postToPreview],
+ );
+
// Send the preview an instance-annotated copy of the code (markers let the
// preview map a selected component to its DOM node for the focus-ring flash),
// plus the clean source so the in-preview Properties popover can parse + edit
@@ -546,29 +367,26 @@ export function PlaygroundClient({defaultIsMobile}: PlaygroundClientProps) {
const postCustomTheme = useCallback(
(customTheme: XDSDefinedTheme) => {
customThemeRef.current = customTheme;
- iframeRef.current?.contentWindow?.postMessage(
- {
- type: 'preview-theme',
- customTokens: customTheme.tokens,
- customComponents: customTheme.components,
- mode,
- },
- window.location.origin,
- );
+ postToPreview({
+ type: 'preview-theme',
+ customTokens: customTheme.tokens,
+ customComponents: customTheme.components,
+ mode,
+ });
},
- [mode],
+ [mode, postToPreview],
);
- const toggleTargeting = useCallback((pressed?: boolean) => {
- setIsTargeting(prev => {
- const next = pressed ?? !prev;
- iframeRef.current?.contentWindow?.postMessage(
- {type: next ? 'targeting-enable' : 'targeting-disable'},
- window.location.origin,
- );
- return next;
- });
- }, []);
+ const toggleTargeting = useCallback(
+ (pressed?: boolean) => {
+ setIsTargeting(prev => {
+ const next = pressed ?? !prev;
+ postToPreview({type: next ? 'targeting-enable' : 'targeting-disable'});
+ return next;
+ });
+ },
+ [postToPreview],
+ );
useEffect(() => {
const handler = (e: MessageEvent) => {
@@ -600,10 +418,7 @@ export function PlaygroundClient({defaultIsMobile}: PlaygroundClientProps) {
// mode. Properties are edited via the badge's popover now, so the left
// panel stays on whatever view is currently open.
setIsTargeting(false);
- iframeRef.current?.contentWindow?.postMessage(
- {type: 'targeting-disable'},
- window.location.origin,
- );
+ postToPreview({type: 'targeting-disable'});
}
if (e.data?.type === 'targeting-exit') {
setIsTargeting(false);
@@ -611,7 +426,7 @@ export function PlaygroundClient({defaultIsMobile}: PlaygroundClientProps) {
};
window.addEventListener('message', handler);
return () => window.removeEventListener('message', handler);
- }, [postCode]);
+ }, [postCode, postToPreview]);
useEffect(() => {
const interval = setInterval(() => {
@@ -619,13 +434,10 @@ export function PlaygroundClient({defaultIsMobile}: PlaygroundClientProps) {
clearInterval(interval);
return;
}
- iframeRef.current?.contentWindow?.postMessage(
- {type: 'preview-ping'},
- window.location.origin,
- );
+ postToPreview({type: 'preview-ping'});
}, 300);
return () => clearInterval(interval);
- }, []);
+ }, [postToPreview]);
// Debounced push of code → preview + URL hash
useEffect(() => {
@@ -650,35 +462,17 @@ export function PlaygroundClient({defaultIsMobile}: PlaygroundClientProps) {
};
}, [code, postCode]);
- // Theme + mode → preview. Also re-sent once the preview signals ready so a
- // non-default initial theme (e.g. neutral) applies even if this effect first
- // ran before the iframe was listening. Once the Theme editor has produced a
- // theme (seeded via ?theme= or edited by the user), it becomes the source of
- // truth and is applied across ALL views (Code / Properties / Theme) so the
- // preview stays consistent when switching tabs and when toggling light/dark.
+ // Theme + mode → preview. Re-sent on previewReady so a non-default initial
+ // theme still applies if this first ran before the iframe was listening. A
+ // theme authored in the Theme editor takes precedence and stays the source of
+ // truth across all views.
useEffect(() => {
- const win = iframeRef.current?.contentWindow;
- if (!win) {
- return;
- }
if (customThemeRef.current) {
- const custom = customThemeRef.current;
- win.postMessage(
- {
- type: 'preview-theme',
- customTokens: custom.tokens,
- customComponents: custom.components,
- mode,
- },
- window.location.origin,
- );
+ postCustomTheme(customThemeRef.current);
} else {
- win.postMessage(
- {type: 'preview-theme', theme, mode},
- window.location.origin,
- );
+ postToPreview({type: 'preview-theme', theme, mode});
}
- }, [mode, previewReady, activeView, theme]);
+ }, [mode, previewReady, activeView, theme, postCustomTheme, postToPreview]);
// While the resize handle is dragged, the cursor can pass over the preview
// iframe — a separate document that swallows pointer events and stalls the
@@ -739,13 +533,9 @@ export function PlaygroundClient({defaultIsMobile}: PlaygroundClientProps) {
});
}, []);
- // Derive the export href from reactive state so the download is a real,
- // normally-rendered <a> (see downloadLinkRef below) rather than a DOM
- // element fabricated and clicked inside a callback. The active theme is the
- // one authored in the Theme editor (snapshotted into state when the popover
- // opens), falling back to the seeded theme. Returns the suggested filename
- // and a data: URL holding the generated `defineTheme` source; null until a
- // theme name is entered.
+ // Derive the export href (filename + data: URL of the generated defineTheme
+ // source) from reactive state, so the download is a real <a> (downloadLinkRef)
+ // rather than a fabricated element. Null until a theme name is entered.
const themeExport = useMemo(() => {
const name = themeName.trim();
if (!name) {
@@ -796,11 +586,8 @@ export function PlaygroundClient({defaultIsMobile}: PlaygroundClientProps) {
return () => cancelAnimationFrame(id);
}, [activeView]);
- // Dropdown items for "Themes" — derived from the registered playground
- // themes (PLAYGROUND_THEME_OPTIONS) so any installed @xds/theme-* package
- // shows up automatically. Selecting one prompts for confirmation (it discards
- // the current theme) before re-seeding the Theme editor (and thus the preview)
- // with that theme's values.
+ // "Themes" dropdown — every registered playground theme. Selecting one prompts
+ // for confirmation before re-seeding the Theme editor (and preview).
const themeMenuItems = useMemo(
() =>
PLAYGROUND_THEME_OPTIONS.map(option => ({
@@ -810,11 +597,8 @@ export function PlaygroundClient({defaultIsMobile}: PlaygroundClientProps) {
[],
);
- // Dropdown items for "Templates" — the published, ready templates from the
- // generated registry (the same source the /templates gallery renders), so any
- // new template shows up automatically. Selecting one prompts for confirmation
- // (it overwrites the editor) before loading its source (setCode drives Monaco,
- // the preview, and the URL hash).
+ // "Templates" dropdown — the published, ready templates from the generated
+ // registry. Selecting one prompts for confirmation before loading its source.
const templateMenuItems = useMemo(
() => [
{
@@ -852,8 +636,7 @@ export function PlaygroundClient({defaultIsMobile}: PlaygroundClientProps) {
wordWrap: 'on' as const,
padding: {top: 12},
accessibilitySupport: 'off' as const,
- // Hide scrollbars (wheel/keyboard scrolling still works) + the right-side
- // overview ruler, for a cleaner panel.
+ // Hide scrollbars and the overview ruler for a cleaner panel.
scrollbar: {
vertical: 'hidden' as const,
horizontal: 'hidden' as const,
@@ -1009,10 +792,10 @@ export function PlaygroundClient({defaultIsMobile}: PlaygroundClientProps) {
</XDSHStack>
</XDSHStack>
)}
- <div {...stylex.props(s.tabBody)}>
- {/* Code: Monaco stays mounted to preserve typedefs + editor state */}
- <div
- {...stylex.props(s.codePane, activeView !== 'code' && s.hidden)}>
+ {/* Both panes stay mounted (hidden when inactive) so Monaco's
+ typedefs and the theme editor's state survive tab switches. */}
+ <XDSVStack xstyle={s.tabBody}>
+ <XDSVStack xstyle={[s.pane, activeView !== 'code' && s.hidden]}>
<MonacoEditor
defaultLanguage="typescript"
value={code}
@@ -1023,24 +806,16 @@ export function PlaygroundClient({defaultIsMobile}: PlaygroundClientProps) {
onMount={handleMonacoMount}
options={editorOptions}
/>
- </div>
-
- {/* Theme: stays mounted (hidden when inactive) to preserve the
- editor's token/component state across tab switches — it only
- changes when the user edits it, not on navigation. */}
- <div
- {...stylex.props(
- s.themePane,
- activeView !== 'theme' && s.hidden,
- )}>
- <PlaygroundThemeEditor
+ </XDSVStack>
+ <XDSVStack xstyle={[s.pane, activeView !== 'theme' && s.hidden]}>
+ <ThemeEditor
key={selectedTheme}
mode={mode}
initialTheme={editorInitialTheme}
onThemeChange={postCustomTheme}
/>
- </div>
- </div>
+ </XDSVStack>
+ </XDSVStack>
</XDSVStack>
{!isMobile && (
@@ -1119,9 +894,13 @@ export function PlaygroundClient({defaultIsMobile}: PlaygroundClientProps) {
endContent={
<XDSHStack gap={4} vAlign="center">
{buildStatus !== 'idle' && (
- <div
- {...stylex.props(s.buildStatus)}
- style={{opacity: statusFading ? 0 : 1}}>
+ <XDSHStack
+ gap={2}
+ vAlign="center"
+ xstyle={[
+ s.buildStatus,
+ statusFading && s.buildStatusFaded,
+ ]}>
<XDSStatusDot
variant={BUILD_STATUS_META[buildStatus].variant}
label={BUILD_STATUS_META[buildStatus].label}
@@ -1141,7 +920,7 @@ export function PlaygroundClient({defaultIsMobile}: PlaygroundClientProps) {
onClick={handleRebuild}
/>
)}
- </div>
+ </XDSHStack>
)}
<XDSPopover
label="Share template"
diff --git a/apps/docsite/src/app/playground/PreviewStage.tsx b/apps/docsite/src/app/playground/PreviewStage.tsx
index 367a68efdf..f75014442f 100644
--- a/apps/docsite/src/app/playground/PreviewStage.tsx
+++ b/apps/docsite/src/app/playground/PreviewStage.tsx
@@ -3,20 +3,20 @@
/**
* @file PreviewStage.tsx
* @input viewport size, fullscreen flag, iframe ref
- * @output Responsive preview frame hosting the /playground-preview iframe
+ * @output Responsive preview frame hosting the /playground/preview iframe
* @position Playground right panel — preview surface.
*
* Keeps a SINGLE iframe element mounted across viewport + fullscreen changes
* (only the wrapper styles change) so the parent's postMessage channel to the
- * preview never resets. Desktop = fill; Phone = a fixed 375px-wide frame
- * (content reflows natively at mobile width, no scaling). Mirrors the Nest
- * craft editor's viewport behavior and dimensions.
+ * preview never resets. Desktop = fill; Phone = a fixed 402px-wide frame
+ * (content reflows natively at mobile width, no scaling).
*/
'use client';
import * as stylex from '@stylexjs/stylex';
import {XDSCard} from '@xds/core/Card';
+import {XDSCenter} from '@xds/core/Center';
import {XDSButton} from '@xds/core/Button';
import {Minimize2} from 'lucide-react';
@@ -30,9 +30,6 @@ const s = stylex.create({
area: {
flex: 1,
minHeight: 0,
- display: 'flex',
- justifyContent: 'center',
- alignItems: 'stretch',
overflow: 'hidden',
paddingInline: 'var(--spacing-4)',
paddingBlockEnd: 'var(--spacing-4)',
@@ -43,9 +40,6 @@ const s = stylex.create({
paddingBlockEnd: 0,
paddingBlockStart: 0,
},
- areaCenter: {
- alignItems: 'center',
- },
fullscreen: {
position: 'fixed',
inset: 0,
@@ -99,6 +93,14 @@ const s = stylex.create({
},
});
+// Runtime sizing — the preview frame is a fixed device size or fills its area.
+const dynamic = stylex.create({
+ size: (width: number | string, height: number | string) => ({
+ width,
+ height,
+ }),
+});
+
interface PreviewStageProps {
viewport: Viewport;
isFullscreen: boolean;
@@ -123,13 +125,13 @@ export function PreviewStage({
const height = isPhone ? PHONE_HEIGHT : '100%';
return (
- <div
- {...stylex.props(
+ <XDSCenter
+ axis={isPhone ? 'both' : 'horizontal'}
+ xstyle={[
s.area,
isFullBleed && !isFullscreen && s.areaFullBleed,
- isPhone && s.areaCenter,
isFullscreen && s.fullscreen,
- )}>
+ ]}>
{isFullscreen && (
<XDSCard padding={0} xstyle={s.exitButtonCard}>
<XDSButton
@@ -149,16 +151,16 @@ export function PreviewStage({
s.card,
(isFullscreen || isFullBleed) && s.cardFullscreen,
isFullBleed && !isFullscreen && s.cardFullBleed,
- ]}
- style={{width, height}}>
+ dynamic.size(width, height),
+ ]}>
<iframe
ref={iframeRef}
- src="/playground-preview"
+ src="/playground/preview"
sandbox="allow-scripts allow-same-origin"
title="Preview"
{...stylex.props(s.iframe, isInteractionDisabled && s.iframeInert)}
/>
</XDSCard>
- </div>
+ </XDSCenter>
);
}
diff --git a/apps/docsite/src/app/playground/themes/github-dark.json b/apps/docsite/src/app/playground/codeEditorThemes/github-dark.json
similarity index 100%
rename from apps/docsite/src/app/playground/themes/github-dark.json
rename to apps/docsite/src/app/playground/codeEditorThemes/github-dark.json
diff --git a/apps/docsite/src/app/playground/themes/github-light.json b/apps/docsite/src/app/playground/codeEditorThemes/github-light.json
similarity index 100%
rename from apps/docsite/src/app/playground/themes/github-light.json
rename to apps/docsite/src/app/playground/codeEditorThemes/github-light.json
diff --git a/apps/docsite/src/app/playground/defaultCode.ts b/apps/docsite/src/app/playground/defaultCode.ts
index 68f4b6c14e..b9366756e2 100644
--- a/apps/docsite/src/app/playground/defaultCode.ts
+++ b/apps/docsite/src/app/playground/defaultCode.ts
@@ -6,7 +6,7 @@
* @position Playground — the initial example users see and edit.
*
* A minimal, self-contained XDSCard example (header, body text, footer button)
- * that runs in the preview sandbox (see (preview)/playground-preview/runner.ts).
+ * that runs in the preview sandbox (see playground/preview/runner.ts).
* Kept as a string because the playground edits/compiles it as user code rather
* than importing it.
*/
@@ -34,7 +34,7 @@ export default function Example() {
content={
<XDSLayoutContent>
<XDSText type="body" color="secondary">
- Try out components in the code editor, open a ready-made templates,
+ Try out components in the code editor, open a ready-made template,
and build your own theme in the theme editor — all in one place.
</XDSText>
</XDSLayoutContent>
diff --git a/apps/docsite/src/app/playground/monacoSetup.ts b/apps/docsite/src/app/playground/monacoSetup.ts
new file mode 100644
index 0000000000..aebf59aff7
--- /dev/null
+++ b/apps/docsite/src/app/playground/monacoSetup.ts
@@ -0,0 +1,157 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file monacoSetup.ts
+ * @input The Monaco runtime instance passed to the editor's onMount
+ * @output Self-hosted loader config + TypeScript-service setup with XDS typedefs
+ * @position Playground Code editor — keeps Monaco wiring out of PlaygroundClient.
+ *
+ * Configures Monaco's TypeScript service with real XDS type definitions loaded
+ * from a pre-built JSON bundle (generated at build time), so the editor offers
+ * accurate autocomplete and diagnostics for @xds/core, React, StyleX, and icons.
+ */
+
+import {loader} from '@monaco-editor/react';
+import type * as MonacoTypes from 'monaco-editor';
+
+// Self-host Monaco from public/monaco/vs — corpnet blocks the default CDN.
+if (typeof window !== 'undefined') {
+ loader.config({paths: {vs: '/monaco/vs'}});
+}
+
+/** Monaco instance type — the full runtime object passed to onMount. */
+export type MonacoInstance = typeof MonacoTypes & {
+ languages: typeof MonacoTypes.languages & {
+ typescript: {
+ typescriptDefaults: {
+ setCompilerOptions: (options: Record<string, unknown>) => void;
+ setDiagnosticsOptions: (options: Record<string, unknown>) => void;
+ addExtraLib: (content: string, filePath: string) => void;
+ };
+ ScriptTarget: Record<string, number>;
+ ModuleKind: Record<string, number>;
+ JsxEmit: Record<string, number>;
+ ModuleResolutionKind: Record<string, number>;
+ };
+ };
+ editor: typeof MonacoTypes.editor & {
+ defineTheme: (name: string, data: Record<string, unknown>) => void;
+ };
+};
+
+/**
+ * Configure Monaco's TypeScript service with real XDS type definitions.
+ * Loads .d.ts files from a pre-built JSON bundle (generated at build time).
+ */
+export function configureMonaco(monaco: MonacoInstance) {
+ const ts = monaco.languages.typescript.typescriptDefaults;
+
+ ts.setCompilerOptions({
+ target: monaco.languages.typescript.ScriptTarget.ESNext,
+ module: monaco.languages.typescript.ModuleKind.ESNext,
+ jsx: monaco.languages.typescript.JsxEmit.ReactJSX,
+ esModuleInterop: true,
+ allowSyntheticDefaultImports: true,
+ moduleResolution: monaco.languages.typescript.ModuleResolutionKind.NodeJs,
+ allowJs: true,
+ strict: false,
+ });
+
+ ts.setDiagnosticsOptions({
+ noSemanticValidation: true,
+ noSyntaxValidation: false,
+ });
+
+ // Global declarations for React hooks (available without import in playground)
+ ts.addExtraLib(
+ `declare function useState<T>(init: T | (() => T)): [T, (v: T | ((prev: T) => T)) => void];
+ declare function useEffect(fn: () => void | (() => void), deps?: readonly unknown[]): void;
+ declare function useCallback<T extends Function>(fn: T, deps: readonly unknown[]): T;
+ declare function useMemo<T>(fn: () => T, deps: readonly unknown[]): T;
+ declare function useRef<T>(init: T): { current: T };
+ declare function useReducer<S, A>(reducer: (state: S, action: A) => S, init: S): [S, (action: A) => void];
+ declare function useContext<T>(ctx: unknown): T;`,
+ 'file:///globals.d.ts',
+ );
+
+ // Lucide icons wildcard stub so named imports don't show as errors.
+ ts.addExtraLib(
+ `declare module 'lucide-react' { const icons: Record<string, React.ComponentType<{size?: number | string; color?: string; strokeWidth?: number | string; className?: string}>>; export = icons; }`,
+ 'file:///node_modules/lucide-react/index.d.ts',
+ );
+
+ // Load real type definitions from the pre-built JSON bundle
+ fetch('/playground-types.json')
+ .then(r => r.json())
+ .then((packages: Record<string, Record<string, string>>) => {
+ const reactFiles = packages['react'] ?? {};
+ for (const [fileName, content] of Object.entries(reactFiles)) {
+ ts.addExtraLib(
+ content,
+ `file:///node_modules/@types/react/${fileName}`,
+ );
+ // Also register react/jsx-runtime as a resolvable module path
+ if (fileName === 'jsx-runtime.d.ts') {
+ ts.addExtraLib(
+ content,
+ 'file:///node_modules/react/jsx-runtime.d.ts',
+ );
+ }
+ }
+
+ const stylexFiles = packages['@stylexjs/stylex'] ?? {};
+ for (const [fileName, content] of Object.entries(stylexFiles)) {
+ ts.addExtraLib(
+ content,
+ `file:///node_modules/@stylexjs/stylex/${fileName}`,
+ );
+ }
+
+ // Heroicons ambient declarations, one per size/style variant
+ // ('@heroicons/react/{16,20,24}/{outline,solid}'), so those imports
+ // resolve once semantic validation turns on below.
+ const heroiconFiles = packages['@heroicons/react'] ?? {};
+ for (const [fileName, content] of Object.entries(heroiconFiles)) {
+ const variant = fileName.replace(/\.d\.ts$/, '');
+ ts.addExtraLib(
+ content,
+ `file:///node_modules/@heroicons/react/${variant}/index.d.ts`,
+ );
+ }
+
+ const xdsFiles = packages['@xds/core'] ?? {};
+ const submoduleReexports: string[] = [];
+
+ for (const [relPath, content] of Object.entries(xdsFiles)) {
+ ts.addExtraLib(
+ content,
+ `file:///node_modules/@xds/core/dist/${relPath}`,
+ );
+
+ if (relPath.endsWith('/index.d.ts')) {
+ const moduleName = relPath.replace('/index.d.ts', '');
+ ts.addExtraLib(
+ content,
+ `file:///node_modules/@xds/core/${moduleName}/index.d.ts`,
+ );
+ submoduleReexports.push(moduleName);
+ }
+ }
+
+ const barrelContent = submoduleReexports
+ .map(m => `export * from '@xds/core/${m}';`)
+ .join('\n');
+ ts.addExtraLib(
+ `declare module '@xds/core' {\n${barrelContent}\n}`,
+ 'file:///node_modules/@xds/core/index.d.ts',
+ );
+
+ ts.setDiagnosticsOptions({
+ noSemanticValidation: false,
+ noSyntaxValidation: false,
+ });
+ })
+ .catch(() => {
+ // Types unavailable — keep semantic validation disabled
+ });
+}
diff --git a/apps/docsite/src/app/playground/preview/ErrorBoundary.tsx b/apps/docsite/src/app/playground/preview/ErrorBoundary.tsx
new file mode 100644
index 0000000000..8483beee83
--- /dev/null
+++ b/apps/docsite/src/app/playground/preview/ErrorBoundary.tsx
@@ -0,0 +1,82 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file ErrorBoundary.tsx
+ * @input The rendered user component (children) + a reset key
+ * @output Catches render errors and shows a stark fallback instead of crashing
+ * @position Playground preview iframe — isolates user-code render failures.
+ */
+
+import React, {useState, type ErrorInfo, type ReactNode} from 'react';
+import * as stylex from '@stylexjs/stylex';
+
+// Render-error fallback (deliberately stark + monospace, theme-independent).
+const styles = stylex.create({
+ container: {
+ padding: 16,
+ fontFamily: 'ui-monospace, monospace',
+ fontSize: 13,
+ color: '#ef4444',
+ lineHeight: 1.5,
+ },
+ header: {fontWeight: 600, marginBottom: 8, cursor: 'pointer'},
+ message: {whiteSpace: 'pre-wrap', margin: 0},
+});
+
+export function ErrorDisplay({message}: {message: string}) {
+ const [expanded, setExpanded] = useState(false);
+ const preview = message.length > 120 ? message.slice(0, 120) + '…' : message;
+
+ return (
+ <div {...stylex.props(styles.container)}>
+ <div
+ {...stylex.props(styles.header)}
+ onClick={() => setExpanded(e => !e)}>
+ ⚠ Render Error {message.length > 120 && (expanded ? '▾' : '▸')}
+ </div>
+ <pre {...stylex.props(styles.message)}>
+ {expanded ? message : preview}
+ </pre>
+ </div>
+ );
+}
+
+interface ErrorBoundaryProps {
+ resetKey: unknown;
+ children: ReactNode;
+ onError: (error: Error) => void;
+}
+
+interface ErrorBoundaryState {
+ error: Error | null;
+}
+
+export class ErrorBoundary extends React.Component<
+ ErrorBoundaryProps,
+ ErrorBoundaryState
+> {
+ state: ErrorBoundaryState = {error: null};
+
+ static getDerivedStateFromError(error: Error): ErrorBoundaryState {
+ return {error};
+ }
+
+ componentDidCatch(error: Error, _info: ErrorInfo): void {
+ this.props.onError(error);
+ }
+
+ componentDidUpdate(prevProps: ErrorBoundaryProps): void {
+ if (prevProps.resetKey !== this.props.resetKey && this.state.error) {
+ this.setState({error: null});
+ }
+ }
+
+ render(): ReactNode {
+ if (this.state.error) {
+ return <ErrorDisplay message={this.state.error.message} />;
+ }
+ return this.props.children;
+ }
+}
diff --git a/apps/docsite/src/app/playground/preview/layout.tsx b/apps/docsite/src/app/playground/preview/layout.tsx
new file mode 100644
index 0000000000..6310fe57ce
--- /dev/null
+++ b/apps/docsite/src/app/playground/preview/layout.tsx
@@ -0,0 +1,17 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file layout.tsx
+ * @output The playground preview route, rendered bare (no docsite chrome).
+ * @position Playground preview iframe — loads the document reset.
+ *
+ * The preview renders inside an iframe, so it deliberately adds no nav/footer.
+ * previewReset.css gives the iframe document full height; the targeting-overlay
+ * styles live with their code (propertyEditor/targetingOverlay.css).
+ */
+
+import './previewReset.css';
+
+export default function PreviewLayout({children}: {children: React.ReactNode}) {
+ return children;
+}
diff --git a/apps/docsite/src/app/playground/preview/page.tsx b/apps/docsite/src/app/playground/preview/page.tsx
new file mode 100644
index 0000000000..be7f65ee84
--- /dev/null
+++ b/apps/docsite/src/app/playground/preview/page.tsx
@@ -0,0 +1,292 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+import React, {
+ useCallback,
+ useEffect,
+ useLayoutEffect,
+ useRef,
+ useState,
+} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {XDSTheme, defineTheme} from '@xds/core/theme';
+import type {ThemeMode, XDSDefinedTheme} from '@xds/core/theme';
+import {themeByValue, DEFAULT_PLAYGROUND_THEME} from '../previewThemes';
+import {useThemeMode} from '../../providers';
+import {ErrorBoundary, ErrorDisplay} from './ErrorBoundary';
+import {
+ createTargetingController,
+ refreshTargetLabels,
+ setActiveSiteMode,
+ setCleanSource,
+} from '../propertyEditor/targetingOverlay';
+import {runCode, setTypeScript} from './runner';
+import type * as TS from 'typescript';
+
+const FALLBACK_THEME =
+ themeByValue[DEFAULT_PLAYGROUND_THEME] ?? Object.values(themeByValue)[0];
+
+// useLayoutEffect warns during SSR; the preview measures real DOM only on the
+// client, so fall back to useEffect on the server.
+const useIsomorphicLayoutEffect =
+ typeof window !== 'undefined' ? useLayoutEffect : useEffect;
+
+type PreviewMessage =
+ | {type: 'preview-ping'}
+ | {type: 'preview-code'; code: string; source: string}
+ | {type: 'preview-clear'}
+ | {
+ type: 'preview-theme';
+ mode?: string;
+ theme?: string;
+ // A custom theme authored in the editor. Sent as raw token map +
+ // components (not a defineTheme result) so the payload stays reliably
+ // structured-clone-safe across postMessage; the iframe rebuilds it.
+ customTokens?: Record<string, string>;
+ customComponents?: unknown;
+ }
+ | {type: 'targeting-enable'}
+ | {type: 'targeting-disable'};
+
+const styles = stylex.create({
+ // The preview stage either fills the frame (full-page templates) or centers a
+ // small example.
+ stageFill: {
+ height: '100%',
+ minHeight: '100%',
+ display: 'block',
+ backgroundColor: 'var(--color-background-surface)',
+ },
+ stageCenter: {
+ minHeight: '100%',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ padding: 'var(--spacing-4, 16px)',
+ boxSizing: 'border-box',
+ backgroundColor: 'var(--color-background-surface)',
+ },
+ contentFill: {height: '100%', width: '100%'},
+});
+
+function isPreviewMessage(data: unknown): data is PreviewMessage {
+ return (
+ typeof data === 'object' &&
+ data !== null &&
+ 'type' in data &&
+ typeof (data as {type: unknown}).type === 'string'
+ );
+}
+
+export default function PreviewPage() {
+ const [Component, setComponent] = useState<React.ComponentType | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [themeMode, setThemeMode] = useState<ThemeMode>('system');
+ const [themeName, setThemeName] = useState(DEFAULT_PLAYGROUND_THEME);
+ // A custom theme authored in the playground theme editor. When set it takes
+ // precedence over the registered theme resolved from themeName.
+ const [customTheme, setCustomTheme] = useState<XDSDefinedTheme | null>(null);
+ const [resetKey, setResetKey] = useState(0);
+ const [tsReady, setTsReady] = useState(false);
+ // Whether the rendered output should fill the stage (full-page templates) vs
+ // be centered as a small example. Defaults to fill so templates are never
+ // shrunk; the layout effect downgrades small content to centered.
+ const [fill, setFill] = useState(true);
+ const readyRef = useRef(false);
+ const stageRef = useRef<HTMLDivElement>(null);
+ const contentRef = useRef<HTMLDivElement>(null);
+
+ // Load the TypeScript compiler from public/vendor — self-hosted because
+ // corpnet blocks external CDNs. The UMD sets window.ts in the browser
+ // (this iframe has no AMD loader, so there's no define() conflict).
+ useEffect(() => {
+ const script = document.createElement('script');
+ script.src = '/vendor/typescript.js';
+ script.onload = () => {
+ const w = window as unknown as {ts?: typeof TS};
+ if (w.ts) {
+ setTypeScript(w.ts);
+ setTsReady(true);
+ }
+ };
+ document.head.appendChild(script);
+ }, []);
+
+ const theme = customTheme ?? themeByValue[themeName] ?? FALLBACK_THEME;
+
+ const postToParent = useCallback((msg: Record<string, unknown>) => {
+ window.parent.postMessage(msg, '*');
+ }, []);
+
+ const targetingRef = useRef<ReturnType<
+ typeof createTargetingController
+ > | null>(null);
+ if (targetingRef.current == null && typeof window !== 'undefined') {
+ targetingRef.current = createTargetingController(postToParent);
+ }
+
+ const handleCode = useCallback(
+ (code: string) => {
+ const result = runCode(code);
+ if (result.Component) {
+ setComponent(() => result.Component);
+ setError(null);
+ // Intentionally do NOT clear the selection overlay here: a prop edit
+ // from the badge popover re-renders the component, and the popover
+ // must stay anchored to the (still-present) selection badge. The rAF
+ // tracker re-attaches to the same data-pg-id, and updateSelectionPosition
+ // hides the overlay on its own if the selected element disappears.
+ setFill(true);
+ setResetKey(k => k + 1);
+ postToParent({type: 'preview-rendered'});
+ } else {
+ setComponent(null);
+ setError(`[${result.phase}] ${result.error}`);
+ postToParent({
+ type: 'preview-error',
+ error: result.error,
+ phase: result.phase,
+ });
+ }
+ },
+ [postToParent],
+ );
+
+ const handleClear = useCallback(() => {
+ setComponent(null);
+ setError(null);
+ }, []);
+
+ const handleTheme = useCallback(
+ (msg: {
+ mode?: string;
+ theme?: string;
+ customTokens?: Record<string, string>;
+ customComponents?: unknown;
+ }) => {
+ if (
+ msg.mode === 'light' ||
+ msg.mode === 'dark' ||
+ msg.mode === 'system'
+ ) {
+ setThemeMode(msg.mode);
+ }
+ if (msg.customTokens) {
+ setCustomTheme(
+ defineTheme({
+ name: 'custom',
+ tokens: msg.customTokens,
+ components: msg.customComponents as XDSDefinedTheme['components'],
+ }),
+ );
+ } else {
+ // No custom tokens — fall back to the registered theme by key.
+ setCustomTheme(null);
+ if (msg.theme && msg.theme in themeByValue) {
+ setThemeName(msg.theme);
+ }
+ }
+ },
+ [],
+ );
+
+ useEffect(() => {
+ if (!tsReady) {
+ return;
+ }
+
+ function onMessage(event: MessageEvent) {
+ if (!isPreviewMessage(event.data)) {
+ return;
+ }
+
+ switch (event.data.type) {
+ case 'preview-ping':
+ postToParent({type: 'preview-ready'});
+ break;
+ case 'preview-code':
+ // Keep the clean source current for the badge popover, then refresh
+ // any live badges so an open popover re-parses against it.
+ setCleanSource(event.data.source ?? event.data.code);
+ refreshTargetLabels();
+ handleCode(event.data.code);
+ break;
+ case 'preview-clear':
+ handleClear();
+ break;
+ case 'preview-theme':
+ handleTheme(event.data);
+ break;
+ case 'targeting-enable':
+ targetingRef.current?.enable();
+ break;
+ case 'targeting-disable':
+ targetingRef.current?.disable();
+ break;
+ }
+ }
+
+ window.addEventListener('message', onMessage);
+
+ if (!readyRef.current) {
+ readyRef.current = true;
+ postToParent({type: 'preview-ready'});
+ }
+
+ return () => window.removeEventListener('message', onMessage);
+ }, [tsReady, postToParent, handleCode, handleClear, handleTheme]);
+
+ // After each successful render (measured in fill/block layout), decide
+ // whether the content is a small example that should be centered. Full-page
+ // templates (e.g. XDSAppShell at 100dvh) fill a dimension and stay as-is.
+ useIsomorphicLayoutEffect(() => {
+ const stage = stageRef.current;
+ const root = contentRef.current?.firstElementChild as HTMLElement | null;
+ if (!stage || !root) {
+ return;
+ }
+ const rect = root.getBoundingClientRect();
+ const fillsWidth = rect.width >= stage.clientWidth - 2;
+ const fillsHeight = rect.height >= stage.clientHeight - 2;
+ setFill(fillsWidth || fillsHeight);
+ }, [resetKey]);
+
+ const handleBoundaryError = useCallback(
+ (err: Error) => {
+ postToParent({
+ type: 'preview-error',
+ error: err.message,
+ phase: 'runtime',
+ });
+ },
+ [postToParent],
+ );
+
+ // Keep the overlay badges (rendered in their own roots, outside this React
+ // tree) on the site theme but matching the site's light/dark mode.
+ const {mode: siteMode} = useThemeMode();
+ useEffect(() => {
+ setActiveSiteMode(siteMode);
+ refreshTargetLabels();
+ }, [siteMode]);
+
+ // fill = full-page template (definite height so `height: 100%` resolves);
+ // otherwise center the small example.
+ return (
+ <XDSTheme theme={theme} mode={themeMode}>
+ <div
+ ref={stageRef}
+ {...stylex.props(fill ? styles.stageFill : styles.stageCenter)}>
+ {error && <ErrorDisplay message={error} />}
+ {Component && (
+ <div ref={contentRef} {...stylex.props(fill && styles.contentFill)}>
+ <ErrorBoundary resetKey={resetKey} onError={handleBoundaryError}>
+ <Component />
+ </ErrorBoundary>
+ </div>
+ )}
+ </div>
+ </XDSTheme>
+ );
+}
diff --git a/apps/docsite/src/app/playground/preview/previewReset.css b/apps/docsite/src/app/playground/preview/previewReset.css
new file mode 100644
index 0000000000..6a74849b45
--- /dev/null
+++ b/apps/docsite/src/app/playground/preview/previewReset.css
@@ -0,0 +1,13 @@
+/* Copyright (c) Meta Platforms, Inc. and affiliates. */
+
+/*
+ * Document reset for the preview iframe. Full-height html/body so user
+ * templates sized with height: 100% / 100dvh fill the frame. Imported by the
+ * preview route's layout.
+ */
+
+html,
+body {
+ height: 100%;
+ margin: 0;
+}
diff --git a/apps/docsite/src/app/(preview)/playground-preview/runner.ts b/apps/docsite/src/app/playground/preview/runner.ts
similarity index 89%
rename from apps/docsite/src/app/(preview)/playground-preview/runner.ts
rename to apps/docsite/src/app/playground/preview/runner.ts
index 6dbdda2bfe..d5e22136f7 100644
--- a/apps/docsite/src/app/(preview)/playground-preview/runner.ts
+++ b/apps/docsite/src/app/playground/preview/runner.ts
@@ -115,7 +115,11 @@ function buildGlobalScope(): Record<string, unknown> {
const vars: Record<string, unknown> = {};
for (const moduleExports of Object.values(scope)) {
for (const [name, value] of Object.entries(moduleExports)) {
- if (name !== 'default' && name !== '__esModule' && !RESERVED_GLOBALS.has(name)) {
+ if (
+ name !== 'default' &&
+ name !== '__esModule' &&
+ !RESERVED_GLOBALS.has(name)
+ ) {
vars[name] = value;
}
}
@@ -125,6 +129,16 @@ function buildGlobalScope(): Record<string, unknown> {
return vars;
}
+// The global scope and require resolver depend only on the static `scope`
+// import, so build them once and reuse across every run (evaluate() is on the
+// hot path — it runs on every debounced edit).
+let globalScopeCache: Record<string, unknown> | null = null;
+function getGlobalScope(): Record<string, unknown> {
+ return (globalScopeCache ??= buildGlobalScope());
+}
+
+const sharedRequire = makeRequire();
+
function compile(code: string): string {
if (ts == null) {
throw new Error(
@@ -158,7 +172,8 @@ function compile(code: string): string {
function findDeclaredIdentifiers(compiled: string): Set<string> {
const names = new Set<string>();
// Top-level declarations (function/class and simple const/let/var bindings).
- const declRe = /^(?:export\s+)?(?:const|let|var|function\*?|class)\s+([A-Za-z_$][\w$]*)/gm;
+ const declRe =
+ /^(?:export\s+)?(?:const|let|var|function\*?|class)\s+([A-Za-z_$][\w$]*)/gm;
let m: RegExpExecArray | null;
while ((m = declRe.exec(compiled)) !== null) {
names.add(m[1]);
@@ -169,21 +184,24 @@ function findDeclaredIdentifiers(compiled: string): Set<string> {
function evaluate(compiled: string): React.ComponentType {
const exportsObj: Record<string, unknown> = {};
const moduleObj = {exports: exportsObj};
- const requireFn = makeRequire();
- const globals = buildGlobalScope();
+ const globals = getGlobalScope();
// Don't inject globals the user already declares — a parameter and a
// top-level `const`/`function`/`class` of the same name can't coexist.
const declared = findDeclaredIdentifiers(compiled);
const globalNames = Object.keys(globals).filter(
- name => !declared.has(name) && name !== 'module' && name !== 'exports' && name !== 'require',
+ name =>
+ !declared.has(name) &&
+ name !== 'module' &&
+ name !== 'exports' &&
+ name !== 'require',
);
const keys = ['module', 'exports', 'require', ...globalNames];
const values = [
moduleObj,
exportsObj,
- requireFn,
+ sharedRequire,
...globalNames.map(name => globals[name]),
];
diff --git a/apps/docsite/src/app/playground/playgroundThemes.ts b/apps/docsite/src/app/playground/previewThemes.ts
similarity index 93%
rename from apps/docsite/src/app/playground/playgroundThemes.ts
rename to apps/docsite/src/app/playground/previewThemes.ts
index e816309254..d61298d498 100644
--- a/apps/docsite/src/app/playground/playgroundThemes.ts
+++ b/apps/docsite/src/app/playground/previewThemes.ts
@@ -1,7 +1,7 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
/**
- * @file playgroundThemes.ts
+ * @file previewThemes.ts
* @input generated theme registry + package registry
* @output Selectable theme options + value→theme lookup for the playground
* @position Playground — single source of truth for selectable themes.
@@ -15,7 +15,7 @@ import type {XDSDefinedTheme} from '@xds/core/theme';
import {themeObjectsFull} from '../../generated/themeRegistry';
import {packages} from '../../generated/packageRegistry';
-export interface PlaygroundTheme {
+interface PlaygroundTheme {
/** Short, stable key used as the selector value + postMessage payload. */
value: string;
/** Human-readable label shown in the selector. */
@@ -45,9 +45,7 @@ function toLabel(packageName: string, shortName: string): string {
return base.charAt(0).toUpperCase() + base.slice(1);
}
-export const PLAYGROUND_THEMES: PlaygroundTheme[] = Object.entries(
- themeObjectsFull,
-)
+const PLAYGROUND_THEMES: PlaygroundTheme[] = Object.entries(themeObjectsFull)
.map(([packageName, theme]) => {
const value = toShortName(packageName);
return {value, label: toLabel(packageName, value), theme};
diff --git a/apps/docsite/src/app/playground/PropertyPanel.tsx b/apps/docsite/src/app/playground/propertyEditor/PropertyEditor.tsx
similarity index 93%
rename from apps/docsite/src/app/playground/PropertyPanel.tsx
rename to apps/docsite/src/app/playground/propertyEditor/PropertyEditor.tsx
index 72ca556799..848a7cf8f6 100644
--- a/apps/docsite/src/app/playground/PropertyPanel.tsx
+++ b/apps/docsite/src/app/playground/propertyEditor/PropertyEditor.tsx
@@ -1,14 +1,14 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
/**
- * @file PropertyPanel.tsx
+ * @file PropertyEditor.tsx
* @input Current editor code + the selected instance + onCodeChange callback
* @output Literal-bound prop knobs for one component instance + "Apply" footer
* @position Playground in-preview "Properties" popover (anchored to the selection badge).
*
* Parses the code and renders the docs-style props table for the externally
* selected component instance. Changing a knob performs a targeted source-range
- * edit (see babelParser) against a local draft; edits are buffered and only
+ * edit (see componentInstances) against a local draft; edits are buffered and only
* written back through onCodeChange when the user clicks "Apply" (pinned at the
* bottom of the popover, outside the scroll area). Only literal props (boolean /
* enum / string / number) are editable; enum controls preserve typed option
@@ -28,14 +28,15 @@ import {XDSTextInput} from '@xds/core/TextInput';
import {XDSNumberInput} from '@xds/core/NumberInput';
import {XDSEmptyState} from '@xds/core/EmptyState';
import {XDSList, XDSListItem} from '@xds/core/List';
+import {XDSCenter} from '@xds/core/Center';
import {XDSButton} from '@xds/core/Button';
import {
coerceDefault,
coerceEnumOption,
parsePropType,
type PropControlDescriptor,
-} from '../../components/component-detail/parsePropType';
-import type {PropDoc} from '../../generated/componentRegistry';
+} from '../../../components/component-detail/parsePropType';
+import type {PropDoc} from '../../../generated/componentRegistry';
import {
analyzeCode,
formatAttr,
@@ -43,8 +44,8 @@ import {
setAttribute,
type AttrInfo,
type InstanceInfo,
-} from './babelParser';
-import {getComponentByModule} from './usedComponents';
+} from './componentInstances';
+import {getComponentByModule} from './componentLookup';
const NUMERIC_RE = /^-?\d+(\.\d+)?$/;
@@ -62,9 +63,6 @@ const s = stylex.create({
},
emptyWrap: {
flex: 1,
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
padding: 'var(--spacing-6)',
},
});
@@ -81,7 +79,7 @@ function isEditable(control: PropControlDescriptor, attr?: AttrInfo): boolean {
);
}
-// Prop types that have no inline control in the popover panel and so are
+// Prop types that have no inline control in the popover and so are
// hidden entirely (ReactNode parses to a string control but isn't meaningfully
// editable here; StyleXStyles/AriaRole have no control at all).
const UNSUPPORTED_PROP_TYPES = new Set([
@@ -90,7 +88,7 @@ const UNSUPPORTED_PROP_TYPES = new Set([
'AriaRole',
]);
-/** Whether a prop can be edited through the panel (and should be shown). */
+/** Whether a prop can be edited through the editor (and should be shown). */
function isSupportedProp(prop: PropDoc): boolean {
if (UNSUPPORTED_PROP_TYPES.has(prop.type.trim())) {
return false;
@@ -239,7 +237,7 @@ interface ExternalSelection {
instanceIndex: number;
}
-interface PropertyPanelProps {
+interface PropertyEditorProps {
code: string;
onCodeChange: (code: string) => void;
/** The component instance to edit (chosen via the in-preview selection). */
@@ -248,12 +246,12 @@ interface PropertyPanelProps {
onApplied?: () => void;
}
-export function PropertyPanel({
+export function PropertyEditor({
code,
onCodeChange,
externalSelection,
onApplied,
-}: PropertyPanelProps) {
+}: PropertyEditorProps) {
const {component: selected, instanceIndex} = externalSelection;
const lastInstances = useRef<InstanceInfo[]>([]);
@@ -290,13 +288,13 @@ export function PropertyPanel({
if (instances.length === 0) {
return (
- <div {...stylex.props(s.emptyWrap)}>
+ <XDSCenter xstyle={s.emptyWrap}>
<XDSEmptyState
title="No components detected"
description="Add a component in the Code tab to view properties."
isCompact
/>
- </div>
+ </XDSCenter>
);
}
diff --git a/apps/docsite/src/app/playground/babelParser.ts b/apps/docsite/src/app/playground/propertyEditor/componentInstances.ts
similarity index 97%
rename from apps/docsite/src/app/playground/babelParser.ts
rename to apps/docsite/src/app/playground/propertyEditor/componentInstances.ts
index 7cc3063e79..d356aacfb7 100644
--- a/apps/docsite/src/app/playground/babelParser.ts
+++ b/apps/docsite/src/app/playground/propertyEditor/componentInstances.ts
@@ -1,10 +1,10 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
/**
- * @file babelParser.ts
+ * @file componentInstances.ts
* @input Playground source code (TSX string)
* @output Detected XDS component instances + targeted source-range editors
- * @position Playground Property tab — binds interactive knobs to real code.
+ * @position Playground — backs the Properties popover knobs and preview targeting.
*
* Uses @babel/parser (bundled, browser-safe — NOT a CDN) to parse the code and
* walk the AST for `<XDS*>` JSX opening elements. Each attribute's character
@@ -19,7 +19,7 @@
import {parse} from '@babel/parser';
/** Literal value kinds we can round-trip through a knob. */
-export type AttrValueKind =
+type AttrValueKind =
| 'boolean' // boolean shorthand or {true}/{false}
| 'string' // "..." or {'...'}
| 'number' // {123}
@@ -235,8 +235,8 @@ export function setAttribute(
/**
* Insert a `data-pg-id="Component#index"` marker on every `<XDS*>` element so
* the preview can map a selected component/instance back to its DOM node. The
- * index is per-component-type in source order, matching the Property tab's
- * instance picker. Returns the original code unchanged on a parse error.
+ * index is per-component-type in source order, matching the Properties
+ * popover's instance picker. Returns the original code unchanged on a parse error.
*
* Markers are only applied to the copy SENT to the preview — never to the code
* the user sees, edits, or shares.
diff --git a/apps/docsite/src/app/playground/usedComponents.ts b/apps/docsite/src/app/playground/propertyEditor/componentLookup.ts
similarity index 91%
rename from apps/docsite/src/app/playground/usedComponents.ts
rename to apps/docsite/src/app/playground/propertyEditor/componentLookup.ts
index 0a914a7475..9ab37280ab 100644
--- a/apps/docsite/src/app/playground/usedComponents.ts
+++ b/apps/docsite/src/app/playground/propertyEditor/componentLookup.ts
@@ -1,7 +1,7 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
/**
- * @file usedComponents.ts
+ * @file componentLookup.ts
* @input Generated component registry
* @output Module-name → ComponentEntry lookup
* @position Playground Properties popover support.
@@ -10,7 +10,7 @@
import {
components,
type ComponentEntry,
-} from '../../generated/componentRegistry';
+} from '../../../generated/componentRegistry';
const byModuleName: Map<string, ComponentEntry> = (() => {
const map = new Map<string, ComponentEntry>();
diff --git a/apps/docsite/src/app/playground/propertyEditor/targetingOverlay.css b/apps/docsite/src/app/playground/propertyEditor/targetingOverlay.css
new file mode 100644
index 0000000000..c02e894bf8
--- /dev/null
+++ b/apps/docsite/src/app/playground/propertyEditor/targetingOverlay.css
@@ -0,0 +1,78 @@
+/* Copyright (c) Meta Platforms, Inc. and affiliates. */
+
+/*
+ * Styles for the targeting/selection overlay built by targetingOverlay.tsx.
+ * Global (not a CSS module) because these class names are assigned to DOM nodes
+ * created imperatively, and because the rules rely on descendant/universal
+ * selectors that StyleX can't express. Imported by targetingOverlay.tsx, so it
+ * only loads on the preview route.
+ */
+
+.pg-targeting,
+.pg-targeting * {
+ cursor: crosshair !important;
+}
+
+.pg-target-overlay {
+ position: fixed;
+ pointer-events: none;
+ z-index: 999999;
+ border: 2px solid var(--color-border-focus, #1877f2);
+ border-radius: var(--radius-element, 6px);
+ background: rgba(24, 119, 242, 0.06);
+ transition:
+ top 80ms ease-out,
+ left 80ms ease-out,
+ width 80ms ease-out,
+ height 80ms ease-out;
+ display: none;
+}
+.pg-target-overlay[data-visible='true'] {
+ display: block;
+}
+
+.pg-target-label {
+ position: absolute;
+ bottom: 100%;
+ left: -2px;
+ margin-bottom: var(--spacing-1, 4px);
+ padding: var(--spacing-0-5, 2px) var(--spacing-3, 12px);
+ font: 500 11px/16px ui-sans-serif, system-ui, sans-serif;
+ background: var(--color-border-focus, #1877f2);
+ border-radius: var(--radius-corner, 4px);
+ white-space: nowrap;
+ user-select: none;
+ pointer-events: auto;
+}
+.pg-target-label-bottom {
+ top: 100%;
+ bottom: auto;
+ margin-top: 4px;
+ margin-bottom: 0;
+}
+
+.pg-target-selection {
+ position: fixed;
+ pointer-events: none;
+ z-index: 999998;
+ border: 2px solid var(--color-border-focus, #1877f2);
+ border-radius: var(--radius-element, 6px);
+ background: rgba(24, 119, 242, 0.06);
+ display: none;
+}
+.pg-target-selection[data-visible='true'] {
+ display: block;
+}
+
+.pg-target-selection .pg-target-label {
+ position: absolute;
+ bottom: 100%;
+ left: -2px;
+ margin-bottom: 4px;
+}
+.pg-target-selection .pg-target-label-bottom {
+ top: 100%;
+ bottom: auto;
+ margin-top: 4px;
+ margin-bottom: 0;
+}
diff --git a/apps/docsite/src/app/(preview)/playground-preview/page.tsx b/apps/docsite/src/app/playground/propertyEditor/targetingOverlay.tsx
similarity index 51%
rename from apps/docsite/src/app/(preview)/playground-preview/page.tsx
rename to apps/docsite/src/app/playground/propertyEditor/targetingOverlay.tsx
index 2cdc3d9206..0d9e026fb9 100644
--- a/apps/docsite/src/app/(preview)/playground-preview/page.tsx
+++ b/apps/docsite/src/app/playground/propertyEditor/targetingOverlay.tsx
@@ -2,130 +2,40 @@
'use client';
-import React, {
- useCallback,
- useEffect,
- useLayoutEffect,
- useRef,
- useState,
- type CSSProperties,
- type ErrorInfo,
- type ReactNode,
-} from 'react';
+/**
+ * @file targetingOverlay.tsx
+ * @input Pointer events inside the preview iframe + the current clean source
+ * @output Hover/selection overlays, the selection badge, and the Properties popover
+ * @position Playground preview iframe — the element-targeting half of property editing.
+ *
+ * Runs inside the preview iframe. The hover/selection overlays and their labels
+ * are vanilla DOM (created imperatively and positioned every animation frame for
+ * performance); each label hosts a React root rendering the selection badge,
+ * whose popover embeds the PropertyEditor. The preview page drives this via
+ * createTargetingController() and the setActiveSiteMode/setCleanSource setters.
+ */
+
+import {useState} from 'react';
import {createRoot, type Root} from 'react-dom/client';
import * as stylex from '@stylexjs/stylex';
+import './targetingOverlay.css';
import {Settings, X} from 'lucide-react';
import {XDSHStack} from '@xds/core/Layout';
import {XDSText} from '@xds/core/Text';
import {XDSButton} from '@xds/core/Button';
import {XDSPopover} from '@xds/core/Popover';
-import {XDSTheme, XDSMediaTheme, defineTheme} from '@xds/core/theme';
-import type {ThemeMode, XDSDefinedTheme} from '@xds/core/theme';
-import {
- themeByValue,
- DEFAULT_PLAYGROUND_THEME,
-} from '../../playground/playgroundThemes';
+import {XDSTheme, XDSMediaTheme} from '@xds/core/theme';
+import type {ThemeMode} from '@xds/core/theme';
import {astryxTheme} from '../../../themes/astryx';
-import {useThemeMode} from '../../providers';
-import {PropertyPanel} from '../../playground/PropertyPanel';
-import {runCode, setTypeScript} from './runner';
-import type * as TS from 'typescript';
-
-const FALLBACK_THEME =
- themeByValue[DEFAULT_PLAYGROUND_THEME] ?? Object.values(themeByValue)[0];
-
-// useLayoutEffect warns during SSR; the preview measures real DOM only on the
-// client, so fall back to useEffect on the server.
-const useIsomorphicLayoutEffect =
- typeof window !== 'undefined' ? useLayoutEffect : useEffect;
-
-interface ErrorBoundaryProps {
- resetKey: unknown;
- children: ReactNode;
- onError: (error: Error) => void;
-}
-
-interface ErrorBoundaryState {
- error: Error | null;
-}
-
-class ErrorBoundary extends React.Component<
- ErrorBoundaryProps,
- ErrorBoundaryState
-> {
- state: ErrorBoundaryState = {error: null};
-
- static getDerivedStateFromError(error: Error): ErrorBoundaryState {
- return {error};
- }
-
- componentDidCatch(error: Error, _info: ErrorInfo): void {
- this.props.onError(error);
- }
-
- componentDidUpdate(prevProps: ErrorBoundaryProps): void {
- if (prevProps.resetKey !== this.props.resetKey && this.state.error) {
- this.setState({error: null});
- }
- }
-
- render(): ReactNode {
- if (this.state.error) {
- return <ErrorDisplay message={this.state.error.message} />;
- }
- return this.props.children;
- }
-}
-
-function ErrorDisplay({message}: {message: string}) {
- const [expanded, setExpanded] = useState(false);
- const preview = message.length > 120 ? message.slice(0, 120) + '…' : message;
+import {PropertyEditor} from './PropertyEditor';
- return (
- <div
- style={{
- padding: 16,
- fontFamily: 'ui-monospace, monospace',
- fontSize: 13,
- color: '#ef4444',
- lineHeight: 1.5,
- }}>
- <div
- style={{fontWeight: 600, marginBottom: 8, cursor: 'pointer'}}
- onClick={() => setExpanded(e => !e)}>
- ⚠ Render Error {message.length > 120 && (expanded ? '▾' : '▸')}
- </div>
- <pre style={{whiteSpace: 'pre-wrap', margin: 0}}>
- {expanded ? message : preview}
- </pre>
- </div>
- );
-}
-
-type PreviewMessage =
- | {type: 'preview-ping'}
- | {type: 'preview-code'; code: string; source: string}
- | {type: 'preview-clear'}
- | {
- type: 'preview-theme';
- mode?: string;
- theme?: string;
- // A custom theme authored in the editor. Sent as raw token map +
- // components (not a defineTheme result) so the payload stays reliably
- // structured-clone-safe across postMessage; the iframe rebuilds it.
- customTokens?: Record<string, string>;
- customComponents?: unknown;
- }
- | {type: 'targeting-enable'}
- | {type: 'targeting-disable'};
-
-// Blue label for selected instance with a popover for its properties
const styles = stylex.create({
badge: {minHeight: 32},
badgeActions: {marginRight: -10},
popover: {paddingBlock: 0, paddingInline: 0},
});
+// Blue label for a selected instance with a popover for its properties.
function TargetLabel({
name,
isInteractive,
@@ -185,7 +95,7 @@ function TargetLabel({
onOpenChange={setIsOpen}
xstyle={styles.popover}
content={
- <PropertyPanel
+ <PropertyEditor
code={code}
onCodeChange={onCodeChange}
externalSelection={{component, instanceIndex}}
@@ -208,6 +118,16 @@ let activeSiteMode: ThemeMode = 'light';
let cleanSource = '';
+/** The site color mode the badges render in (set by the preview page). */
+export function setActiveSiteMode(mode: ThemeMode) {
+ activeSiteMode = mode;
+}
+
+/** The un-annotated source the popover's PropertyEditor edits against. */
+export function setCleanSource(source: string) {
+ cleanSource = source;
+}
+
function postEditToParent(code: string) {
window.parent.postMessage({type: 'preview-edit-code', code}, '*');
}
@@ -252,7 +172,8 @@ function setTargetLabelText(label: HTMLDivElement, value: string) {
renderTargetLabel(label);
}
-function refreshTargetLabels() {
+/** Re-render every live badge (e.g. after the site mode or source changes). */
+export function refreshTargetLabels() {
for (const label of activeLabels) {
renderTargetLabel(label);
}
@@ -301,7 +222,7 @@ function updateSelectionPosition() {
overlay.dataset.visible = 'true';
// Carry the full id (Component#index) so the selection badge's popover can
- // scope its PropertyPanel to this exact instance. Re-render only when the
+ // scope its PropertyEditor to this exact instance. Re-render only when the
// name or id actually changes (this runs every animation frame).
const sep = id.lastIndexOf('#');
const name = sep >= 0 ? id.slice(0, sep) : id;
@@ -351,7 +272,7 @@ function clearSelectionOverlay() {
* intercepts pointer events to highlight hovered XDS components and report
* clicks back to the parent frame.
*/
-function createTargetingController(
+export function createTargetingController(
postToParent: (msg: Record<string, unknown>) => void,
) {
let enabled = false;
@@ -532,242 +453,3 @@ function createTargetingController(
return {enable, disable, clearSelection};
}
-
-function isPreviewMessage(data: unknown): data is PreviewMessage {
- return (
- typeof data === 'object' &&
- data !== null &&
- 'type' in data &&
- typeof (data as {type: unknown}).type === 'string'
- );
-}
-
-export default function PreviewPage() {
- const [Component, setComponent] = useState<React.ComponentType | null>(null);
- const [error, setError] = useState<string | null>(null);
- const [themeMode, setThemeMode] = useState<ThemeMode>('system');
- const [themeName, setThemeName] = useState(DEFAULT_PLAYGROUND_THEME);
- // A custom theme authored in the playground theme editor. When set it takes
- // precedence over the registered theme resolved from themeName.
- const [customTheme, setCustomTheme] = useState<XDSDefinedTheme | null>(null);
- const [resetKey, setResetKey] = useState(0);
- const [tsReady, setTsReady] = useState(false);
- // Whether the rendered output should fill the stage (full-page templates) vs
- // be centered as a small example. Defaults to fill so templates are never
- // shrunk; the layout effect downgrades small content to centered.
- const [fill, setFill] = useState(true);
- const readyRef = useRef(false);
- const stageRef = useRef<HTMLDivElement>(null);
- const contentRef = useRef<HTMLDivElement>(null);
-
- // Load the TypeScript compiler from public/vendor — self-hosted because
- // corpnet blocks external CDNs. The UMD sets window.ts in the browser
- // (this iframe has no AMD loader, so there's no define() conflict).
- useEffect(() => {
- const script = document.createElement('script');
- script.src = '/vendor/typescript.js';
- script.onload = () => {
- const w = window as unknown as {ts?: typeof TS};
- if (w.ts) {
- setTypeScript(w.ts);
- setTsReady(true);
- }
- };
- document.head.appendChild(script);
- }, []);
-
- const theme = customTheme ?? themeByValue[themeName] ?? FALLBACK_THEME;
-
- const postToParent = useCallback((msg: Record<string, unknown>) => {
- window.parent.postMessage(msg, '*');
- }, []);
-
- const targetingRef = useRef<ReturnType<
- typeof createTargetingController
- > | null>(null);
- if (targetingRef.current == null && typeof window !== 'undefined') {
- targetingRef.current = createTargetingController(postToParent);
- }
-
- const handleCode = useCallback(
- (code: string) => {
- const result = runCode(code);
- if (result.Component) {
- setComponent(() => result.Component);
- setError(null);
- // Intentionally do NOT clear the selection overlay here: a prop edit
- // from the badge popover re-renders the component, and the popover
- // must stay anchored to the (still-present) selection badge. The rAF
- // tracker re-attaches to the same data-pg-id, and updateSelectionPosition
- // hides the overlay on its own if the selected element disappears.
- setFill(true);
- setResetKey(k => k + 1);
- postToParent({type: 'preview-rendered'});
- } else {
- setComponent(null);
- setError(`[${result.phase}] ${result.error}`);
- postToParent({
- type: 'preview-error',
- error: result.error,
- phase: result.phase,
- });
- }
- },
- [postToParent],
- );
-
- const handleClear = useCallback(() => {
- setComponent(null);
- setError(null);
- }, []);
-
- const handleTheme = useCallback(
- (msg: {
- mode?: string;
- theme?: string;
- customTokens?: Record<string, string>;
- customComponents?: unknown;
- }) => {
- if (
- msg.mode === 'light' ||
- msg.mode === 'dark' ||
- msg.mode === 'system'
- ) {
- setThemeMode(msg.mode);
- }
- if (msg.customTokens) {
- setCustomTheme(
- defineTheme({
- name: 'custom',
- tokens: msg.customTokens,
- components: msg.customComponents as XDSDefinedTheme['components'],
- }),
- );
- } else {
- // No custom tokens — fall back to the registered theme by key.
- setCustomTheme(null);
- if (msg.theme && msg.theme in themeByValue) {
- setThemeName(msg.theme);
- }
- }
- },
- [],
- );
-
- useEffect(() => {
- if (!tsReady) {
- return;
- }
-
- function onMessage(event: MessageEvent) {
- if (!isPreviewMessage(event.data)) {
- return;
- }
-
- switch (event.data.type) {
- case 'preview-ping':
- postToParent({type: 'preview-ready'});
- break;
- case 'preview-code':
- // Keep the clean source current for the badge popover, then refresh
- // any live badges so an open popover re-parses against it.
- cleanSource = event.data.source ?? event.data.code;
- refreshTargetLabels();
- handleCode(event.data.code);
- break;
- case 'preview-clear':
- handleClear();
- break;
- case 'preview-theme':
- handleTheme(event.data);
- break;
- case 'targeting-enable':
- targetingRef.current?.enable();
- break;
- case 'targeting-disable':
- targetingRef.current?.disable();
- break;
- }
- }
-
- window.addEventListener('message', onMessage);
-
- if (!readyRef.current) {
- readyRef.current = true;
- postToParent({type: 'preview-ready'});
- }
-
- return () => window.removeEventListener('message', onMessage);
- }, [tsReady, postToParent, handleCode, handleClear, handleTheme]);
-
- // After each successful render (measured in fill/block layout), decide
- // whether the content is a small example that should be centered. Full-page
- // templates (e.g. XDSAppShell at 100dvh) fill a dimension and stay as-is.
- useIsomorphicLayoutEffect(() => {
- const stage = stageRef.current;
- const root = contentRef.current?.firstElementChild as HTMLElement | null;
- if (!stage || !root) {
- return;
- }
- const rect = root.getBoundingClientRect();
- const fillsWidth = rect.width >= stage.clientWidth - 2;
- const fillsHeight = rect.height >= stage.clientHeight - 2;
- setFill(fillsWidth || fillsHeight);
- }, [resetKey]);
-
- const handleBoundaryError = useCallback(
- (err: Error) => {
- postToParent({
- type: 'preview-error',
- error: err.message,
- phase: 'runtime',
- });
- },
- [postToParent],
- );
-
- // Keep the overlay badges (rendered in their own roots, outside this React
- // tree) on the site theme but matching the site's light/dark mode.
- const {mode: siteMode} = useThemeMode();
- useEffect(() => {
- activeSiteMode = siteMode;
- refreshTargetLabels();
- }, [siteMode]);
-
- const stageStyle: CSSProperties = fill
- ? {
- // Definite height so templates sized with `height: 100%` resolve.
- height: '100%',
- minHeight: '100%',
- display: 'block',
- backgroundColor: 'var(--color-background-surface)',
- }
- : {
- minHeight: '100%',
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
- padding: 'var(--spacing-4, 16px)',
- boxSizing: 'border-box',
- backgroundColor: 'var(--color-background-surface)',
- };
-
- const contentStyle: CSSProperties = fill
- ? {height: '100%', width: '100%'}
- : {};
-
- return (
- <XDSTheme theme={theme} mode={themeMode}>
- <div ref={stageRef} style={stageStyle}>
- {error && <ErrorDisplay message={error} />}
- {Component && (
- <div ref={contentRef} style={contentStyle}>
- <ErrorBoundary resetKey={resetKey} onError={handleBoundaryError}>
- <Component />
- </ErrorBoundary>
- </div>
- )}
- </div>
- </XDSTheme>
- );
-}
diff --git a/apps/docsite/src/app/playground/themeEditor/BaseStylesPanel.tsx b/apps/docsite/src/app/playground/themeEditor/BaseStylesPanel.tsx
new file mode 100644
index 0000000000..cf4d465804
--- /dev/null
+++ b/apps/docsite/src/app/playground/themeEditor/BaseStylesPanel.tsx
@@ -0,0 +1,584 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+import type {ReactNode} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {XDSText} from '@xds/core/Text';
+import {XDSVStack, XDSHStack} from '@xds/core/Stack';
+import {XDSGrid} from '@xds/core/Grid';
+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%'},
+ // 4px below the accent header, on top of the section's own gap.
+ headerSpace: {marginBottom: 'var(--spacing-1)'},
+});
+
+interface ScaleOption {
+ label: string;
+ value: string;
+}
+
+interface ScaleControlProps {
+ /** Visible section label (e.g. "Corner Radius"). */
+ label: string;
+ /** Info-tooltip text describing the scale formula. */
+ tooltip: string;
+ /** Accessible base name; the toggle group adds " preset". */
+ controlLabel: string;
+ /** Preset buttons (label + value). */
+ options: ScaleOption[];
+ /** Selected preset value, or null when the theme doesn't match a preset. */
+ toggleValue: string | null;
+ onToggle: (value: string) => void;
+ numberValue: number | null;
+ onNumber: (value: number) => void;
+ min: number;
+ max: number;
+ step: number;
+ units: string;
+}
+
+/**
+ * A label + info tooltip over a preset toggle group and a free-entry number
+ * input — the shared shape of the type-size, radius, spacing, element-size, and
+ * duration controls.
+ */
+function ScaleControl({
+ label,
+ tooltip,
+ controlLabel,
+ options,
+ toggleValue,
+ onToggle,
+ numberValue,
+ onNumber,
+ min,
+ max,
+ step,
+ units,
+}: ScaleControlProps) {
+ return (
+ <XDSVStack gap={1}>
+ <XDSHStack gap={1} vAlign="center">
+ <XDSText type="label" color="secondary">
+ {label}
+ </XDSText>
+ <XDSTooltip content={tooltip}>
+ <XDSIcon icon="info" size="sm" color="secondary" />
+ </XDSTooltip>
+ </XDSHStack>
+ <XDSHStack gap={2} vAlign="center" justify="between">
+ <XDSToggleButtonGroup
+ label={`${controlLabel} preset`}
+ type="single"
+ size="sm"
+ value={toggleValue}
+ onChange={(v: string | null) => {
+ if (v != null) {
+ onToggle(v);
+ }
+ }}>
+ {options.map(o => (
+ <XDSToggleButton key={o.value} label={o.label} value={o.value} />
+ ))}
+ </XDSToggleButtonGroup>
+ <XDSNumberInput
+ label={controlLabel}
+ isLabelHidden
+ value={numberValue}
+ placeholder="—"
+ onChange={onNumber}
+ min={min}
+ max={max}
+ step={step}
+ units={units}
+ size="sm"
+ />
+ </XDSHStack>
+ </XDSVStack>
+ );
+}
+
+/** Label-over-field pairing used by the typography selectors. */
+function LabeledField({label, children}: {label: string; children: ReactNode}) {
+ return (
+ <XDSVStack gap={1}>
+ <XDSText type="label" color="secondary">
+ {label}
+ </XDSText>
+ {children}
+ </XDSVStack>
+ );
+}
+
+interface BaseStylesPanelProps {
+ 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;
+}
+
+export function BaseStylesPanel({
+ tokens,
+ mode,
+ typeScaleBase,
+ typeScaleRatio,
+ radiusBase,
+ spacingBase,
+ sizeBase,
+ durationStep,
+ activePreset,
+ autoPickColors,
+ onTokenChange,
+ onApplyTypeScale,
+ onApplyRadiusScale,
+ onApplySpacingScale,
+ onApplySizeScale,
+ onApplyDurationScale,
+ onApplyUnifiedPreset,
+ onSetAutoPickColors,
+ onExpandColorScale,
+}: BaseStylesPanelProps) {
+ // 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 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 — then the match is null and the control renders
+ // "unset" 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 */}
+ <XDSVStack gap={3}>
+ <XDSHStack
+ vAlign="center"
+ justify="between"
+ xstyle={styles.headerSpace}>
+ <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 */}
+ <XDSVStack gap={3}>
+ <XDSText type="label" color="secondary">
+ Preset
+ </XDSText>
+ <XDSGrid columns={4} gap={2}>
+ {Object.keys(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)';
+ const title = key.charAt(0).toUpperCase() + key.slice(1);
+ return (
+ <XDSSelectableCard
+ key={key}
+ label={`${title} preset`}
+ isSelected={isSelected}
+ onChange={() => onApplyUnifiedPreset(key)}
+ padding={2}>
+ <XDSVStack gap={1.5} hAlign="center">
+ <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'}>
+ {title}
+ </XDSText>
+ </XDSVStack>
+ </XDSSelectableCard>
+ );
+ })}
+ </XDSGrid>
+ </XDSVStack>
+
+ {/* Typography */}
+ <XDSVStack gap={4}>
+ <XDSVStack gap={3}>
+ {[
+ {token: '--font-family-heading', label: 'Heading Font'},
+ {token: '--font-family-body', label: 'Body Font'},
+ ].map(({token, label}) => (
+ <LabeledField key={token} label={label}>
+ <XDSSelector
+ label={label}
+ isLabelHidden
+ size="sm"
+ placeholder="Custom"
+ xstyle={styles.fullWidthField}
+ options={FONT_OPTIONS}
+ value={fontValue(token)}
+ onChange={(val: string) => onTokenChange(token, val)}
+ />
+ </LabeledField>
+ ))}
+ <LabeledField label="Type Scale">
+ <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));
+ }
+ }}
+ />
+ </LabeledField>
+ </XDSVStack>
+ <ScaleControl
+ label="Type Size"
+ tooltip={`Geometric scale: size = round(base × ratio^step). Base = ${typeSizeMatch ?? typeScaleBase}px, ratio = ${typeScaleRatio.toFixed(3)}.`}
+ controlLabel="Type size"
+ options={[
+ {label: 'S', value: '12'},
+ {label: 'M', value: '14'},
+ {label: 'L', value: '16'},
+ {label: 'XL', value: '18'},
+ ]}
+ toggleValue={typeSizeMatch != null ? String(typeSizeMatch) : null}
+ onToggle={v => onApplyTypeScale(Number(v), typeScaleRatio)}
+ numberValue={typeSizeMatch ?? null}
+ onNumber={v => onApplyTypeScale(v, typeScaleRatio)}
+ min={10}
+ max={24}
+ step={1}
+ units="px"
+ />
+ </XDSVStack>
+
+ {/* Shape & Layout */}
+ <XDSVStack gap={4}>
+ <ScaleControl
+ label="Corner Radius"
+ tooltip={`Linear scale: inner = ${radiusMatch ?? radiusBase}px, element = ${(radiusMatch ?? radiusBase) * 2}px, container = ${(radiusMatch ?? radiusBase) * 3}px, page = ${Math.round((radiusMatch ?? radiusBase) * 7)}px.`}
+ controlLabel="Radius"
+ options={[
+ {label: 'S', value: '2'},
+ {label: 'M', value: '4'},
+ {label: 'L', value: '6'},
+ {label: 'XL', value: '12'},
+ ]}
+ toggleValue={radiusMatch != null ? String(radiusMatch) : null}
+ onToggle={v => onApplyRadiusScale(Number(v))}
+ numberValue={radiusMatch ?? null}
+ onNumber={v => onApplyRadiusScale(v)}
+ min={0}
+ max={18}
+ step={2}
+ units="px"
+ />
+ <ScaleControl
+ label="Spacing"
+ tooltip={`Linear scale: step N = ${spacingMatch ?? spacingBase}px × N.`}
+ controlLabel="Spacing"
+ options={[
+ {label: 'S', value: '2'},
+ {label: 'M', value: '4'},
+ {label: 'L', value: '6'},
+ {label: 'XL', value: '8'},
+ ]}
+ toggleValue={spacingMatch != null ? String(spacingMatch) : null}
+ onToggle={v => onApplySpacingScale(Number(v))}
+ numberValue={spacingMatch ?? null}
+ onNumber={v => onApplySpacingScale(v)}
+ min={0}
+ max={16}
+ step={2}
+ units="px"
+ />
+ <ScaleControl
+ label="Element Size"
+ tooltip={`sm = ${(sizeMatch ?? sizeBase) - 4}px, md = ${sizeMatch ?? sizeBase}px, lg = ${(sizeMatch ?? sizeBase) + 4}px.`}
+ controlLabel="Element size"
+ options={[
+ {label: 'S', value: '28'},
+ {label: 'M', value: '32'},
+ {label: 'L', value: '40'},
+ {label: 'XL', value: '48'},
+ ]}
+ toggleValue={sizeMatch != null ? String(sizeMatch) : null}
+ onToggle={v => onApplySizeScale(Number(v))}
+ numberValue={sizeMatch ?? null}
+ onNumber={v => onApplySizeScale(v)}
+ min={24}
+ max={56}
+ step={2}
+ units="px"
+ />
+ </XDSVStack>
+
+ {/* Motion */}
+ <ScaleControl
+ label="Duration"
+ tooltip={`Speed multiplier for all motion. Current: ${durationStep}× (e.g. medium = ${Math.round(410 / durationStep)}ms).`}
+ controlLabel="Duration"
+ options={[
+ {label: '0.5×', value: '0.5'},
+ {label: '1×', value: '1'},
+ {label: '1.5×', value: '1.5'},
+ {label: '2×', value: '2'},
+ ]}
+ toggleValue={String(durationStep)}
+ onToggle={v => onApplyDurationScale(Number(v))}
+ numberValue={durationStep}
+ onNumber={v => onApplyDurationScale(Math.round(v * 10) / 10)}
+ min={0.5}
+ max={2}
+ step={0.1}
+ units="×"
+ />
+ </XDSVStack>
+ );
+}
diff --git a/apps/docsite/src/components/themePlayground/ColorSwatch.tsx b/apps/docsite/src/app/playground/themeEditor/ColorSwatch.tsx
similarity index 72%
rename from apps/docsite/src/components/themePlayground/ColorSwatch.tsx
rename to apps/docsite/src/app/playground/themeEditor/ColorSwatch.tsx
index f979af7893..a7264d9be5 100644
--- a/apps/docsite/src/components/themePlayground/ColorSwatch.tsx
+++ b/apps/docsite/src/app/playground/themeEditor/ColorSwatch.tsx
@@ -2,6 +2,7 @@
'use client';
+import * as stylex from '@stylexjs/stylex';
import {XDSTextInput} from '@xds/core/TextInput';
import {TokenRow} from './TokenRow';
import {
@@ -10,6 +11,40 @@ import {
colorWithAlphaToString,
} from './helpers';
+const s = stylex.create({
+ swatch: {
+ width: 28,
+ height: 28,
+ borderRadius: 6,
+ border: '1px solid var(--color-border-emphasized)',
+ flexShrink: 0,
+ position: 'relative',
+ },
+ swatchInteractive: {
+ cursor: 'pointer',
+ },
+ // Native color input overlaid transparently on the swatch (XDS has no color
+ // picker), so clicking the swatch opens the OS picker.
+ colorInput: {
+ position: 'absolute',
+ inset: 0,
+ width: '100%',
+ height: '100%',
+ opacity: 0,
+ cursor: 'pointer',
+ border: 'none',
+ padding: 0,
+ zIndex: 1,
+ },
+ input: {
+ width: 120,
+ },
+});
+
+const dynamic = stylex.create({
+ fill: (color: string) => ({backgroundColor: color}),
+});
+
export function ColorSwatch({
tokenName,
value,
@@ -47,41 +82,17 @@ export function ColorSwatch({
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',
- }}
- />
+ {...stylex.props(
+ s.swatch,
+ hasColorPicker && s.swatchInteractive,
+ dynamic.fill(displayValue),
+ )}>
{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,
- }}
+ {...stylex.props(s.colorInput)}
/>
)}
</div>
@@ -115,7 +126,7 @@ export function ColorSwatch({
onChange(tokenName, newValue);
}
}}
- style={{width: 120}}
+ xstyle={s.input}
/>
}
/>
diff --git a/apps/docsite/src/components/themePlayground/ComponentTokensPanel.tsx b/apps/docsite/src/app/playground/themeEditor/ComponentTokensPanel.tsx
similarity index 85%
rename from apps/docsite/src/components/themePlayground/ComponentTokensPanel.tsx
rename to apps/docsite/src/app/playground/themeEditor/ComponentTokensPanel.tsx
index e55066d502..c01d90179d 100644
--- a/apps/docsite/src/components/themePlayground/ComponentTokensPanel.tsx
+++ b/apps/docsite/src/app/playground/themeEditor/ComponentTokensPanel.tsx
@@ -2,10 +2,10 @@
'use client';
-import * as React from 'react';
+import {useCallback, useRef, useState} from 'react';
import * as stylex from '@stylexjs/stylex';
import {XDSText, XDSHeading} from '@xds/core/Text';
-import {XDSVStack, XDSHStack} from '@xds/core/Stack';
+import {XDSVStack, XDSHStack, XDSStackItem} from '@xds/core/Stack';
import {XDSSelector} from '@xds/core/Selector';
import {XDSTextInput} from '@xds/core/TextInput';
import {XDSButton} from '@xds/core/Button';
@@ -19,11 +19,21 @@ import {
const styles = stylex.create({
fullWidthField: {width: '100%'},
+ row: {
+ paddingBlock: 6,
+ gap: 10,
+ },
+ // minWidth: 0 lets the description truncate (maxLines) instead of overflowing.
+ rowLabel: {
+ minWidth: 0,
+ },
+ // Fixed-width value-control column for each component-token row.
+ rowControl: {
+ flexShrink: 0,
+ width: 180,
+ },
});
-// 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
@@ -74,20 +84,22 @@ export function ComponentTokensPanel({
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('');
+ const [customVars, setCustomVars] = useState<Set<string>>(new Set());
+ const [newComponent, setNewComponent] = useState('button');
+ const [newProperty, setNewProperty] = useState('');
+ const [newValue, setNewValue] = useState('');
// Initialize from existing overrides to avoid duplicate keys after remount
- const nextIdRef = React.useRef(
+ const nextIdRef = 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;}
+ const handleAddCustom = useCallback(() => {
+ if (!newComponent || !newProperty || !newValue) {
+ return;
+ }
onCustomOverridesChange([
...customOverrides,
{
@@ -107,14 +119,14 @@ export function ComponentTokensPanel({
onCustomOverridesChange,
]);
- const handleRemoveCustom = React.useCallback(
+ const handleRemoveCustom = useCallback(
(index: number) => {
onCustomOverridesChange(customOverrides.filter((_, i) => i !== index));
},
[customOverrides, onCustomOverridesChange],
);
- const handleUpdateCustomValue = React.useCallback(
+ const handleUpdateCustomValue = useCallback(
(index: number, value: string) => {
const updated = [...customOverrides];
updated[index] = {...updated[index], value};
@@ -141,21 +153,17 @@ export function ComponentTokensPanel({
v.options.some(o => o.value === currentValue));
return (
- <div
+ <XDSHStack
key={v.name}
- style={{
- padding: '6px 0',
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'space-between',
- gap: 10,
- }}>
- <div style={{flex: 1, minWidth: 0}}>
+ vAlign="center"
+ justify="between"
+ xstyle={styles.row}>
+ <XDSStackItem size="fill" xstyle={styles.rowLabel}>
<XDSText type="label" color="secondary" maxLines={1}>
{v.description}
</XDSText>
- </div>
- <div style={{flexShrink: 0, width: CONTROL_WIDTH}}>
+ </XDSStackItem>
+ <XDSStackItem xstyle={styles.rowControl}>
{!isPresetValue ? (
<XDSTextInput
label={v.name}
@@ -199,8 +207,8 @@ export function ComponentTokensPanel({
}}
/>
)}
- </div>
- </div>
+ </XDSStackItem>
+ </XDSHStack>
);
})}
</XDSVStack>
@@ -218,11 +226,11 @@ export function ComponentTokensPanel({
{customOverrides.map((override, i) => (
<XDSVStack key={override.id} gap={1}>
<XDSHStack gap={2} vAlign="end">
- <div style={{flex: 1, minWidth: 0}}>
+ <XDSStackItem size="fill" xstyle={styles.rowLabel}>
<XDSText type="supporting" color="secondary" maxLines={1}>
.xds-{override.component} → {override.property}
</XDSText>
- </div>
+ </XDSStackItem>
<XDSButton
label="Remove"
variant="ghost"
diff --git a/apps/docsite/src/components/themePlayground/RawTokensPanel.tsx b/apps/docsite/src/app/playground/themeEditor/RawTokensPanel.tsx
similarity index 69%
rename from apps/docsite/src/components/themePlayground/RawTokensPanel.tsx
rename to apps/docsite/src/app/playground/themeEditor/RawTokensPanel.tsx
index b3c4a15349..30783c48c4 100644
--- a/apps/docsite/src/components/themePlayground/RawTokensPanel.tsx
+++ b/apps/docsite/src/app/playground/themeEditor/RawTokensPanel.tsx
@@ -2,7 +2,9 @@
'use client';
-import * as React from 'react';
+import {useState} from 'react';
+import type {ReactNode} from 'react';
+import * as stylex from '@stylexjs/stylex';
import {XDSText} from '@xds/core/Text';
import {XDSVStack} from '@xds/core/Stack';
import {XDSTextInput} from '@xds/core/TextInput';
@@ -33,6 +35,54 @@ import {ColorSwatch} from './ColorSwatch';
import {TokenRow} from './TokenRow';
import {COLOR_CATEGORIES, TYPOGRAPHY_CATEGORIES} from './constants';
+const s = stylex.create({
+ scrollX: {
+ overflowX: 'auto',
+ },
+ categoryHeading: {
+ display: 'block',
+ paddingTop: 'var(--spacing-2)',
+ paddingBottom: 'var(--spacing-1)',
+ },
+ spacingPreview: {
+ height: 24,
+ backgroundColor: 'var(--color-accent)',
+ borderRadius: 4,
+ flexShrink: 0,
+ },
+ radiusPreview: {
+ width: 32,
+ height: 32,
+ backgroundColor: 'var(--color-accent)',
+ flexShrink: 0,
+ },
+ typePreview: {
+ width: 48,
+ height: 32,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ color: 'var(--color-text-primary)',
+ flexShrink: 0,
+ },
+ inputSm: {
+ width: 80,
+ },
+ inputLg: {
+ width: 200,
+ },
+});
+
+const dynamic = stylex.create({
+ spacingWidth: (width: number) => ({width}),
+ radius: (radius: string) => ({borderRadius: radius}),
+ font: (
+ fontSize: string,
+ fontWeight: string | number,
+ fontFamily: string,
+ ) => ({fontSize, fontWeight, fontFamily}),
+});
+
const TOKEN_GROUPS = {
colors: {label: 'Colors', tokens: colorDefaults},
spacing: {label: 'Spacing', tokens: spacingDefaults},
@@ -49,7 +99,7 @@ const TOKEN_GROUPS = {
type TokenGroupKey = keyof typeof TOKEN_GROUPS;
-const TOKEN_ICONS: Record<TokenGroupKey, React.ReactNode> = {
+const TOKEN_ICONS: Record<TokenGroupKey, ReactNode> = {
colors: <PaletteOutline16Icon />,
spacing: <FourRectangleGridOutline16Icon />,
radius: <FrameDashedOutline16Icon />,
@@ -60,92 +110,61 @@ const TOKEN_ICONS: Record<TokenGroupKey, React.ReactNode> = {
easing: <BoltOutline16Icon />,
};
-function SpacingEditor({
- tokenName,
- value,
- onChange,
-}: {
+interface EditorProps {
tokenName: string;
value: string;
onChange: (name: string, value: string) => void;
-}) {
+}
+
+function SpacingEditor({tokenName, value, onChange}: EditorProps) {
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,
- }}
+ {...stylex.props(
+ s.spacingPreview,
+ dynamic.spacingWidth(Math.min(numValue, 48)),
+ )}
/>
}
input={
- <div style={{width: 80}}>
- <XDSTextInput
- label="Value"
- isLabelHidden
- value={value}
- onChange={val => onChange(tokenName, val)}
- size="sm"
- />
- </div>
+ <XDSTextInput
+ label="Value"
+ isLabelHidden
+ value={value}
+ onChange={val => onChange(tokenName, val)}
+ size="sm"
+ xstyle={s.inputSm}
+ />
}
/>
);
}
-function RadiusEditor({
- tokenName,
- value,
- onChange,
-}: {
- tokenName: string;
- value: string;
- onChange: (name: string, value: string) => void;
-}) {
+function RadiusEditor({tokenName, value, onChange}: EditorProps) {
return (
<TokenRow
tokenName={tokenName}
preview={
- <div
- style={{
- width: 32,
- height: 32,
- backgroundColor: 'var(--color-accent)',
- borderRadius: value,
- flexShrink: 0,
- }}
- />
+ <div {...stylex.props(s.radiusPreview, dynamic.radius(value))} />
}
input={
- <div style={{width: 80}}>
- <XDSTextInput
- label="Value"
- isLabelHidden
- value={value}
- onChange={val => onChange(tokenName, val)}
- size="sm"
- />
- </div>
+ <XDSTextInput
+ label="Value"
+ isLabelHidden
+ value={value}
+ onChange={val => onChange(tokenName, val)}
+ size="sm"
+ xstyle={s.inputSm}
+ />
}
/>
);
}
-function TypographyEditor({
- tokenName,
- value,
- onChange,
-}: {
- tokenName: string;
- value: string;
- onChange: (name: string, value: string) => void;
-}) {
+function TypographyEditor({tokenName, value, onChange}: EditorProps) {
const isFont = tokenName.includes('font-') && !tokenName.includes('weight');
const isSize = tokenName.includes('text-') && tokenName.includes('size');
const isWeight = tokenName.includes('weight');
@@ -155,58 +174,44 @@ function TypographyEditor({
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,
- }}>
+ {...stylex.props(
+ s.typePreview,
+ dynamic.font(
+ isSize ? value : '14px',
+ isWeight ? value : 400,
+ isFont ? value : 'inherit',
+ ),
+ )}>
Aa
</div>
}
input={
- <div style={{width: 200}}>
- <XDSTextInput
- label="Value"
- isLabelHidden
- value={value}
- onChange={val => onChange(tokenName, val)}
- size="sm"
- />
- </div>
+ <XDSTextInput
+ label="Value"
+ isLabelHidden
+ value={value}
+ onChange={val => onChange(tokenName, val)}
+ size="sm"
+ xstyle={s.inputLg}
+ />
}
/>
);
}
-function GenericEditor({
- tokenName,
- value,
- onChange,
-}: {
- tokenName: string;
- value: string;
- onChange: (name: string, value: string) => void;
-}) {
+function GenericEditor({tokenName, value, onChange}: EditorProps) {
return (
<TokenRow
tokenName={tokenName}
input={
- <div style={{width: 200}}>
- <XDSTextInput
- label="Value"
- isLabelHidden
- value={value}
- onChange={val => onChange(tokenName, val)}
- size="sm"
- />
- </div>
+ <XDSTextInput
+ label="Value"
+ isLabelHidden
+ value={value}
+ onChange={val => onChange(tokenName, val)}
+ size="sm"
+ xstyle={s.inputLg}
+ />
}
/>
);
@@ -223,11 +228,11 @@ export function RawTokensPanel({
mode,
onTokenChange,
}: RawTokensPanelProps) {
- const [activeGroup, setActiveGroup] = React.useState<TokenGroupKey>('colors');
+ const [activeGroup, setActiveGroup] = useState<TokenGroupKey>('colors');
return (
<XDSVStack gap={3}>
- <div style={{overflowX: 'auto'}}>
+ <div {...stylex.props(s.scrollX)}>
<XDSToggleButtonGroup
label="Token category"
type="single"
@@ -261,10 +266,7 @@ export function RawTokensPanel({
type="label"
color="primary"
weight="semibold"
- style={{
- padding: '8px 0 4px',
- display: 'block',
- }}>
+ xstyle={s.categoryHeading}>
{category}
</XDSText>
{tokenNames
@@ -317,7 +319,7 @@ export function RawTokensPanel({
type="label"
color="primary"
weight="semibold"
- style={{padding: '8px 0 4px', display: 'block'}}>
+ xstyle={s.categoryHeading}>
{category}
</XDSText>
{tokenNames.map(tokenName => (
diff --git a/apps/docsite/src/components/themePlayground/PlaygroundThemeEditor.tsx b/apps/docsite/src/app/playground/themeEditor/ThemeEditor.tsx
similarity index 64%
rename from apps/docsite/src/components/themePlayground/PlaygroundThemeEditor.tsx
rename to apps/docsite/src/app/playground/themeEditor/ThemeEditor.tsx
index 75b67e95c9..4ebb8d9b8e 100644
--- a/apps/docsite/src/components/themePlayground/PlaygroundThemeEditor.tsx
+++ b/apps/docsite/src/app/playground/themeEditor/ThemeEditor.tsx
@@ -1,21 +1,22 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
/**
- * @file PlaygroundThemeEditor.tsx
+ * @file ThemeEditor.tsx
* @input optional seed theme + the playground's light/dark mode
* @output the theme editor's left-panel content (tab strip + scrollable body)
- * @position Playground — embeds the themePlayground editor as a left-panel view.
+ * @position Playground — the Theme tab's editor, rendered in the left panel.
*
- * A self-contained version of the editor portion of ThemeEditorView: it owns the
- * token + scale state, renders the Theme/Components/Tokens tab strip and body, and
- * reports the composed theme upward via onThemeChange so the playground can push it
- * to the live preview iframe.
+ * A self-contained theme editor: it owns the token + scale state, renders the
+ * Theme/Components/Tokens tab strip and body, and reports the composed theme upward
+ * via onThemeChange so the playground can push it to the live preview iframe.
*/
'use client';
-import * as React from 'react';
+import {useCallback, useEffect, useMemo, useState} from 'react';
+import * as stylex from '@stylexjs/stylex';
import {XDSTabList, XDSTab} from '@xds/core/TabList';
+import {XDSVStack, XDSStackItem} from '@xds/core/Stack';
import {
defineTheme,
expandTypeScale,
@@ -34,7 +35,7 @@ import {
easeDefaults,
} from '@xds/core/theme';
import type {XDSDefinedTheme} from '@xds/core/theme';
-import {EditorSections} from './EditorSections';
+import {BaseStylesPanel} from './BaseStylesPanel';
import {ComponentTokensPanel} from './ComponentTokensPanel';
import type {CustomOverride} from './ComponentTokensPanel';
import {RawTokensPanel} from './RawTokensPanel';
@@ -43,7 +44,24 @@ import {
COMPONENT_VAR_NAMES,
GOOGLE_FONTS_URL,
} from './constants';
-import {buildComponentOverrides, mergeComponentStyleMaps} from './helpers';
+import {
+ buildComponentOverrides,
+ buildSpacingScale,
+ mergeComponentStyleMaps,
+} from './helpers';
+
+const s = stylex.create({
+ root: {
+ flex: 1,
+ minHeight: 0,
+ overflow: 'hidden',
+ },
+ body: {
+ flex: 1,
+ overflow: 'auto',
+ padding: 'var(--spacing-4)',
+ },
+});
const ALL_DEFAULTS: Record<string, string> = {
...colorDefaults,
@@ -59,7 +77,7 @@ const ALL_DEFAULTS: Record<string, string> = {
...easeDefaults,
};
-interface PlaygroundThemeEditorProps {
+interface ThemeEditorProps {
/** Light/dark mode, owned by the playground so editor + preview stay in sync. */
mode: 'light' | 'dark';
/** Optional theme to seed the editor's token + component state from. */
@@ -68,37 +86,35 @@ interface PlaygroundThemeEditorProps {
onThemeChange: (theme: XDSDefinedTheme) => void;
}
-export function PlaygroundThemeEditor({
+export function ThemeEditor({
mode,
initialTheme,
onThemeChange,
-}: PlaygroundThemeEditorProps) {
- const [tokens, setTokens] = React.useState<Record<string, string>>(() => ({
+}: ThemeEditorProps) {
+ const [tokens, setTokens] = useState<Record<string, string>>(() => ({
...ALL_DEFAULTS,
...initialTheme?.tokens,
}));
// Component-level overrides from the seeded theme. Kept separate from token
// state so they form the base layer that token + custom overrides compose on.
- const [baseComponents] = React.useState<Record<string, unknown>>(
+ const [baseComponents] = useState<Record<string, unknown>>(
() => initialTheme?.components ?? {},
);
- const [panelTab, setPanelTab] = React.useState<
- 'theme' | 'components' | 'tokens'
- >('theme');
- 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);
+ const [panelTab, setPanelTab] = useState<'theme' | 'components' | 'tokens'>(
+ 'theme',
+ );
+ const [typeScaleBase, setTypeScaleBase] = useState(14);
+ const [typeScaleRatio, setTypeScaleRatio] = useState(1.2);
+ const [radiusBase, setRadiusBase] = useState(4);
+ const [spacingBase, setSpacingBase] = useState(4);
+ const [sizeBase, setSizeBase] = useState(32);
+ const [durationStep, setDurationStep] = useState(1);
// A unified preset is only "active" once the user explicitly applies one.
- const [activePreset, setActivePreset] = React.useState<string | null>(null);
- const [autoPickColors, setAutoPickColors] = React.useState(false);
- const [customOverrides, setCustomOverrides] = React.useState<
- CustomOverride[]
- >([]);
+ const [activePreset, setActivePreset] = useState<string | null>(null);
+ const [autoPickColors, setAutoPickColors] = useState(false);
+ const [customOverrides, setCustomOverrides] = useState<CustomOverride[]>([]);
- const currentTheme = React.useMemo(() => {
+ const currentTheme = useMemo(() => {
const coreTokens: Record<string, string> = {};
const componentTokens: Record<string, string> = {};
for (const [key, value] of Object.entries(tokens)) {
@@ -125,50 +141,28 @@ export function PlaygroundThemeEditor({
// Report the composed theme upward so the playground can push it to the
// preview iframe whenever tokens or overrides change.
- React.useEffect(() => {
+ useEffect(() => {
onThemeChange(currentTheme);
}, [currentTheme, onThemeChange]);
- const handleTokenChange = React.useCallback((name: string, value: string) => {
+ const handleTokenChange = useCallback((name: string, value: string) => {
setTokens(prev => ({...prev, [name]: value}));
}, []);
- const applyTypeScale = React.useCallback((base: number, ratio: number) => {
+ const applyTypeScale = useCallback((base: number, ratio: number) => {
setActivePreset(null);
setTypeScaleBase(base);
setTypeScaleRatio(ratio);
setTokens(prev => ({...prev, ...expandTypeScale({base, ratio})}));
}, []);
- const applySpacingScale = React.useCallback((base: number) => {
+ const applySpacingScale = 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}));
+ setTokens(prev => ({...prev, ...buildSpacingScale(base)}));
}, []);
- const applySizeScale = React.useCallback((base: number) => {
+ const applySizeScale = useCallback((base: number) => {
setActivePreset(null);
setSizeBase(base);
setTokens(prev => ({
@@ -179,7 +173,7 @@ export function PlaygroundThemeEditor({
}));
}, []);
- const applyRadiusScale = React.useCallback((base: number) => {
+ const applyRadiusScale = useCallback((base: number) => {
setActivePreset(null);
setRadiusBase(base);
setTokens(prev => ({
@@ -188,7 +182,7 @@ export function PlaygroundThemeEditor({
}));
}, []);
- const applyDurationScale = React.useCallback((multiplier: number) => {
+ const applyDurationScale = useCallback((multiplier: number) => {
setDurationStep(multiplier);
const defaults: Record<string, number> = {
'--duration-fast-min': 130,
@@ -208,7 +202,7 @@ export function PlaygroundThemeEditor({
setTokens(prev => ({...prev, ...patch}));
}, []);
- const applyUnifiedPreset = React.useCallback((presetKey: string) => {
+ const applyUnifiedPreset = useCallback((presetKey: string) => {
const p = UNIFIED_PRESETS[presetKey as keyof typeof UNIFIED_PRESETS];
if (!p) {
return;
@@ -219,43 +213,18 @@ export function PlaygroundThemeEditor({
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`,
- };
- });
+ setTokens(prev => ({
+ ...prev,
+ ...expandTypeScale({base: p.typeBase, ratio: p.typeRatio}),
+ ...buildSpacingScale(p.spacing),
+ ...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 handleExpandColorScale = useCallback((accentHex: string) => {
const derived = expandColorScale({accent: accentHex});
let hex = accentHex.replace('#', '');
// Normalize 3-char short hex (e.g. "f00") to 6-char ("ff0000")
@@ -277,19 +246,10 @@ export function PlaygroundThemeEditor({
}, []);
return (
- <div
- style={{
- flex: 1,
- minHeight: 0,
- display: 'flex',
- flexDirection: 'column',
- overflow: 'hidden',
- }}>
- {/* Self-load theme fonts (mirrors ThemeEditorView) so the editor's
- controls render in the loaded theme's typeface even when used
- standalone. */}
+ <XDSVStack xstyle={s.root}>
+ {/* Self-load theme fonts so the editor's controls render in the loaded
+ theme's typeface even when used standalone. */}
<style>{`@import url("${GOOGLE_FONTS_URL}");`}</style>
- {/* Tab strip */}
<XDSTabList
hasDivider
value={panelTab}
@@ -299,10 +259,9 @@ export function PlaygroundThemeEditor({
<XDSTab value="tokens" label="Advanced" />
</XDSTabList>
- {/* Scrollable editor content */}
- <div style={{flex: 1, overflow: 'auto', padding: 16}}>
+ <XDSStackItem size="fill" xstyle={s.body}>
{panelTab === 'theme' && (
- <EditorSections
+ <BaseStylesPanel
tokens={tokens}
mode={mode}
typeScaleBase={typeScaleBase}
@@ -322,7 +281,6 @@ export function PlaygroundThemeEditor({
onApplyUnifiedPreset={applyUnifiedPreset}
onSetAutoPickColors={setAutoPickColors}
onExpandColorScale={handleExpandColorScale}
- onSetTokens={setTokens}
/>
)}
{panelTab === 'components' && (
@@ -341,7 +299,7 @@ export function PlaygroundThemeEditor({
onTokenChange={handleTokenChange}
/>
)}
- </div>
- </div>
+ </XDSStackItem>
+ </XDSVStack>
);
}
diff --git a/apps/docsite/src/app/playground/themeEditor/TokenRow.tsx b/apps/docsite/src/app/playground/themeEditor/TokenRow.tsx
new file mode 100644
index 0000000000..1f22e956c8
--- /dev/null
+++ b/apps/docsite/src/app/playground/themeEditor/TokenRow.tsx
@@ -0,0 +1,50 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+import type {ReactNode} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {XDSText} from '@xds/core/Text';
+import {XDSHStack, XDSStackItem} from '@xds/core/Stack';
+import {getTokenLabel} from './helpers';
+
+const s = stylex.create({
+ row: {
+ paddingBlock: 'var(--spacing-2)',
+ },
+ // minWidth: 0 lets the label truncate (maxLines) instead of overflowing.
+ label: {
+ minWidth: 0,
+ },
+ controls: {
+ flexShrink: 0,
+ },
+});
+
+/**
+ * Standard token-editor row. Left: readable token name. Right: optional visual
+ * preview followed by the input.
+ */
+export function TokenRow({
+ tokenName,
+ preview,
+ input,
+}: {
+ tokenName: string;
+ preview?: ReactNode;
+ input: ReactNode;
+}) {
+ return (
+ <XDSHStack gap={3} vAlign="center" justify="between" xstyle={s.row}>
+ <XDSStackItem size="fill" xstyle={s.label}>
+ <XDSText type="body" color="primary" maxLines={1}>
+ {getTokenLabel(tokenName)}
+ </XDSText>
+ </XDSStackItem>
+ <XDSHStack gap={2} vAlign="center" xstyle={s.controls}>
+ {preview}
+ {input}
+ </XDSHStack>
+ </XDSHStack>
+ );
+}
diff --git a/apps/docsite/src/components/themePlayground/constants.ts b/apps/docsite/src/app/playground/themeEditor/constants.ts
similarity index 99%
rename from apps/docsite/src/components/themePlayground/constants.ts
rename to apps/docsite/src/app/playground/themeEditor/constants.ts
index 5ba05caed3..efd09cf614 100644
--- a/apps/docsite/src/components/themePlayground/constants.ts
+++ b/apps/docsite/src/app/playground/themeEditor/constants.ts
@@ -65,7 +65,7 @@ export const UNIFIED_PRESETS = {
},
} as const;
-export const RADIUS_OPTIONS = [
+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'},
@@ -78,7 +78,7 @@ export const RADIUS_OPTIONS = [
{value: 'var(--radius-full)', token: '--radius-full', label: 'Full'},
];
-export const SPACING_OPTIONS = [
+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'},
@@ -102,7 +102,7 @@ export function resolveOptionLabel(
return option.label;
}
-export interface ComponentVar {
+interface ComponentVar {
name: string;
default: string;
description: string;
diff --git a/apps/docsite/src/components/themePlayground/helpers.ts b/apps/docsite/src/app/playground/themeEditor/helpers.ts
similarity index 91%
rename from apps/docsite/src/components/themePlayground/helpers.ts
rename to apps/docsite/src/app/playground/themeEditor/helpers.ts
index 0d05054787..cdf18deff4 100644
--- a/apps/docsite/src/components/themePlayground/helpers.ts
+++ b/apps/docsite/src/app/playground/themeEditor/helpers.ts
@@ -63,6 +63,20 @@ export function getTokenLabel(tokenName: string): string {
.replace(/\b\w/g, c => c.toUpperCase());
}
+/**
+ * Build the `--spacing-*` token ramp from a base step: each token is
+ * `round(base × step)px`. Token keys derive from the step (e.g. 0.5 → "0-5").
+ */
+export function buildSpacingScale(base: number): Record<string, string> {
+ const steps = [0, 0.5, 1, 1.5, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
+ const patch: Record<string, string> = {};
+ for (const step of steps) {
+ patch[`--spacing-${String(step).replace('.', '-')}`] =
+ `${Math.round(base * step)}px`;
+ }
+ return patch;
+}
+
type ComponentStyleMap = Record<string, Record<string, Record<string, string>>>;
export function buildComponentOverrides(
@@ -136,7 +150,10 @@ function serializeStyleObject(
if (value && typeof value === 'object') {
lines.push(`${pad}'${escapedKey}': {`);
lines.push(
- ...serializeStyleObject(value as Record<string, unknown>, indentLevel + 1),
+ ...serializeStyleObject(
+ value as Record<string, unknown>,
+ indentLevel + 1,
+ ),
);
lines.push(`${pad}},`);
} else {
@@ -149,7 +166,7 @@ function serializeStyleObject(
return lines;
}
-export interface CustomOverrideEntry {
+interface CustomOverrideEntry {
component: string;
property: string;
value: string;
diff --git a/apps/docsite/src/components/themePlayground/icons.tsx b/apps/docsite/src/app/playground/themeEditor/icons.tsx
similarity index 72%
rename from apps/docsite/src/components/themePlayground/icons.tsx
rename to apps/docsite/src/app/playground/themeEditor/icons.tsx
index d20965a907..a570fe697a 100644
--- a/apps/docsite/src/components/themePlayground/icons.tsx
+++ b/apps/docsite/src/app/playground/themeEditor/icons.tsx
@@ -7,11 +7,8 @@
* 16px size the editor expects, so the ported component code stays unchanged.
*/
-import * as React from 'react';
+import type {ComponentType, ReactElement} from 'react';
import {
- ArrowLeft,
- Sun,
- Moon,
Palette,
LayoutGrid,
Copy,
@@ -24,13 +21,8 @@ import {
} from 'lucide-react';
const sized =
- (Icon: React.ComponentType<LucideProps>) =>
- (props: LucideProps): React.ReactElement => <Icon size={16} {...props} />;
-
-// ThemeEditorView
-export const ArrowLeftFilled16Icon = sized(ArrowLeft);
-export const LargeHalfCircle8RaysLargeOutline16Icon = sized(Sun);
-export const CrescentOutline16Icon = sized(Moon);
+ (Icon: ComponentType<LucideProps>) =>
+ (props: LucideProps): ReactElement => <Icon size={16} {...props} />;
// RawTokensPanel token-category icons
export const PaletteOutline16Icon = sized(Palette);
diff --git a/apps/docsite/src/app/themes/playground/[theme]/page.tsx b/apps/docsite/src/app/themes/playground/[theme]/page.tsx
deleted file mode 100644
index 8bdfe8daa6..0000000000
--- a/apps/docsite/src/app/themes/playground/[theme]/page.tsx
+++ /dev/null
@@ -1,41 +0,0 @@
-// 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/ThemeCardShowcase.tsx b/apps/docsite/src/components/ThemeCardShowcase.tsx
deleted file mode 100644
index ff6a26a060..0000000000
--- a/apps/docsite/src/components/ThemeCardShowcase.tsx
+++ /dev/null
@@ -1,1249 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-'use client';
-
-/**
- * Real-world card showcase for a theme.
- *
- * Three realistic product surfaces rendered with the theme's components
- * — meant to demonstrate how the theme behaves in compositions people
- * actually build (stats card, task card, profile card) rather than as
- * an abstract sample-each-component list.
- *
- * Lives outside the live ThemeShowcasePreview card on the dedicated
- * /themes/<name> page. Always renders in light mode regardless of
- * the page-header toggle, so the cards work as a static reference.
- */
-
-import {type ReactNode} from 'react';
-import * as stylex from '@stylexjs/stylex';
-import {
- Plus,
- Search,
- Tag,
- Folder,
- MapPin,
- List,
- LayoutGrid,
- ShoppingBag,
- Banknote,
- Mic,
- CreditCard,
- Lock,
- X,
- Download,
- Smartphone,
- Wallet,
-} from 'lucide-react';
-import {XDSText, XDSHeading} from '@xds/core/Text';
-import {XDSVStack, XDSHStack} from '@xds/core/Layout';
-import {XDSGrid, XDSGridSpan} from '@xds/core/Grid';
-import {XDSCard} from '@xds/core/Card';
-import {XDSButton} from '@xds/core/Button';
-import {XDSLink} from '@xds/core/Link';
-import {XDSBadge} from '@xds/core/Badge';
-import {XDSBanner} from '@xds/core/Banner';
-import {XDSDivider} from '@xds/core/Divider';
-import {XDSCheckboxInput} from '@xds/core/CheckboxInput';
-import {XDSItem} from '@xds/core/Item';
-import {XDSTable, proportional, pixel} from '@xds/core/Table';
-import {XDSTextInput} from '@xds/core/TextInput';
-import {XDSSelector} from '@xds/core/Selector';
-import {XDSRadioList, XDSRadioListItem} from '@xds/core/RadioList';
-import {XDSSelectableCard} from '@xds/core/SelectableCard';
-import {XDSMoreMenu} from '@xds/core/MoreMenu';
-import {
- XDSChatComposer,
- XDSChatMessage,
- XDSChatMessageBubble,
- XDSChatMessageList,
- XDSChatSystemMessage,
-} from '@xds/core/Chat';
-import {XDSTheme} from '@xds/core/theme';
-import type {XDSDefinedTheme} from '@xds/core/theme';
-import type {ThemeImageSet} from './themeImages';
-
-const styles = stylex.create({
- // Each card paints the theme's body color so the showcase reads as
- // a coherent product surface against the docsite's chrome.
- // Border is forced transparent so the cards float on the surface
- // chrome without visible chrome of their own.
- card: {
- backgroundColor: 'var(--color-background-body)',
- color: 'var(--color-text-primary)',
- minWidth: 0,
- borderColor: 'transparent',
- },
- // Nested flex columns inherit `min-width: auto` which equals
- // content-min-width — causing form inputs to overflow the card
- // at narrow viewports. Force min-width: 0 + width: 100% so the
- // stack always respects the parent's available width and lets
- // its children (XDSTextInput, etc.) shrink with it.
- checkoutStack: {
- minWidth: 0,
- width: '100%',
- },
- // Content inside a payment-method SelectableCard. Constrains the
- // inner stack to the card's available width and wraps long
- // labels (e.g. "Apple Pay", "Google Pay") to a second line
- // instead of overflowing the card boundary at narrow widths.
- paymentCardContent: {
- minWidth: 0,
- width: '100%',
- textAlign: 'center',
- wordBreak: 'break-word',
- },
- // KNOWN-GAP (XDSGridSpan): when an auto-fit XDSGrid produces
- // fewer tracks than an XDSGridSpan claims, the span keeps its
- // original count and leaves empty tracks beside smaller cards
- // (e.g. Chat claims 2-of-3, but if only 2 tracks fit, Checkout
- // ends up alone on its row with one empty track beside it).
- // Forcing every span to `grid-column: 1 / -1` below 1024px (the
- // threshold where the worst-case 4-track + 3-gap layout stops
- // fitting) collapses each row to a single column at narrow
- // widths so cards always reach the row edge.
- //
- // Ideally XDSGridSpan would clamp `span N` to the available
- // track count automatically; until that lands in @xds/core,
- // this xstyle is the load-bearing workaround for both grid rows
- // below.
- fullSpanAtNarrow: {
- gridColumn: {
- default: null,
- '@media (max-width: 1024px)': '1 / -1',
- },
- },
- // Inventory card uses padding={0} since the header, filter row,
- // and table each own their own padding. Background uses --color-
- // background-surface (the lifted-above-body tone) so the inventory
- // reads as a distinct interactive surface against the page chrome.
- // Keeps the XDSCard default variant's border (via --color-border-
- // emphasized) so it reads as a bordered card.
- inventoryCard: {
- backgroundColor: 'var(--color-background-surface)',
- color: 'var(--color-text-primary)',
- overflow: 'hidden',
- },
- inventoryHeader: {
- paddingBlock: 'var(--spacing-6)',
- paddingInline: 'var(--spacing-6)',
- },
- inventoryFilterRow: {
- paddingBlock: 'var(--spacing-4)',
- paddingInline: 'var(--spacing-6)',
- width: '100%',
- },
- // Wraps the low-stock XDSBanner above the table so it inherits the
- // table's horizontal padding rather than running edge-to-edge.
- inventoryBannerWrap: {
- paddingInline: 'var(--spacing-6)',
- paddingBottom: 'var(--spacing-4)',
- },
- searchInput: {
- flex: 1,
- minWidth: 0,
- maxWidth: 240,
- },
- // Square thumbnail used in the Item column. Falls back to a
- // colored letter chip via styles.thumbnailFallback when no image
- // is provided.
- thumbnail: {
- width: 32,
- height: 32,
- borderRadius: 'var(--radius-element)',
- objectFit: 'cover' as const,
- display: 'block',
- flexShrink: 0,
- },
- thumbnailFallback: {
- width: 32,
- height: 32,
- borderRadius: 'var(--radius-element)',
- backgroundColor: 'var(--color-background-muted)',
- color: 'var(--color-text-secondary)',
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
- fontSize: 'var(--font-size-sm)',
- fontWeight: 600,
- flexShrink: 0,
- },
- // Latest activity card uses surface bg so it reads as a distinct
- // analytics surface beside Inventory (which also uses surface).
- activityCard: {
- backgroundColor: 'var(--color-background-surface)',
- color: 'var(--color-text-primary)',
- minWidth: 0,
- height: '100%',
- },
- // Hand-rolled sparkline — 5 vertical bars rendered as flex children.
- // Theme-aware fill uses --color-success for the on-trend green tone
- // (matches the categorical "green" badge palette used elsewhere).
- // Each bar's height is set inline via --bar-h percentage.
- sparkline: {
- display: 'flex',
- alignItems: 'flex-end',
- justifyContent: 'space-around',
- height: 120,
- width: '100%',
- gap: 8,
- },
- sparkBar: {
- flex: 1,
- minWidth: 0,
- borderRadius: 'var(--radius-element)',
- // Categorical green background tint — the soft pastel surface
- // stop, not the saturated icon/text stop. Reads as a quiet
- // chart fill rather than an alert/status color.
- backgroundColor: 'var(--color-background-green)',
- // Bar height comes from inline `height` style per bar.
- },
- sparkLabels: {
- display: 'flex',
- justifyContent: 'space-around',
- width: '100%',
- color: 'var(--color-text-secondary)',
- fontSize: 'var(--font-size-xs)',
- },
- // Big KPI value (e.g. "18K"). Uses the theme's heading font so it
- // tracks the theme's typography decisions.
- kpiValue: {
- fontSize: 24,
- fontWeight: 700,
- lineHeight: 1.1,
- color: 'var(--color-text-primary)',
- fontFamily: 'var(--font-family-heading)',
- letterSpacing: '-0.01em',
- },
- // Chat card uses padding={0} since the header, message list, and
- // composer each own their own padding. Uses surface bg to match
- // the chat-app pattern people expect (chat surfaces typically
- // lift above body to read as a focused conversation panel).
- chatCard: {
- backgroundColor: 'var(--color-background-surface)',
- color: 'var(--color-text-primary)',
- minWidth: 0,
- overflow: 'hidden',
- display: 'flex',
- flexDirection: 'column' as const,
- },
- // Chat header — avatar + name + status row pinned to the top of
- // the card. Sits flush above the message canvas divider.
- chatHeader: {
- paddingBlock: 'var(--spacing-4)',
- paddingInline: 'var(--spacing-4)',
- },
- // Body wraps XDSChatMessageList in a flex-grow cell so the list
- // expands to fill the card. The list owns its own internal
- // padding (density-based, balanced = spacing-4), so we don't add
- // any here — otherwise the first message ends up double-padded
- // away from the header divider.
- chatBody: {
- flex: 1,
- minHeight: 0,
- overflow: 'hidden',
- },
- // Suggested-question chips above the composer. Centered so the
- // chips feel like a "tap one of these" affordance rather than a
- // left-aligned toolbar. Same horizontal padding as the composer
- // for visual alignment.
- chatSuggestions: {
- paddingInline: 'var(--spacing-4)',
- paddingBottom: 'var(--spacing-2)',
- },
- chatComposer: {
- paddingInline: 'var(--spacing-4)',
- paddingBottom: 'var(--spacing-4)',
- },
- // Compact activity row icon — circular muted disc holding a heroicon.
- activityIcon: {
- width: 32,
- height: 32,
- borderRadius: 'var(--radius-full)',
- backgroundColor: 'var(--color-background-muted)',
- color: 'var(--color-text-secondary)',
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
- flexShrink: 0,
- },
- // Negative inline margin to cancel out XDSItem's --spacing-2
- // internal padding so item content sits flush with the heading
- // above. The item's hover/focus background still extends
- // correctly because the padding is preserved on each row.
- itemListFlush: {
- marginInline: 'calc(var(--spacing-2) * -1)',
- },
- // Lets the outer card content stack fill the full card height
- // so the activity list flex:1 child can absorb the remaining
- // space below the chart + KPI summary + activity heading.
- activityCardStack: {
- height: '100%',
- },
- // Activity list fills remaining vertical space in the card,
- // clips overflow, and fades the bottom edge so longer feeds
- // visually suggest "more below" without rendering a scrollbar.
- // The mask-image is the same value applied to both standard
- // and -webkit- properties for Safari compatibility.
- activityListFade: {
- flex: 1,
- minHeight: 0,
- overflow: 'hidden',
- maskImage:
- 'linear-gradient(to bottom, black calc(100% - 48px), transparent)',
- WebkitMaskImage:
- 'linear-gradient(to bottom, black calc(100% - 48px), transparent)',
- marginInline: 'calc(var(--spacing-2) * -1)',
- },
-});
-
-interface ThemeCardShowcaseProps {
- theme: XDSDefinedTheme;
- images: ThemeImageSet;
- /**
- * Color mode forwarded from ThemePackagePage's mode toggle in the
- * floating footer. Lets the inventory + checkout + top customers
- * cards flip light/dark in sync with the live preview above.
- */
- mode: 'light' | 'dark';
-}
-
-export function ThemeCardShowcase({
- theme,
- images,
- mode,
-}: ThemeCardShowcaseProps) {
- return (
- <XDSTheme theme={theme} mode={mode}>
- <XDSVStack gap={8}>
- {/* Top row: Checkout (1/3) + Chat (2/3) via XDSGridSpan.
- Uses `repeat: 'fit'` so when the viewport is too narrow
- to fit 3 tracks of at least 200px, the remaining tracks
- collapse and the occupied ones stretch to fill the row
- edge-to-edge. NOTE: no `max` cap here — capping the
- track-max forces each cell to `(100% - gaps) / max`,
- which prevents auto-fit from stretching cells beyond
- that fraction at narrow widths (the cards would never
- fill the full row even with one card per row). */}
- <XDSGrid columns={{minWidth: 200, repeat: 'fit'}} gap={4}>
- <XDSGridSpan columns={1} xstyle={styles.fullSpanAtNarrow}>
- <CheckoutCard />
- </XDSGridSpan>
- <XDSGridSpan columns={2} xstyle={styles.fullSpanAtNarrow}>
- <ChatCard />
- </XDSGridSpan>
- </XDSGrid>
- {/* Bottom row: Inventory (3 cols) + Latest activity sidebar
- (1 col). `repeat: 'fit'` (auto-fit) stretches occupied
- tracks to fill the row when columns collapse at narrow
- viewports — same reasoning as the top row: no `max`
- cap so cells can stretch beyond the (100% / max)
- fraction when only one card per row fits. */}
- <XDSGrid columns={{minWidth: 200, repeat: 'fit'}} gap={4}>
- <XDSGridSpan columns={3} xstyle={styles.fullSpanAtNarrow}>
- <InventoryCard images={images} />
- </XDSGridSpan>
- <XDSGridSpan columns={1} xstyle={styles.fullSpanAtNarrow}>
- <LatestActivityCard />
- </XDSGridSpan>
- </XDSGrid>
- </XDSVStack>
- </XDSTheme>
- );
-}
-
-// =============================================================================
-// Card 4 — Checkout form
-// Components exercised: heading + supporting subtitle, XDSTextInput
-// (email), XDSTextInput with startIcon (card number), 2-column grid
-// for expiry + CVC, XDSSelector (country dropdown), full-width
-// primary button with leading icon. Demonstrates a realistic
-// multi-input form composition.
-// =============================================================================
-
-function CheckoutCard() {
- return (
- <XDSCard padding={5} xstyle={styles.card}>
- <XDSVStack gap={4} xstyle={styles.checkoutStack}>
- <XDSHeading level={2}>Checkout</XDSHeading>
-
- <XDSVStack gap={3} xstyle={styles.checkoutStack}>
- <XDSTextInput
- label="Email"
- placeholder="[email protected]"
- value=""
- onChange={() => {}}
- size="lg"
- />
-
- {/* Shipping method picker — vertical radio list. Each
- row pairs a label + a per-row helper description with
- a trailing price in endContent so the price reads
- right-aligned (typical shipping-options layout). The
- group itself has a `description` for the universal
- caveat under all three options. Static demo: value is
- hard-coded to "economy"; tapping other rows does
- nothing. */}
- <XDSRadioList
- label="Shipping method"
- description="Delivery time may vary based on location and availability."
- value="economy"
- onChange={() => {}}>
- <XDSRadioListItem
- value="economy"
- label="Economy Shipping"
- description="Delivered in 5–7 business days"
- endContent={
- <XDSText type="body" weight="bold">
- $12.00
- </XDSText>
- }
- />
- <XDSRadioListItem
- value="standard"
- label="Standard Shipping"
- description="Delivered in 3–5 business days"
- endContent={
- <XDSText type="body" weight="bold">
- $16.00
- </XDSText>
- }
- />
- <XDSRadioListItem
- value="express"
- label="Express Shipping"
- description="Delivered in 1–2 business days"
- endContent={
- <XDSText type="body" weight="bold">
- $24.00
- </XDSText>
- }
- />
- </XDSRadioList>
-
- {/* Payment method picker — 3 horizontal XDSSelectableCards
- in an equal-width grid. Each card has a centered icon
- above a short label. Selected card gets the built-in
- accent border treatment. Static demo: "card" is hard-
- coded selected; tapping other cards does nothing.
- Uses the responsive {minWidth, max} grid pattern so
- cards collapse to fewer columns when the Checkout
- column itself is too narrow to fit 3 abreast. */}
- <XDSVStack gap={2} xstyle={styles.checkoutStack}>
- <XDSText type="supporting" weight="bold">
- Payment method
- </XDSText>
- <XDSGrid columns={{minWidth: 70, max: 3}} gap={2}>
- <XDSSelectableCard
- label="Pay with card"
- isSelected={true}
- onChange={() => {}}
- padding={3}>
- <XDSVStack
- gap={1}
- hAlign="center"
- xstyle={styles.paymentCardContent}>
- <CreditCard size={20} />
- <XDSText type="supporting" weight="bold">
- Card
- </XDSText>
- </XDSVStack>
- </XDSSelectableCard>
- <XDSSelectableCard
- label="Pay with Apple Pay"
- isSelected={false}
- onChange={() => {}}
- padding={3}>
- <XDSVStack
- gap={1}
- hAlign="center"
- xstyle={styles.paymentCardContent}>
- <Smartphone size={20} />
- <XDSText type="supporting" weight="bold">
- Apple Pay
- </XDSText>
- </XDSVStack>
- </XDSSelectableCard>
- <XDSSelectableCard
- label="Pay with Google Pay"
- isSelected={false}
- onChange={() => {}}
- padding={3}>
- <XDSVStack
- gap={1}
- hAlign="center"
- xstyle={styles.paymentCardContent}>
- <Wallet size={20} />
- <XDSText type="supporting" weight="bold">
- Google Pay
- </XDSText>
- </XDSVStack>
- </XDSSelectableCard>
- </XDSGrid>
- </XDSVStack>
-
- <XDSTextInput
- label="Card number"
- placeholder="1234 1234 1234 1234"
- value=""
- onChange={() => {}}
- startIcon={<CreditCard size={16} />}
- size="lg"
- />
-
- {/* Expiry + CVC in a responsive 2-col grid. At narrow
- widths (Checkout column shrinks below the
- {minWidth: 90} threshold per cell) the grid collapses
- to a single column stack so neither input clips past
- the card edge. */}
- <XDSGrid columns={{minWidth: 90, max: 2}} gap={2}>
- <XDSTextInput
- label="Expiry"
- placeholder="MM / YY"
- value=""
- onChange={() => {}}
- size="lg"
- />
- <XDSTextInput
- label="CVC"
- placeholder="123"
- value=""
- onChange={() => {}}
- size="lg"
- />
- </XDSGrid>
-
- {/* Country — XDSSelector (dropdown). */}
- <XDSSelector
- label="Country"
- value="us"
- onChange={() => {}}
- size="lg"
- options={[
- {value: 'us', label: 'United States'},
- {value: 'ca', label: 'Canada'},
- {value: 'uk', label: 'United Kingdom'},
- {value: 'de', label: 'Germany'},
- {value: 'jp', label: 'Japan'},
- {value: 'au', label: 'Australia'},
- ]}
- />
- </XDSVStack>
-
- {/* 1-click checkout opt-in — pre-checked, with a helper
- description underneath. Uses XDSCheckboxInput's built-in
- `description` slot rather than hand-stacking a second
- text row, so the helper inherits the right indentation
- and secondary text color from the primitive. */}
- <XDSCheckboxInput
- label="Securely save my information for 1-click checkout"
- description="Pay faster on Studio and everywhere Link is accepted."
- value={true}
- onChange={() => {}}
- />
-
- <XDSButton
- variant="primary"
- size="lg"
- label="Pay now"
- icon={<Lock size={16} />}
- />
- </XDSVStack>
- </XDSCard>
- );
-}
-
-// =============================================================================
-// Card 5 — Chat
-//
-// Compact chat surface modeled after a typical product messaging UI.
-// Header has avatar + name + status, followed by a short message
-// thread (date divider + 4 alternating-sender bubbles), and an
-// XDSChatComposer at the bottom. All built from real XDS chat
-// primitives (XDSChatMessage, XDSChatMessageBubble, XDSChatMessageList,
-// XDSChatSystemMessage, XDSChatComposer) so the showcase demonstrates
-// theme tokens flowing through the full chat surface.
-// =============================================================================
-
-const SUGGESTED_QUESTIONS = [
- 'Reschedule delivery',
- 'Update shipping address',
- 'Start a return',
-];
-
-// Copilot-style canvas: bare user prompt (filled, right-aligned) +
-// plain-prose assistant response (ghost, flat) + a rich composer
-// with attach / mode picker / voice icon. No avatar header — the
-// canvas IS the surface, not a conversation window.
-function ChatCard() {
- return (
- <XDSCard padding={0} xstyle={styles.chatCard}>
- {/* Header — heading on the left, action chrome (Export, Close)
- on the right. Uses level=2 so it matches the heading scale
- of the other cards (Inventory, Revenue, Checkout). Common
- chat-panel pattern where the surface owns its own dismiss
- and export affordances. */}
- <XDSHStack
- hAlign="between"
- vAlign="center"
- gap={3}
- xstyle={styles.chatHeader}>
- <XDSHeading level={2}>Studio AI</XDSHeading>
-
- <XDSHStack gap={1} vAlign="center">
- <XDSButton
- variant="ghost"
- size="sm"
- isIconOnly
- label="Export conversation"
- tooltip="Export conversation"
- icon={<Download size={16} />}
- />
- <XDSButton
- variant="ghost"
- size="sm"
- isIconOnly
- label="Close chat"
- tooltip="Close chat"
- icon={<X size={16} />}
- />
- </XDSHStack>
- </XDSHStack>
-
- <XDSDivider variant="subtle" />
-
- {/* Message canvas — wider Copilot-style layout. Thread is a
- multi-turn concierge session about order #1043, with a
- "Today" system divider at the top and one structured-data
- block (compact order summary rendered as XDSItem rows
- with a trailing track-package link). */}
- <div {...stylex.props(styles.chatBody)}>
- <XDSChatMessageList>
- <XDSChatSystemMessage>Today</XDSChatSystemMessage>
-
- <XDSChatMessage sender="user">
- <XDSChatMessageBubble variant="filled">
- Where’s my order?
- </XDSChatMessageBubble>
- </XDSChatMessage>
-
- <XDSChatMessage sender="assistant">
- <XDSVStack gap={3}>
- <XDSText type="body">
- Your order #1043 — the Minimalist Watch and Linen Throw —
- shipped this morning from the Aisle 3 warehouse and is currently
- in transit with UPS. It’s on track to arrive at your address by
- end of day tomorrow.
- </XDSText>
- <XDSText type="body">
- Let me know if you’d like to reschedule the delivery, redirect
- it to a pickup point, or start a return once it arrives.
- </XDSText>
- </XDSVStack>
- </XDSChatMessage>
-
- <XDSChatMessage sender="user">
- <XDSChatMessageBubble variant="filled">
- Can you show me the full details?
- </XDSChatMessageBubble>
- </XDSChatMessage>
-
- <XDSChatMessage sender="assistant">
- <XDSVStack gap={3}>
- <XDSText type="body">
- Here’s everything I have on order #1043:
- </XDSText>
- {/* Compact order-summary block — XDSItem rows give
- a label/description + endContent value pair without
- any custom layout code. Wrapped in XDSCard so the
- block reads as a distinct artifact within the
- prose, similar to a Copilot tool-call result. */}
- <XDSCard padding={3}>
- <XDSVStack gap={1}>
- <XDSItem
- label="Items"
- description="Minimalist Watch · Linen Throw"
- endContent={
- <XDSText type="body" weight="bold">
- $248
- </XDSText>
- }
- />
- <XDSItem
- label="Shipping"
- description="UPS Ground"
- endContent={
- <XDSText type="body" weight="bold">
- $12
- </XDSText>
- }
- />
- <XDSItem
- label="Estimated arrival"
- description="Tomorrow by 8pm"
- endContent={<XDSBadge variant="green" label="On time" />}
- />
- <XDSItem
- label="Tracking"
- description="UPS 1Z 999 AA1 0123 4567 84"
- endContent={<XDSLink href="#">Track →</XDSLink>}
- />
- </XDSVStack>
- </XDSCard>
- </XDSVStack>
- </XDSChatMessage>
- </XDSChatMessageList>
- </div>
-
- {/* Suggested follow-up questions — quick chips above composer.
- Centered so they read as "tap one of these" affordances
- rather than a left-anchored toolbar. Static demo: no real
- send wiring; tapping does nothing. */}
- <div {...stylex.props(styles.chatSuggestions)}>
- <XDSHStack gap={1} hAlign="center" wrap="wrap">
- {SUGGESTED_QUESTIONS.map(question => (
- <XDSButton
- key={question}
- variant="secondary"
- size="sm"
- label={question}
- />
- ))}
- </XDSHStack>
- </div>
-
- {/* Composer — full Copilot pattern via XDSChatComposer slots:
- footerActions = attach + Smart mode picker
- sendActions = voice/dictation icon */}
- <div {...stylex.props(styles.chatComposer)}>
- <XDSChatComposer
- value=""
- onChange={() => {}}
- onSubmit={() => {}}
- placeholder="Ask Studio AI…"
- footerActions={
- <XDSButton
- variant="ghost"
- size="md"
- isIconOnly
- label="Attach"
- tooltip="Attach"
- icon={<Plus size={16} />}
- />
- }
- sendActions={
- <XDSButton
- variant="ghost"
- size="md"
- isIconOnly
- label="Voice input"
- tooltip="Voice input"
- icon={<Mic size={16} />}
- />
- }
- />
- </div>
- </XDSCard>
- );
-}
-
-// =============================================================================
-// Card 7 — Latest activity (sidebar beside Inventory)
-//
-// Vertical analytics sidebar that sits to the right of the Inventory
-// card. Tops out with a small CSS-only sparkline (5 bars, no chart
-// library) + a "Monthly" badge, two KPI summary numbers below the
-// chart, then a 4-item activity feed at the bottom.
-//
-// Components exercised: XDSCard (surface bg), XDSHeading, XDSBadge
-// (categorical), XDSItem (avatar + label + description rows),
-// XDSDivider, XDSLink, hand-rolled CSS sparkline.
-// =============================================================================
-
-const SPARKLINE_DATA = [55, 70, 92, 78, 60];
-const SPARKLINE_LABELS = ['Jan', 'Feb', 'Mar', 'Apr', 'May'];
-
-interface ActivityRow {
- id: string;
- icon: ReactNode;
- /** Order label, e.g. "Order #1043". */
- label: string;
- /** Activity type displayed under the label. */
- detail: string;
- time: string;
- /** Signed dollar amount. Negative values are refunds. */
- amount: number;
-}
-
-const ACTIVITY: ActivityRow[] = [
- {
- id: '1',
- icon: <ShoppingBag size={16} />,
- label: 'Order #1043',
- detail: 'Placed · 1:59 pm',
- time: '1:59 pm',
- amount: 248,
- },
- {
- id: '2',
- icon: <Banknote size={16} />,
- label: 'Order #1041',
- detail: 'Refunded · 12:40 pm',
- time: '12:40 pm',
- amount: -89,
- },
- {
- id: '3',
- icon: <ShoppingBag size={16} />,
- label: 'Order #1040',
- detail: 'Placed · 10:30 am',
- time: '10:30 am',
- amount: 156,
- },
- {
- id: '4',
- icon: <ShoppingBag size={16} />,
- label: 'Order #1038',
- detail: 'Placed · 9:11 am',
- time: '9:11 am',
- amount: 412,
- },
- {
- id: '5',
- icon: <ShoppingBag size={16} />,
- label: 'Order #1037',
- detail: 'Placed · 8:42 am',
- time: '8:42 am',
- amount: 95,
- },
-];
-
-function formatAmount(amount: number): string {
- const sign = amount < 0 ? '−' : '+';
- return `${sign}$${Math.abs(amount).toLocaleString()}`;
-}
-
-function LatestActivityCard() {
- return (
- <XDSCard padding={5} xstyle={styles.activityCard}>
- <XDSVStack gap={4} xstyle={styles.activityCardStack}>
- <XDSHeading level={2}>Revenue</XDSHeading>
-
- {/* Hand-rolled CSS sparkline — 5 vertical bars. Heights set
- via inline `height` so the bars are data-driven without
- generating a stylex class per row. */}
- <XDSVStack gap={2}>
- <div {...stylex.props(styles.sparkline)} aria-hidden="true">
- {SPARKLINE_DATA.map((value, i) => (
- <div
- key={i}
- {...stylex.props(styles.sparkBar)}
- style={{height: `${value}%`}}
- />
- ))}
- </div>
- <div {...stylex.props(styles.sparkLabels)} aria-hidden="true">
- {SPARKLINE_LABELS.map(label => (
- <span key={label}>{label}</span>
- ))}
- </div>
- </XDSVStack>
-
- <XDSGrid columns={2} gap={3}>
- <XDSVStack gap={0}>
- <span {...stylex.props(styles.kpiValue)}>18K</span>
- <XDSText type="supporting" color="secondary">
- Monthly revenue
- </XDSText>
- </XDSVStack>
- <XDSVStack gap={0}>
- <span {...stylex.props(styles.kpiValue)}>+12%</span>
- <XDSText type="supporting" color="secondary">
- Order growth
- </XDSText>
- </XDSVStack>
- </XDSGrid>
-
- <XDSDivider variant="subtle" />
-
- <XDSHStack hAlign="between" vAlign="center">
- <XDSHeading level={3}>Activity</XDSHeading>
- <XDSLink href="#">See all</XDSLink>
- </XDSHStack>
-
- <XDSVStack gap={1} xstyle={styles.activityListFade}>
- {ACTIVITY.map(item => (
- <XDSItem
- key={item.id}
- startContent={
- <div {...stylex.props(styles.activityIcon)} aria-hidden="true">
- {item.icon}
- </div>
- }
- label={item.label}
- description={item.detail}
- endContent={
- <XDSText
- type="body"
- weight="bold"
- color={item.amount < 0 ? 'secondary' : 'primary'}>
- {formatAmount(item.amount)}
- </XDSText>
- }
- href="#"
- />
- ))}
- </XDSVStack>
- </XDSVStack>
- </XDSCard>
- );
-}
-
-// =============================================================================
-// Card 7 — Inventory table
-//
-// Rich product-app inventory pattern with a heading + primary action,
-// a filter row (search + 3 filter pills + view toggle), a table with
-// thumbnails / multi-badge tags / per-row overflow menus / selection
-// checkboxes, and a floating bulk-action toolbar showing "3 selected".
-// Everything is a static demo — no real filtering, sorting, or
-// selection wiring — to keep the focus on theme component fidelity.
-//
-// Components exercised: XDSHeading, XDSButton (primary + ghost),
-// XDSTextInput (with start icon), XDSCheckboxInput, XDSTable (custom
-// renderers + proportional widths + dividers + hover), XDSBadge
-// (categorical variants), XDSMoreMenu, XDSCard, XDSDivider, XDSIcon
-// (via lucide-react).
-// =============================================================================
-
-type TagSpec = {label: string; variant: 'blue' | 'green' | 'orange' | 'yellow'};
-
-// `extends Record<string, unknown>` is load-bearing: XDSTable's
-// generic constraint requires it, and Next.js's production build
-// enforces it strictly (dev builds let it slide). Without it the
-// Vercel preview fails to compile at `<XDSTable<InventoryRow>>`
-// below. The `unknown` value type is broad enough to accept
-// `tags: TagSpec[]` and any other field shape we add later.
-interface InventoryRow extends Record<string, unknown> {
- id: string;
- name: string;
- meta: string;
- available: number;
- location: string;
- tags: TagSpec[];
- /**
- * Key into the active ThemeImageSet. The actual URL is resolved
- * at render time via the `images` prop passed down from
- * ThemePackagePage, so each theme can swap its own product
- * photos without touching this data.
- */
- imageKey?: keyof ThemeImageSet;
- thumbnailFallback: string;
- selected: boolean;
-}
-
-const INVENTORY: InventoryRow[] = [
- {
- id: 'a',
- name: 'Minimalist Watch',
- meta: 'Stainless steel, sapphire crystal',
- available: 42,
- location: 'Aisle 3',
- tags: [{label: 'New', variant: 'blue'}],
- imageKey: 'watch',
- thumbnailFallback: 'M',
- selected: false,
- },
- {
- id: 'b',
- name: 'Wireless Headphones',
- meta: 'ANC, 30hr battery',
- available: 128,
- location: 'Aisle 1',
- tags: [{label: 'Popular', variant: 'green'}],
- imageKey: 'headphones',
- thumbnailFallback: 'W',
- selected: true,
- },
- {
- id: 'c',
- name: 'Canvas Backpack',
- meta: 'Water-resistant, 25L',
- available: 63,
- location: 'Aisle 2',
- tags: [{label: 'Limited', variant: 'yellow'}],
- imageKey: 'backpack',
- thumbnailFallback: 'C',
- selected: false,
- },
- {
- id: 'd',
- name: 'Leather Wallet',
- meta: 'Full-grain, RFID blocking',
- available: 15,
- location: 'Aisle 4',
- tags: [{label: 'Leather', variant: 'yellow'}],
- imageKey: 'wallet',
- thumbnailFallback: 'L',
- selected: true,
- },
- {
- id: 'e',
- name: 'Travel Mug',
- meta: 'Vacuum insulated, 16oz',
- available: 87,
- location: 'Aisle 5',
- tags: [{label: 'Drinkware', variant: 'green'}],
- imageKey: 'mug',
- thumbnailFallback: 'T',
- selected: false,
- },
- {
- id: 'f',
- name: 'Linen Throw',
- meta: 'Heavyweight, oat',
- available: 24,
- location: 'Aisle 6',
- tags: [{label: 'Home', variant: 'orange'}],
- imageKey: 'throw_',
- thumbnailFallback: 'L',
- selected: true,
- },
-];
-
-// Reorder threshold — items with `available` below this surface a
-// warning banner above the table. Kept here next to the INVENTORY
-// data so the threshold and the data stay co-located.
-const LOW_STOCK_THRESHOLD = 25;
-const LOW_STOCK_COUNT = INVENTORY.filter(
- row => row.available < LOW_STOCK_THRESHOLD,
-).length;
-
-// -- Cell renderers ---------------------------------------------------------
-
-function SelectCell({row}: {row: InventoryRow}) {
- return (
- <XDSCheckboxInput
- label={`Select ${row.name}`}
- isLabelHidden
- value={row.selected}
- onChange={() => {}}
- />
- );
-}
-
-function ItemCell({row, images}: {row: InventoryRow; images: ThemeImageSet}) {
- const thumbnailSrc = row.imageKey ? images[row.imageKey] : undefined;
- return (
- <XDSHStack gap={3} vAlign="center">
- {thumbnailSrc ? (
- <img src={thumbnailSrc} alt="" {...stylex.props(styles.thumbnail)} />
- ) : (
- <div {...stylex.props(styles.thumbnailFallback)} aria-hidden="true">
- {row.thumbnailFallback}
- </div>
- )}
- <XDSVStack gap={0} style={{minWidth: 0}}>
- <XDSText type="body" weight="bold">
- {row.name}
- </XDSText>
- <XDSText type="supporting" color="secondary">
- {row.meta}
- </XDSText>
- </XDSVStack>
- </XDSHStack>
- );
-}
-
-function TagsCell({row}: {row: InventoryRow}) {
- return (
- <XDSHStack gap={1} wrap="wrap" hAlign="end">
- {row.tags.map(tag => (
- <XDSBadge key={tag.label} label={tag.label} variant={tag.variant} />
- ))}
- </XDSHStack>
- );
-}
-
-function ActionsCell() {
- return (
- <XDSMoreMenu
- label="Row actions"
- items={[
- {label: 'Edit'},
- {label: 'Duplicate'},
- {label: 'Move to…'},
- {type: 'divider'},
- {label: 'Delete'},
- ]}
- />
- );
-}
-
-// -- Inventory card --------------------------------------------------------
-
-function InventoryCard({images}: {images: ThemeImageSet}) {
- return (
- <XDSCard padding={0} xstyle={styles.inventoryCard}>
- {/* Heading + primary action */}
- <XDSHStack
- hAlign="between"
- vAlign="center"
- xstyle={styles.inventoryHeader}>
- <XDSHeading level={2}>Inventory</XDSHeading>
- <XDSButton
- label="Add item"
- variant="primary"
- size="sm"
- icon={<Plus size={16} />}
- />
- </XDSHStack>
-
- <XDSDivider variant="subtle" />
-
- {/* Filter row — search, filter pills, view toggle */}
- <XDSHStack
- gap={3}
- vAlign="center"
- hAlign="between"
- xstyle={styles.inventoryFilterRow}>
- <XDSHStack gap={2} vAlign="center" style={{flex: 1, minWidth: 0}}>
- <XDSTextInput
- label="Search inventory"
- isLabelHidden
- placeholder="Type and hit enter…"
- value=""
- onChange={() => {}}
- startIcon={<Search size={16} />}
- xstyle={styles.searchInput}
- />
- <XDSSelector
- label="Categories"
- isLabelHidden
- placeholder="Categories"
- size="sm"
- startIcon={<Folder size={16} />}
- value={undefined}
- onChange={() => {}}
- options={['Wearables', 'Audio', 'Bags', 'Drinkware', 'Home']}
- />
- <XDSSelector
- label="Locations"
- isLabelHidden
- placeholder="Locations"
- size="sm"
- startIcon={<MapPin size={16} />}
- value={undefined}
- onChange={() => {}}
- options={[
- 'Aisle 1',
- 'Aisle 2',
- 'Aisle 3',
- 'Aisle 4',
- 'Aisle 5',
- 'Aisle 6',
- ]}
- />
- <XDSSelector
- label="Tags"
- isLabelHidden
- placeholder="Tags"
- size="sm"
- startIcon={<Tag size={16} />}
- value={undefined}
- onChange={() => {}}
- options={[
- 'New',
- 'Popular',
- 'Limited',
- 'Leather',
- 'Drinkware',
- 'Home',
- ]}
- />
- </XDSHStack>
- <XDSHStack gap={1} vAlign="center">
- <XDSButton
- variant="ghost"
- size="sm"
- isIconOnly
- label="List view"
- tooltip="List view"
- icon={<List size={18} />}
- />
- <XDSButton
- variant="ghost"
- size="sm"
- isIconOnly
- label="Grid view"
- tooltip="Grid view"
- icon={<LayoutGrid size={18} />}
- />
- </XDSHStack>
- </XDSHStack>
-
- {/* Low-stock warning — surfaces a contextual XDSBanner above
- the table when any inventory rows fall below LOW_STOCK_
- THRESHOLD. Wrapped in inventoryBannerWrap so the banner
- inherits the table's horizontal padding. */}
- {LOW_STOCK_COUNT > 0 && (
- <div {...stylex.props(styles.inventoryBannerWrap)}>
- <XDSBanner
- status="warning"
- title={`${LOW_STOCK_COUNT} items are running low`}
- />
- </div>
- )}
-
- <XDSTable<InventoryRow>
- data={INVENTORY}
- columns={[
- {
- key: 'select',
- header: '',
- width: pixel(48),
- renderCell: row => <SelectCell row={row} />,
- },
- {
- key: 'item',
- header: 'Item',
- width: proportional(3),
- renderCell: row => <ItemCell row={row} images={images} />,
- },
- {
- key: 'available',
- header: 'Available',
- // Fixed pixel width since the data is short (2-3 digit
- // counts) and the header label is the widest piece.
- // Frees the remaining horizontal space for Item and
- // pushes Available/Location closer to Tags.
- width: pixel(100),
- renderCell: row => <XDSText type="body">{row.available}</XDSText>,
- },
- {
- key: 'location',
- header: 'Location',
- width: pixel(100),
- renderCell: row => <XDSText type="body">{row.location}</XDSText>,
- },
- {
- key: 'tags',
- header: 'Tags',
- width: proportional(2),
- align: 'end',
- renderCell: row => <TagsCell row={row} />,
- },
- {
- key: 'actions',
- header: '',
- width: pixel(48),
- renderCell: () => <ActionsCell />,
- },
- ]}
- density="spacious"
- dividers="rows"
- hasHover
- />
- </XDSCard>
- );
-}
diff --git a/apps/docsite/src/components/ThemeShowcasePreview.tsx b/apps/docsite/src/components/ThemeShowcasePreview.tsx
deleted file mode 100644
index 74ddc98b33..0000000000
--- a/apps/docsite/src/components/ThemeShowcasePreview.tsx
+++ /dev/null
@@ -1,260 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-'use client';
-
-import stylex from '@stylexjs/stylex';
-import {Search, User, ShoppingBag} from 'lucide-react';
-import {XDSText, XDSHeading} from '@xds/core/Text';
-import {XDSVStack, XDSHStack} from '@xds/core/Layout';
-import {XDSButton} from '@xds/core/Button';
-import {XDSCard} from '@xds/core/Card';
-import {XDSCenter} from '@xds/core/Center';
-import {XDSSection} from '@xds/core/Section';
-import {XDSGrid} from '@xds/core/Grid';
-import {XDSBadge} from '@xds/core/Badge';
-import {XDSAspectRatio} from '@xds/core/AspectRatio';
-import {XDSTopNav, XDSTopNavHeading, XDSTopNavItem} from '@xds/core/TopNav';
-import {XDSNumberInput} from '@xds/core/NumberInput';
-import type {ThemeImageSet} from './themeImages';
-const styles = stylex.create({
- productImage: {
- width: '100%',
- height: '100%',
- objectFit: 'cover' as const,
- },
- cardBody: {
- padding: 'var(--spacing-4)',
- // Body fills the remaining vertical space below the image so
- // descriptions of different lengths don't push the "Learn more"
- // button to different vertical positions across cards.
- flex: 1,
- display: 'flex',
- flexDirection: 'column' as const,
- },
- cardStack: {
- // Card content stack fills the card height so cardBody (flex:1)
- // can stretch — without this the stack collapses to its content
- // height and the body doesn't have room to grow.
- height: '100%',
- },
- cardDescription: {
- // Pushes the bottom action row (quantity + Add to cart) to the
- // bottom of the card by absorbing any extra vertical space, so
- // every card's action row aligns horizontally regardless of
- // description length.
- flex: 1,
- },
- // Compact quantity stepper to the left of the Add to cart button.
- // Capped width keeps the stepper from competing with the button
- // for the row's horizontal space.
- quantityInput: {
- width: 40,
- flexShrink: 0,
- },
- // Cart button grows to fill the remaining row width next to the
- // quantity stepper so the action stays the dominant target.
- cartButton: {
- flex: 1,
- },
- heroText: {
- textAlign: 'center' as const,
- maxWidth: 560,
- },
- content: {
- maxWidth: 960,
- marginInline: 'auto',
- },
- // Fluid mode used by the theme playground. Caps the showcase at
- // a sensible max-width so the product grid (3 cards at 240px min +
- // 16px gap) fills the container naturally — wider caps left a
- // gutter of unused space on the trailing edge because XDSGrid's
- // auto-fill column algorithm pads tracks to the start of the row.
- // Stays centered via the base `content` rule's marginInline:auto.
- contentFluid: {
- maxWidth: 880,
- },
- // Center-align the text inside each product card. The parent VStack
- // pinches block-level children to the centre via hAlign="center",
- // but heading/description text still anchors to the start of its
- // own block unless `text-align: center` is applied. We use a
- // stylex rule instead of the XDSHeading/XDSText `justify` prop
- // because the docsite consumes the published @xds/core build,
- // which doesn't expose `justify` yet.
- centerText: {
- textAlign: 'center',
- },
-});
-
-// Keys into the active ThemeImageSet, in the same order as PRODUCTS.
-// The actual URLs are resolved per-theme via the `images` prop.
-const PRODUCT_IMAGE_KEYS: ReadonlyArray<keyof ThemeImageSet> = [
- 'watch',
- 'headphones',
- 'backpack',
-];
-
-const PRODUCTS = [
- {
- name: 'Minimalist Watch',
- description: 'Clean design meets everyday durability.',
- badge: 'New',
- badgeVariant: 'blue' as const,
- },
- {
- name: 'Wireless Headphones',
- description: 'Immersive sound, all-day comfort.',
- badge: 'Popular',
- badgeVariant: 'green' as const,
- },
- {
- name: 'Canvas Backpack',
- description: 'Water-resistant canvas with a quiet, modern profile.',
- badge: 'Limited',
- badgeVariant: 'yellow' as const,
- },
-];
-
-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,
- fluid = false,
-}: ThemeShowcasePreviewProps) {
- return (
- <div data-theme-preview="true">
- <XDSVStack gap={0}>
- {/* Fake app top nav — sits at the top of the preview so the
- surface reads like a real product chrome (brand · primary
- nav · actions) rather than a bare design canvas. The
- brand wordmark, nav items, and end-content actions stay
- generic so the same nav makes sense across every theme
- (neutral, butter, y2k, stone, etc.). */}
- <XDSTopNav
- label="Theme preview navigation"
- heading={<XDSTopNavHeading heading="Studio" />}
- centerContent={
- <>
- <XDSTopNavItem label="Shop" href="#" isSelected />
- <XDSTopNavItem label="New In" href="#" />
- <XDSTopNavItem label="Stories" href="#" />
- <XDSTopNavItem label="Help" href="#" />
- </>
- }
- endContent={
- <XDSHStack gap={2} vAlign="center">
- <XDSHStack gap={0.5}>
- <XDSButton
- label="Search"
- tooltip="Search"
- variant="ghost"
- isIconOnly
- icon={<Search size={20} />}
- href="#"
- />
- <XDSButton
- label="Account"
- tooltip="Account"
- variant="ghost"
- isIconOnly
- icon={<User size={20} />}
- href="#"
- />
- <XDSButton
- label="Cart"
- tooltip="Cart"
- variant="ghost"
- isIconOnly
- icon={<ShoppingBag size={20} />}
- href="#"
- />
- </XDSHStack>
- <XDSButton label="Sign in" variant="primary" href="#" />
- </XDSHStack>
- }
- />
-
- <XDSSection padding={8} variant="transparent">
- <XDSVStack
- gap={10}
- xstyle={
- fluid ? [styles.content, styles.contentFluid] : styles.content
- }>
- <XDSCenter>
- <XDSVStack gap={4} hAlign="center" xstyle={styles.heroText}>
- <XDSText type="display-3">
- Little joys,
- <br />
- everywhere you go
- </XDSText>
- <XDSText type="body" color="secondary">
- We believe the smallest details are the ones that matter most.
- Turn an ordinary day into something worth remembering.
- </XDSText>
- </XDSVStack>
- </XDSCenter>
-
- <XDSGrid columns={{minWidth: 240}} gap={4}>
- {PRODUCTS.map((p, i) => (
- <XDSCard key={p.name} padding={0} height="100%">
- <XDSVStack gap={0} xstyle={styles.cardStack}>
- <XDSAspectRatio ratio={1}>
- <img
- src={images[PRODUCT_IMAGE_KEYS[i]]}
- alt={p.name}
- {...stylex.props(styles.productImage)}
- />
- </XDSAspectRatio>
- <div {...stylex.props(styles.cardBody)}>
- <XDSVStack
- gap={2}
- hAlign="center"
- xstyle={styles.cardStack}>
- <XDSHStack>
- <XDSBadge label={p.badge} variant={p.badgeVariant} />
- </XDSHStack>
- <XDSHeading level={2} xstyle={styles.centerText}>
- {p.name}
- </XDSHeading>
- <XDSText
- type="supporting"
- color="secondary"
- xstyle={[styles.cardDescription, styles.centerText]}>
- {p.description}
- </XDSText>
- <XDSHStack gap={2} vAlign="center" hAlign="center">
- <XDSNumberInput
- label="Quantity"
- isLabelHidden
- value={1}
- onChange={() => {}}
- min={1}
- max={99}
- size="sm"
- xstyle={styles.quantityInput}
- />
- <XDSButton
- label="Add to cart"
- variant="secondary"
- href="#"
- xstyle={styles.cartButton}
- />
- </XDSHStack>
- </XDSVStack>
- </div>
- </XDSVStack>
- </XDSCard>
- ))}
- </XDSGrid>
- </XDSVStack>
- </XDSSection>
- </XDSVStack>
- </div>
- );
-}
diff --git a/apps/docsite/src/components/themeImages.ts b/apps/docsite/src/components/themeImages.ts
deleted file mode 100644
index 8bff64b5a3..0000000000
--- a/apps/docsite/src/components/themeImages.ts
+++ /dev/null
@@ -1,67 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-/**
- * Per-theme product image registry.
- *
- * Each theme can ship its own set of 6 product photos (watch, headphones,
- * backpack, wallet, mug, throw). These images appear in two places on the
- * dedicated /themes/<name> page:
- *
- * 1. ThemeShowcasePreview — the live themed fake "Studio" app, where the
- * first three (watch, headphones, backpack) render as 1:1 product
- * card photos.
- * 2. ThemeCardShowcase — the inventory table thumbnails, which use all
- * six.
- *
- * Adding photos for a new theme:
- * 1. Drop the 6 PNGs into public/<theme-slug>/preview-<item>.png
- * 2. Add an entry to THEME_IMAGES below pointing at those paths
- * 3. That's it — both consumers pick them up automatically
- *
- * Themes not listed in THEME_IMAGES fall back to the neutral image set,
- * so the page never has missing thumbnails — just the most neutral
- * possible product photos until a bespoke set lands.
- */
-
-export interface ThemeImageSet {
- watch: string;
- headphones: string;
- backpack: string;
- wallet: string;
- mug: string;
- throw_: string;
-}
-
-const NEUTRAL_IMAGES: ThemeImageSet = {
- watch: '/neutral/preview-watch.png',
- headphones: '/neutral/preview-headphones.png',
- backpack: '/neutral/preview-backpack.png',
- wallet: '/neutral/preview-wallet.png',
- mug: '/neutral/preview-mug.png',
- throw_: '/neutral/preview-throw.png',
-};
-
-/**
- * Per-theme image overrides. Keyed by theme name (matches XDSDefinedTheme.name
- * and the slug used in /themes/<slug> URLs). Themes not listed here fall back
- * to the neutral set via getThemeImages().
- *
- * To add a new theme:
- * 1. Drop images into public/<theme-name>/preview-*.png
- * 2. Add an entry below:
- * butter: {
- * watch: '/butter/preview-watch.png',
- * ...etc
- * }
- */
-const THEME_IMAGES: Record<string, ThemeImageSet> = {
- neutral: NEUTRAL_IMAGES,
-};
-
-/**
- * Resolve the image set for a theme name. Falls back to NEUTRAL_IMAGES for
- * themes that don't have their own image set yet.
- */
-export function getThemeImages(themeName: string): ThemeImageSet {
- return THEME_IMAGES[themeName] ?? NEUTRAL_IMAGES;
-}
diff --git a/apps/docsite/src/components/themePlayground/ComponentPreview.tsx b/apps/docsite/src/components/themePlayground/ComponentPreview.tsx
deleted file mode 100644
index cd88c52758..0000000000
--- a/apps/docsite/src/components/themePlayground/ComponentPreview.tsx
+++ /dev/null
@@ -1,944 +0,0 @@
-// 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 {CodeExampleBlock} from '../CodeExampleBlock';
-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)'}}>
- <CodeExampleBlock
- 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/EditorSections.tsx b/apps/docsite/src/components/themePlayground/EditorSections.tsx
deleted file mode 100644
index 1a20b5459c..0000000000
--- a/apps/docsite/src/components/themePlayground/EditorSections.tsx
+++ /dev/null
@@ -1,614 +0,0 @@
-// 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/ThemeEditorView.tsx b/apps/docsite/src/components/themePlayground/ThemeEditorView.tsx
deleted file mode 100644
index 38edf15372..0000000000
--- a/apps/docsite/src/components/themePlayground/ThemeEditorView.tsx
+++ /dev/null
@@ -1,766 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-'use client';
-
-import * as React from 'react';
-import * as stylex from '@stylexjs/stylex';
-import {useRouter} from 'next/navigation';
-import {durationVars, easeVars} from '@xds/core/theme/tokens.stylex';
-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 {CodeExampleBlock} from '../CodeExampleBlock';
-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';
-import {trackExport} from '../../lib/analytics';
-
-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;
-}
-
-// First-paint entry animations. Each rule sits in its resting "to"
-// state on the element; the `@starting-style` block declares the
-// "from" state, and a `transition` interpolates between them. The
-// browser runs the transition exactly once — on first paint, the
-// element's initial computed style comes from @starting-style; on
-// the very next frame it resolves to the rule's normal style and
-// the transition plays. No JS coordination, no cross-page flag,
-// no race conditions: each mount of this view animates in, period.
-//
-// Motion tokens (--duration-medium + --ease-standard) keep the
-// entry in sync with the rest of XDS. prefers-reduced-motion
-// shortens the transition to ~0 so reduced-motion users get an
-// instant resolve instead of a noticeable slide / scale.
-const entryStyles = stylex.create({
- // Editor panel slides in from the left. Mirrors the leave-side
- // sidebar animation on /themes so the two halves chain into a
- // single "panel swap" rather than reading as a hard cut.
- editor: {
- transform: 'translateX(0)',
- opacity: 1,
- transitionProperty: 'transform, opacity',
- transitionDuration: {
- default: durationVars['--duration-medium'],
- '@media (prefers-reduced-motion: reduce)': '0.01ms',
- },
- transitionTimingFunction: easeVars['--ease-standard'],
- '@starting-style': {
- transform: 'translateX(-100%)',
- opacity: 0,
- },
- },
- // Preview entry — scale + fade. Starts at 95% scale to mirror the
- // canonical XDS layerAnimations pattern (used for popovers, dropdown
- // menus, hover cards, tooltips). Reads as the preview "settling
- // into place" rather than just fading in flat. transform-origin
- // stays at the default 50% 50% so the scale-up reads as growing
- // outward from the preview's visual center.
- preview: {
- transform: 'scale(1)',
- opacity: 1,
- transitionProperty: 'transform, opacity',
- transitionDuration: {
- default: durationVars['--duration-medium'],
- '@media (prefers-reduced-motion: reduce)': '0.01ms',
- },
- transitionTimingFunction: easeVars['--ease-standard'],
- '@starting-style': {
- transform: 'scale(0.95)',
- opacity: 0,
- },
- },
-});
-
-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
- {...stylex.props(entryStyles.editor)}
- 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"
- tooltip="Back to all themes"
- 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
- {...stylex.props(entryStyles.preview)}
- 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={() => {
- trackExport({page: 'themes', item: selectedThemeId});
- 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>
- <CodeExampleBlock
- code={themeCode}
- language="typescript"
- size="sm"
- />
- </XDSVStack>
-
- <XDSVStack gap={2}>
- <XDSText type="label">2. Wrap your app with the theme</XDSText>
- <CodeExampleBlock 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.tsx
deleted file mode 100644
index 986749089a..0000000000
--- a/apps/docsite/src/components/themePlayground/TokenRow.tsx
+++ /dev/null
@@ -1,50 +0,0 @@
-// 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.tsx
deleted file mode 100644
index 81cfbb50db..0000000000
--- a/apps/docsite/src/components/themePlayground/TokenScalePreview.tsx
+++ /dev/null
@@ -1,251 +0,0 @@
-// 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/themeList.ts b/apps/docsite/src/components/themePlayground/themeList.ts
deleted file mode 100644
index 2f54923944..0000000000
--- a/apps/docsite/src/components/themePlayground/themeList.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-// 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 {themeObjectsFull} from '../../generated/themeRegistry';
-
-export interface ThemeListEntry {
- name: string;
- label: string;
- theme: XDSDefinedTheme;
-}
-
-export function getThemeList(): ThemeListEntry[] {
- return Object.values(themeObjectsFull)
- .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/lib/analytics.ts b/apps/docsite/src/lib/analytics.ts
index d2fd3c50e0..202ed71705 100644
--- a/apps/docsite/src/lib/analytics.ts
+++ b/apps/docsite/src/lib/analytics.ts
@@ -114,8 +114,3 @@ export function trackToggle(
) {
track('toggle', props(p));
}
-
-/** Theme exported. */
-export function trackExport(p: BaseProps) {
- track('export', props(p));
-}