An open source design system that's fully customizable and agent ready
TypeScript
feat(docsite): polish playground — theming, preview centering, fullscreen, system mode (#2448)
Ernest3738631d5e0d
diff --git a/apps/docsite/src/app/(preview)/playground-preview/page.tsx b/apps/docsite/src/app/(preview)/playground-preview/page.tsxindex a40278c7c7..5376fd7e74 100644--- a/apps/docsite/src/app/(preview)/playground-preview/page.tsx+++ b/apps/docsite/src/app/(preview)/playground-preview/page.tsx@@ -5,25 +5,29 @@import React, {useCallback,useEffect,+ useLayoutEffect,useRef,useState,+ type CSSProperties,type ErrorInfo,type ReactNode,} from 'react';import {XDSTheme} from '@xds/core/theme';-import type {XDSDefinedTheme} from '@xds/core/theme';import type {ThemeMode} from '@xds/core/theme';-import {defaultTheme} from '@xds/theme-default/built';-import {neutralTheme} from '@xds/theme-neutral/built';-import {matchaTheme} from '@xds/theme-matcha/built';+import {+ themeByValue,+ DEFAULT_PLAYGROUND_THEME,+} from '../../playground/playgroundThemes';import {runCode, setTypeScript} from './runner';import type * as TS from 'typescript';-const THEME_MAP: Record<string, XDSDefinedTheme> = {- default: defaultTheme,- neutral: neutralTheme,- matcha: matchaTheme,-};+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;@@ -122,10 +126,16 @@ 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');+ const [themeName, setThemeName] = useState(DEFAULT_PLAYGROUND_THEME);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@@ -143,7 +153,7 @@ export default function PreviewPage() {document.head.appendChild(script);}, []);- const theme = THEME_MAP[themeName] ?? defaultTheme;+ const theme = themeByValue[themeName] ?? FALLBACK_THEME;const postToParent = useCallback((msg: Record<string, unknown>) => {window.parent.postMessage(msg, '*');@@ -155,6 +165,9 @@ export default function PreviewPage() {if (result.Component) {setComponent(() => result.Component);setError(null);+ // Reset to fill so the next measurement runs against natural (block+ // flow) sizing rather than a previously-centered layout.+ setFill(true);setResetKey(k => k + 1);postToParent({type: 'preview-rendered'});} else {@@ -179,7 +192,7 @@ export default function PreviewPage() {if (msg.mode === 'light' || msg.mode === 'dark' || msg.mode === 'system') {setThemeMode(msg.mode);}- if (msg.theme && msg.theme in THEME_MAP) {+ if (msg.theme && msg.theme in themeByValue) {setThemeName(msg.theme);}}, []);@@ -223,6 +236,21 @@ export default function PreviewPage() {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({@@ -234,18 +262,36 @@ export default function PreviewPage() {[postToParent],);+ const stageStyle: CSSProperties = fill+ ? {+ minHeight: '100%',+ display: 'block',+ backgroundColor: 'var(--color-background-body)',+ }+ : {+ minHeight: '100%',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ padding: 'var(--spacing-4, 16px)',+ boxSizing: 'border-box',+ backgroundColor: 'var(--color-background-body)',+ };++ // In fill mode the wrapper has no box (display: contents) so the rendered+ // root participates directly in block flow and fills width/height naturally.+ const contentStyle: CSSProperties = fill ? {display: 'contents'} : {};+return (<XDSTheme theme={theme} mode={themeMode}>- <div- style={{- minHeight: '100%',- backgroundColor: 'var(--color-background-body)',- }}>+ <div ref={stageRef} style={stageStyle}>{error && <ErrorDisplay message={error} />}{Component && (- <ErrorBoundary resetKey={resetKey} onError={handleBoundaryError}>- <Component />- </ErrorBoundary>+ <div ref={contentRef} style={contentStyle}>+ <ErrorBoundary resetKey={resetKey} onError={handleBoundaryError}>+ <Component />+ </ErrorBoundary>+ </div>)}</div></XDSTheme>diff --git a/apps/docsite/src/app/playground/PlaygroundClient.tsx b/apps/docsite/src/app/playground/PlaygroundClient.tsxindex 0531131f80..8f945908f4 100644--- a/apps/docsite/src/app/playground/PlaygroundClient.tsx+++ b/apps/docsite/src/app/playground/PlaygroundClient.tsx@@ -52,6 +52,11 @@ import {} from '@heroicons/react/24/outline';import githubLight from './themes/github-light.json';import githubDark from './themes/github-dark.json';+import {useThemeMode} from '../providers';+import {+ PLAYGROUND_THEME_OPTIONS,+ DEFAULT_PLAYGROUND_THEME,+} from './playgroundThemes';import {PreviewStage, type Viewport} from './PreviewStage';import {PropertyPanel} from './PropertyPanel';import {annotateInstanceIds} from './babelParser';@@ -158,12 +163,6 @@ function updateURL(code: string) {window.history.replaceState(null, '', `#code=${compressed}`);}-const THEME_OPTIONS = [- {value: 'default', label: 'Default'},- {value: 'neutral', label: 'Neutral'},- {value: 'matcha', label: 'Matcha'},-];-/*** Configure Monaco's TypeScript service with real XDS type definitions.* Loads .d.ts files from a pre-built JSON bundle (generated at build time).@@ -333,8 +332,12 @@ const s = stylex.create({export function PlaygroundClient() {const router = useRouter();+ // The editor chrome follows the docsite's own light/dark mode, not the OS+ // (operator) color-scheme preference.+ const {mode: siteMode} = useThemeMode();+ const editorTheme = siteMode === 'dark' ? 'github-dark' : 'github-light';const [code, setCode] = useState(getInitialCode);- const [theme, setTheme] = useState('neutral');+ const [theme, setTheme] = useState(DEFAULT_PLAYGROUND_THEME);const [mode, setMode] = useState<'light' | 'dark'>('light');const [activeTab, setActiveTab] = useState<LeftTab>('code');const [viewport, setViewport] = useState<Viewport>('desktop');@@ -344,7 +347,6 @@ export function PlaygroundClient() {const [statusFading, setStatusFading] = useState(false);const [copied, setCopied] = useState(false);const [previewReady, setPreviewReady] = useState(false);- const [editorTheme, setEditorTheme] = useState('github-dark');// The code the playground was seeded with (a shared/example snippet from the// URL hash, or the default). Reset restores this — not the hardcoded default.@@ -368,16 +370,14 @@ export function PlaygroundClient() {autoSaveId: 'xds-playground-left-width',});- // Sync editor + initial preview mode with system preference+ // 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.+ const initialSiteModeRef = useRef(siteMode);useEffect(() => {- const mq = window.matchMedia('(prefers-color-scheme: dark)');- const update = () => {- setEditorTheme(mq.matches ? 'github-dark' : 'github-light');- setMode(mq.matches ? 'dark' : 'light');- };- update();- mq.addEventListener('change', update);- return () => mq.removeEventListener('change', update);+ setMode(initialSiteModeRef.current);}, []);// Re-read code from hash on hashchange (e.g. SPA navigation with new code)@@ -690,7 +690,7 @@ export function PlaygroundClient() {<XDSSelectorlabel="Theme"isLabelHidden- options={THEME_OPTIONS}+ options={PLAYGROUND_THEME_OPTIONS}value={theme}onChange={setTheme}size="md"diff --git a/apps/docsite/src/app/playground/PreviewStage.tsx b/apps/docsite/src/app/playground/PreviewStage.tsxindex 20c9158634..4b3e8663da 100644--- a/apps/docsite/src/app/playground/PreviewStage.tsx+++ b/apps/docsite/src/app/playground/PreviewStage.tsx@@ -46,7 +46,15 @@ const s = stylex.create({position: 'fixed',inset: 0,zIndex: 50,- padding: 'var(--spacing-4)',+ padding: 0,+ },+ // In fullscreen the card chrome (radius, border, shadow) is stripped so the+ // preview reads as a bare, edge-to-edge surface. The element stays mounted to+ // preserve the single iframe + its postMessage channel.+ cardFullscreen: {+ borderRadius: 0,+ borderWidth: 0,+ boxShadow: 'none',},card: {maxWidth: '100%',@@ -122,7 +130,10 @@ export function PreviewStage({</XDSCard></div>)}- <XDSCard padding={0} xstyle={s.card} style={{width, height}}>+ <XDSCard+ padding={0}+ xstyle={[s.card, isFullscreen && s.cardFullscreen]}+ style={{width, height}}><iframeref={iframeRef}src="/playground-preview"diff --git a/apps/docsite/src/app/playground/playgroundThemes.ts b/apps/docsite/src/app/playground/playgroundThemes.tsnew file mode 100644index 0000000000..3d84ebd6e9--- /dev/null+++ b/apps/docsite/src/app/playground/playgroundThemes.ts@@ -0,0 +1,65 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file playgroundThemes.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.+ *+ * Derived entirely from the docsite's generated registries, so any official+ * @xds/theme-* package installed on the docsite automatically shows up in the+ * playground theme selector (and resolves in the preview) with no code change.+ */++import type {XDSDefinedTheme} from '@xds/core/theme';+import {themeObjects} from '../../generated/themeRegistry';+import {packages} from '../../generated/packageRegistry';++export interface PlaygroundTheme {+ /** Short, stable key used as the selector value + postMessage payload. */+ value: string;+ /** Human-readable label shown in the selector. */+ label: string;+ /** The resolved theme object passed to <XDSTheme>. */+ theme: XDSDefinedTheme;+}++const displayNameByPackage = new Map(packages.map(p => [p.name, p.displayName]));++/** "@xds/theme-default" → "default" */+function toShortName(packageName: string): string {+ return packageName.replace(/^@xds\/theme-/, '');+}++/**+ * Produce a clean label. Package displayNames are inconsistent+ * ("Default Theme", "Theme: matcha", "Gothic Theme") — strip the "theme"+ * noise and title-case, falling back to the short package name.+ */+function toLabel(packageName: string, shortName: string): string {+ const display = displayNameByPackage.get(packageName);+ const cleaned = display?.replace(/theme:?/gi, '').trim();+ const base = cleaned || shortName;+ return base.charAt(0).toUpperCase() + base.slice(1);+}++export const PLAYGROUND_THEMES: PlaygroundTheme[] = Object.entries(themeObjects)+ .map(([packageName, theme]) => {+ const value = toShortName(packageName);+ return {value, label: toLabel(packageName, value), theme};+ })+ .sort((a, b) => a.label.localeCompare(b.label));++export const PLAYGROUND_THEME_OPTIONS = PLAYGROUND_THEMES.map(+ ({value, label}) => ({value, label}),+);++export const themeByValue: Record<string, XDSDefinedTheme> = Object.fromEntries(+ PLAYGROUND_THEMES.map(t => [t.value, t.theme]),+);++/** Preferred initial theme — neutral if present, else the first available. */+export const DEFAULT_PLAYGROUND_THEME =+ PLAYGROUND_THEMES.find(t => t.value === 'neutral')?.value ??+ PLAYGROUND_THEMES[0]?.value ??+ 'default';diff --git a/apps/docsite/src/app/playground/themes/github-dark.json b/apps/docsite/src/app/playground/themes/github-dark.jsonindex b6225a85a5..f3e45232de 100644--- a/apps/docsite/src/app/playground/themes/github-dark.json+++ b/apps/docsite/src/app/playground/themes/github-dark.json@@ -3,7 +3,6 @@"inherit": true,"rules": [{- "background": "24292e","token": ""},{@@ -335,10 +334,12 @@],"colors": {"editor.foreground": "#f6f8fa",- "editor.background": "#24292e",+ "editor.background": "#00000000",+ "editorGutter.background": "#00000000",+ "minimap.background": "#00000000","editor.selectionBackground": "#4c2889",- "editor.inactiveSelectionBackground": "#444d56",- "editor.lineHighlightBackground": "#444d56",+ "editor.inactiveSelectionBackground": "#444d5680",+ "editor.lineHighlightBackground": "#ffffff0d","editorCursor.foreground": "#ffffff","editorWhitespace.foreground": "#6a737d","editorIndentGuide.background": "#6a737d",diff --git a/apps/docsite/src/app/providers.tsx b/apps/docsite/src/app/providers.tsxindex 641324a3ed..5945b39b71 100644--- a/apps/docsite/src/app/providers.tsx+++ b/apps/docsite/src/app/providers.tsx@@ -2,7 +2,7 @@'use client';-import {createContext, useContext, useState} from 'react';+import {createContext, useContext, useEffect, useState} from 'react';import Link from 'next/link';import {XDSTheme} from '@xds/core/theme';import {XDSLinkProvider} from '@xds/core/Link';@@ -23,9 +23,28 @@ export function useThemeMode() {}export function Providers({children}: {children: React.ReactNode}) {+ // Default to the OS color scheme. SSR/first paint use a deterministic 'light'+ // default (so hydration matches); the effect syncs to the real system+ // preference on mount and tracks live changes — until the user manually+ // toggles, after which their choice sticks for the rest of the session.const [mode, setMode] = useState<ThemeMode>('light');-- const toggleMode = () => setMode(m => (m === 'light' ? 'dark' : 'light'));+ const [isManual, setIsManual] = useState(false);++ useEffect(() => {+ if (isManual) {+ return;+ }+ const mq = window.matchMedia('(prefers-color-scheme: dark)');+ const sync = () => setMode(mq.matches ? 'dark' : 'light');+ sync();+ mq.addEventListener('change', sync);+ return () => mq.removeEventListener('change', sync);+ }, [isManual]);++ const toggleMode = () => {+ setIsManual(true);+ setMode(m => (m === 'light' ? 'dark' : 'light'));+ };return (<ThemeModeContext value={{mode, toggleMode}}>diff --git a/apps/docsite/src/themes/astryxTheme.ts b/apps/docsite/src/themes/astryxTheme.tsindex 16c46c94ab..d2aa22db74 100644--- a/apps/docsite/src/themes/astryxTheme.ts+++ b/apps/docsite/src/themes/astryxTheme.ts@@ -32,7 +32,10 @@ export const astryxTheme = defineTheme({'--color-icon-accent': 'light-dark(#292724, #E8E3DA)','--color-accent-muted':'light-dark(rgba(41, 39, 36, 0.12), rgba(232, 227, 218, 0.16))',- '--color-background-body': '#F8F4ED',+ // Mode-aware so the page background flips with dark mode. Light keeps the+ // warm Astryx cream; dark falls back to the XDS default body color+ // (a flat static value here would freeze the page in light mode).+ '--color-background-body': 'light-dark(#F8F4ED, #111112)',// Astryx display headings render semibold (XDS default is normal weight).'--text-display-1-weight': 'var(--font-weight-semibold)','--text-display-2-weight': 'var(--font-weight-semibold)',