An open source design system that's fully customizable and agent ready
TypeScript
feat(docsite): redesign playground (#2428)
Ernest96b5bcf642b8
diff --git a/apps/docsite/.gitignore b/apps/docsite/.gitignoreindex d4595b7de3..94f7146525 100644--- a/apps/docsite/.gitignore+++ b/apps/docsite/.gitignore@@ -7,6 +7,11 @@ src/generated/# Auto-generated by scripts/generate-playground-types.mjspublic/playground-types.json+# Self-hosted vendor assets copied by scripts/copy-vendor.mjs+# (Monaco editor + the in-browser TypeScript compiler; regenerated on build)+public/monaco/+public/vendor/+# Auto-generated by `xds theme build` (pnpm build:theme). The theme source# lives at src/themes/astryxTheme.ts; the built JS/CSS/d.ts files are# regenerated locally and in CI before next dev / next build.diff --git a/apps/docsite/package.json b/apps/docsite/package.jsonindex 9ede02104a..b99729cac1 100644--- a/apps/docsite/package.json+++ b/apps/docsite/package.json@@ -4,7 +4,7 @@"private": true,"scripts": {"build:theme": "xds theme build src/themes/astryxTheme.ts --out src/themes/astryx.css",- "generate": "pnpm build:theme && node scripts/generate-data.mjs && node scripts/generate-playground-types.mjs",+ "generate": "pnpm build:theme && node scripts/generate-data.mjs && node scripts/generate-playground-types.mjs && node scripts/copy-vendor.mjs","dev": "pnpm generate && next dev","build": "pnpm generate && next build","start": "next start",diff --git a/apps/docsite/scripts/copy-vendor.mjs b/apps/docsite/scripts/copy-vendor.mjsnew file mode 100644index 0000000000..87d67de242--- /dev/null+++ b/apps/docsite/scripts/copy-vendor.mjs@@ -0,0 +1,46 @@+#!/usr/bin/env node+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * Copies third-party browser assets into public/ so the playground can run+ * fully self-hosted (corpnet blocks external CDNs like jsdelivr / unpkg):+ *+ * - monaco-editor/min/vs -> public/monaco/vs (Monaco AMD loader + workers)+ * - typescript/lib/typescript.js -> public/vendor/typescript.js (in-browser TSX transpile + AST)+ *+ * Idempotent: skips files that already exist. Run as part of `generate`.+ */++import {createRequire} from 'module';+import {cpSync, copyFileSync, existsSync, mkdirSync, statSync} from 'fs';+import {join, dirname} from 'path';+import {fileURLToPath} from 'url';++const require = createRequire(import.meta.url);+const __dirname = dirname(fileURLToPath(import.meta.url));+const publicDir = join(__dirname, '..', 'public');++// --- Monaco editor (min/vs) ---+const monacoPkg = require.resolve('monaco-editor/package.json');+const monacoVs = join(dirname(monacoPkg), 'min', 'vs');+const monacoDest = join(publicDir, 'monaco', 'vs');+if (existsSync(join(monacoDest, 'loader.js'))) {+ console.log('monaco: already present at public/monaco/vs — skipping');+} else {+ mkdirSync(dirname(monacoDest), {recursive: true});+ cpSync(monacoVs, monacoDest, {recursive: true});+ console.log('monaco: copied min/vs -> public/monaco/vs');+}++// --- TypeScript (browser UMD) ---+const tsLib = require.resolve('typescript/lib/typescript.js');+const tsDest = join(publicDir, 'vendor', 'typescript.js');+if (existsSync(tsDest) && statSync(tsDest).size === statSync(tsLib).size) {+ console.log(+ 'typescript: already present at public/vendor/typescript.js — skipping',+ );+} else {+ mkdirSync(dirname(tsDest), {recursive: true});+ copyFileSync(tsLib, tsDest);+ console.log('typescript: copied -> public/vendor/typescript.js');+}diff --git a/apps/docsite/src/app/(preview)/playground-preview/layout.tsx b/apps/docsite/src/app/(preview)/playground-preview/layout.tsxindex 0a71e51255..88cd1effad 100644--- a/apps/docsite/src/app/(preview)/playground-preview/layout.tsx+++ b/apps/docsite/src/app/(preview)/playground-preview/layout.tsx@@ -3,7 +3,22 @@export default function PreviewLayout({children}: {children: React.ReactNode}) {return (<>- <style>{`html, body { height: 100%; margin: 0; }`}</style>+ <style>{`+ html, body { height: 100%; margin: 0; }+ @keyframes pg-flash-ring {+ 0% { outline-color: var(--color-border-focus, #1877f2); }+ 100% { outline-color: rgba(24, 119, 242, 0); }+ }+ .pg-flash {+ outline: 3px solid var(--color-border-focus, #1877f2);+ outline-offset: 2px;+ border-radius: var(--radius-element, 6px);+ animation: pg-flash-ring 1s ease forwards;+ }+ @media (prefers-reduced-motion: reduce) {+ .pg-flash { animation-duration: 0.01ms; }+ }+ `}</style>{children}</>);diff --git a/apps/docsite/src/app/(preview)/playground-preview/page.tsx b/apps/docsite/src/app/(preview)/playground-preview/page.tsxindex e5d5926fba..a40278c7c7 100644--- a/apps/docsite/src/app/(preview)/playground-preview/page.tsx+++ b/apps/docsite/src/app/(preview)/playground-preview/page.tsx@@ -16,7 +16,8 @@ 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 {runCode, setBabel} from './runner';+import {runCode, setTypeScript} from './runner';+import type * as TS from 'typescript';const THEME_MAP: Record<string, XDSDefinedTheme> = {default: defaultTheme,@@ -91,7 +92,22 @@ type PreviewMessage =| {type: 'preview-ping'}| {type: 'preview-code'; code: string}| {type: 'preview-clear'}- | {type: 'preview-theme'; mode?: string; theme?: string};+ | {type: 'preview-theme'; mode?: string; theme?: string}+ | {type: 'preview-highlight'; id: string};++/** Briefly flash a focus ring on the element marked with the given data-pg-id. */+function flashElement(id: string) {+ const el = document.querySelector<HTMLElement>(`[data-pg-id="${id}"]`);+ if (!el) {+ return;+ }+ el.classList.remove('pg-flash');+ // Force reflow so re-adding the class restarts the animation.+ void el.offsetWidth;+ el.classList.add('pg-flash');+ el.scrollIntoView({block: 'nearest', behavior: 'smooth'});+ window.setTimeout(() => el.classList.remove('pg-flash'), 1000);+}function isPreviewMessage(data: unknown): data is PreviewMessage {return (@@ -108,18 +124,20 @@ export default function PreviewPage() {const [themeMode, setThemeMode] = useState<ThemeMode>('system');const [themeName, setThemeName] = useState('default');const [resetKey, setResetKey] = useState(0);- const [babelReady, setBabelReady] = useState(false);+ const [tsReady, setTsReady] = useState(false);const readyRef = useRef(false);- // Load Babel from CDN — avoids bundling the 5MB package through Next.js+ // 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 = 'https://unpkg.com/@babel/standalone@7/babel.min.js';+ script.src = '/vendor/typescript.js';script.onload = () => {- const w = window as unknown as Record<string, unknown>;- if (w.Babel) {- setBabel(w.Babel as Parameters<typeof setBabel>[0]);- setBabelReady(true);+ const w = window as unknown as {ts?: typeof TS};+ if (w.ts) {+ setTypeScript(w.ts);+ setTsReady(true);}};document.head.appendChild(script);@@ -167,7 +185,7 @@ export default function PreviewPage() {}, []);useEffect(() => {- if (!babelReady) {+ if (!tsReady) {return;}@@ -189,6 +207,9 @@ export default function PreviewPage() {case 'preview-theme':handleTheme(event.data);break;+ case 'preview-highlight':+ flashElement(event.data.id);+ break;}}@@ -200,7 +221,7 @@ export default function PreviewPage() {}return () => window.removeEventListener('message', onMessage);- }, [babelReady, postToParent, handleCode, handleClear, handleTheme]);+ }, [tsReady, postToParent, handleCode, handleClear, handleTheme]);const handleBoundaryError = useCallback((err: Error) => {@@ -215,7 +236,11 @@ export default function PreviewPage() {return (<XDSTheme theme={theme} mode={themeMode}>- <div style={{minHeight: '100%', padding: 24}}>+ <div+ style={{+ minHeight: '100%',+ backgroundColor: 'var(--color-background-body)',+ }}>{error && <ErrorDisplay message={error} />}{Component && (<ErrorBoundary resetKey={resetKey} onError={handleBoundaryError}>diff --git a/apps/docsite/src/app/(preview)/playground-preview/runner.ts b/apps/docsite/src/app/(preview)/playground-preview/runner.tsindex 4695dbd1e7..0bfb88e12f 100644--- a/apps/docsite/src/app/(preview)/playground-preview/runner.ts+++ b/apps/docsite/src/app/(preview)/playground-preview/runner.ts@@ -1,28 +1,28 @@// Copyright (c) Meta Platforms, Inc. and affiliates.-import {scope} from './scope';--interface BabelStandalone {- transform(code: string, options: Record<string, unknown>): {code: string};-}+/**+ * @file runner.ts+ * @input User TSX source + the in-browser TypeScript compiler+ * @output A live React component (or a structured error)+ * @position Playground preview iframe — compiles & evaluates user code.+ *+ * Transpiles TSX → CommonJS with the self-hosted TypeScript compiler+ * (window.ts, served from /vendor/typescript.js — corpnet blocks CDNs), then+ * evaluates it with a custom `require` mapped to the preview scope plus a+ * global scope so unimported React hooks / XDS components still resolve.+ */-/** Set by the page after loading Babel from CDN */-let Babel: BabelStandalone | null = null;+import type * as TS from 'typescript';+import {scope} from './scope';-export function setBabel(instance: BabelStandalone) {- Babel = instance;-}+/** Set by the page after loading /vendor/typescript.js */+let ts: typeof TS | null = null;-interface ParsedImport {- source: string;- specifiers: Array<{- local: string;- imported: string | null;- type: 'default' | 'named' | 'namespace';- }>;+export function setTypeScript(instance: typeof TS) {+ ts = instance;}-type RunPhase = 'babel' | 'import' | 'runtime';+type RunPhase = 'compile' | 'runtime';type RunResult =| {Component: React.ComponentType; error?: undefined}@@ -36,156 +36,93 @@ for (const [key, value] of Object.entries(scope)) {scopeLookup.set(key.toLowerCase(), value as Record<string, unknown>);}-function compileCode(code: string): {- compiled: string;- imports: ParsedImport[];-} {- const imports: ParsedImport[] = [];-- const importStripper = (): {- visitor: Record<- string,- (path: {node: Record<string, unknown>; remove: () => void}) => void- >;- } => ({- visitor: {- ImportDeclaration(path: {- node: Record<string, unknown>;- remove: () => void;- }) {- const source = (path.node.source as {value: string}).value;- const specifiers: ParsedImport['specifiers'] = [];-- for (const spec of path.node.specifiers as Array<{- type: string;- local: {name: string};- imported?: {name: string};- }>) {- if (spec.type === 'ImportDefaultSpecifier') {- specifiers.push({- local: spec.local.name,- imported: null,- type: 'default',- });- } else if (spec.type === 'ImportNamespaceSpecifier') {- specifiers.push({- local: spec.local.name,- imported: null,- type: 'namespace',- });- } else if (spec.type === 'ImportSpecifier') {- specifiers.push({- local: spec.local.name,- imported: spec.imported?.name ?? spec.local.name,- type: 'named',- });+/** A CommonJS-style require resolving against the preview scope. */+function makeRequire(): (id: string) => unknown {+ return (id: string) => {+ if (ASSET_RE.test(id)) {+ return {default: '', __esModule: true};+ }+ const mod = scopeLookup.get(id.toLowerCase());+ if (mod) {+ // Mark as an ES module so TS esModuleInterop uses `.default` correctly.+ return (mod as {__esModule?: boolean}).__esModule+ ? mod+ : {...mod, __esModule: true};+ }+ // Unknown module — return placeholders that render nothing.+ return new Proxy(+ {__esModule: true},+ {+ get(_target, prop) {+ if (prop === '__esModule') {+ return true;}- }-- imports.push({source, specifiers});- path.remove();- },- ExpressionStatement(path: {- node: Record<string, unknown>;- remove: () => void;- }) {- const expr = path.node.expression as- | Record<string, unknown>- | undefined;- if (- expr &&- typeof expr === 'object' &&- expr.type === 'StringLiteral' &&- expr.value === 'use client'- ) {- path.remove();- }+ if (typeof prop === 'string') {+ const placeholder = () => null;+ (placeholder as {displayName?: string}).displayName =+ `${id}/${prop}`;+ return placeholder;+ }+ return undefined;+ },},- },- });-- if (Babel == null) {- throw new Error('Babel has not been loaded yet — call setBabel() first');- }-- const result = Babel.transform(code, {- filename: 'playground.tsx',- presets: [- ['typescript', {isTSX: true, allExtensions: true}],- ['react', {runtime: 'classic'}],- ],- plugins: [importStripper, 'transform-modules-commonjs'],- });-- return {compiled: result.code, imports};+ );+ };}-function buildScope(imports: ParsedImport[]): Record<string, unknown> {+/**+ * Build a scope with ALL named exports from every module so React hooks and+ * XDS components are available as globals without an explicit import.+ */+function buildGlobalScope(): Record<string, unknown> {const vars: Record<string, unknown> = {};-- for (const imp of imports) {- if (ASSET_RE.test(imp.source)) {- for (const spec of imp.specifiers) {- vars[spec.local] = '';- }- continue;- }-- const mod = scopeLookup.get(imp.source.toLowerCase());-- if (mod) {- for (const spec of imp.specifiers) {- if (spec.type === 'default') {- vars[spec.local] = mod.default ?? mod;- } else if (spec.type === 'namespace') {- vars[spec.local] = mod;- } else {- vars[spec.local] = mod[spec.imported ?? spec.local];- }- }- } else {- for (const spec of imp.specifiers) {- if (spec.type === 'namespace') {- vars[spec.local] = new Proxy(- {},- {- get(_target, prop) {- if (typeof prop === 'string') {- const placeholder = () => null;- placeholder.displayName = `${imp.source}.${prop}`;- return placeholder;- }- return undefined;- },- },- );- } else {- const placeholder = () => null;- placeholder.displayName = `${imp.source}/${spec.local}`;- vars[spec.local] = placeholder;- }+ for (const moduleExports of Object.values(scope)) {+ for (const [name, value] of Object.entries(moduleExports)) {+ if (name !== 'default' && name !== '__esModule') {+ vars[name] = value;}}}-+ // React global for classic JSX (React.createElement).+ vars.React = scope['react']?.default ?? scope['react'];return vars;}-function evaluate(- compiledCode: string,- scopeVars: Record<string, unknown>,-): React.ComponentType {- const exports: Record<string, unknown> = {};- const module = {exports};+function compile(code: string): string {+ if (ts == null) {+ throw new Error(+ 'TypeScript has not been loaded yet — call setTypeScript()',+ );+ }+ const result = ts.transpileModule(code, {+ fileName: 'playground.tsx',+ reportDiagnostics: false,+ compilerOptions: {+ jsx: ts.JsxEmit.React, // emit React.createElement (classic runtime)+ target: ts.ScriptTarget.ES2020,+ module: ts.ModuleKind.CommonJS,+ esModuleInterop: true,+ allowJs: true,+ },+ });+ return result.outputText;+}++function evaluate(compiled: string): React.ComponentType {+ const exportsObj: Record<string, unknown> = {};+ const moduleObj = {exports: exportsObj};+ const requireFn = makeRequire();+ const globals = buildGlobalScope();- const keys = ['module', 'exports', ...Object.keys(scopeVars)];- const values = [module, exports, ...Object.values(scopeVars)];+ const keys = ['module', 'exports', 'require', ...Object.keys(globals)];+ const values = [moduleObj, exportsObj, requireFn, ...Object.values(globals)];- const fn = new Function(...keys, compiledCode);+ const fn = new Function(...keys, compiled);fn(...values);const defaultExport =- (module.exports as Record<string, unknown>).default ?? exports.default;+ (moduleObj.exports as Record<string, unknown>).default ??+ exportsObj.default;if (typeof defaultExport !== 'function') {throw new Error(@@ -196,54 +133,23 @@ function evaluate(return defaultExport as React.ComponentType;}-/**- * Build a scope with ALL exports from every module in the scope map.- * This makes React hooks and XDS components available as globals- * without requiring explicit imports.- */-function buildGlobalScope(): Record<string, unknown> {- const vars: Record<string, unknown> = {};- for (const [, moduleExports] of Object.entries(scope)) {- for (const [name, value] of Object.entries(moduleExports)) {- if (name !== 'default' && name !== '__esModule') {- vars[name] = value;- }- }- }- // Also add React as a global (needed for JSX classic runtime)- vars.React = scope['react']?.default ?? scope['react'];- return vars;-}-export function runCode(code: string): RunResult {- if (!Babel) {- return {error: 'Babel compiler not loaded yet', phase: 'babel'};+ if (!ts) {+ return {error: 'TypeScript compiler not loaded yet', phase: 'compile'};}let compiled: string;- let imports: ParsedImport[];-- try {- ({compiled, imports} = compileCode(code));- } catch (e: unknown) {- return {- error: e instanceof Error ? e.message : String(e),- phase: 'babel',- };- }-- let scopeVars: Record<string, unknown>;try {- scopeVars = {...buildGlobalScope(), ...buildScope(imports)};+ compiled = compile(code);} catch (e: unknown) {return {error: e instanceof Error ? e.message : String(e),- phase: 'import',+ phase: 'compile',};}try {- const Component = evaluate(compiled, scopeVars);+ const Component = evaluate(compiled);return {Component};} catch (e: unknown) {return {diff --git a/apps/docsite/src/app/playground/CraftPanel.tsx b/apps/docsite/src/app/playground/CraftPanel.tsxnew file mode 100644index 0000000000..b78c451cdd--- /dev/null+++ b/apps/docsite/src/app/playground/CraftPanel.tsx@@ -0,0 +1,72 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file CraftPanel.tsx+ * @output Disabled AI "Craft" chat with a coming-soon empty state+ * @position Playground left panel — "Craft" tab (placeholder for future AI).+ */++'use client';++import * as stylex from '@stylexjs/stylex';+import {XDSChatMessageList, XDSChatComposer} from '@xds/core/Chat';+import {XDSEmptyState} from '@xds/core/EmptyState';+import {SparklesIcon} from '@heroicons/react/24/outline';++const s = stylex.create({+ root: {+ display: 'flex',+ flexDirection: 'column',+ height: '100%',+ minHeight: 0,+ overflow: 'hidden',+ },+ list: {+ flex: 1,+ minHeight: 0,+ overflow: 'auto',+ },+ composer: {+ flexShrink: 0,+ padding: 'var(--spacing-3)',+ },+ icon: {+ transform: 'scale(2)',+ display: 'inline-flex',+ color: 'var(--color-text-secondary)',+ paddingBottom: 'var(--spacing-1)',+ },+});++export function CraftPanel() {+ return (+ <div {...stylex.props(s.root)}>+ <XDSChatMessageList+ density="compact"+ xstyle={s.list}+ emptyState={+ <XDSEmptyState+ icon={+ <span aria-hidden="true" {...stylex.props(s.icon)}>+ <SparklesIcon width={24} height={24} />+ </span>+ }+ title="Craft with AI"+ description="This feature is coming later."+ headingLevel={3}+ />+ }>+ {[]}+ </XDSChatMessageList>+ <div {...stylex.props(s.composer)}>+ <XDSChatComposer+ isDisabled+ value=""+ onChange={() => {}}+ onSubmit={() => {}}+ placeholder="Coming soon…"+ />+ </div>+ </div>+ );+}diff --git a/apps/docsite/src/app/playground/PlaygroundClient.tsx b/apps/docsite/src/app/playground/PlaygroundClient.tsxindex 345646813e..0531131f80 100644--- a/apps/docsite/src/app/playground/PlaygroundClient.tsx+++ b/apps/docsite/src/app/playground/PlaygroundClient.tsx@@ -1,9 +1,29 @@// Copyright (c) Meta Platforms, Inc. and affiliates.+/**+ * @file PlaygroundClient.tsx+ * @input URL hash (shared code), user edits, knob edits+ * @output Full-page two-panel playground (editor + live preview)+ * @position app/playground — the interactive XDS code playground.+ *+ * Left panel: back + tabs (Code · Property · Craft).+ * - Code: Monaco editor (controlled) with real XDS .d.ts typedefs.+ * - Property: component selector + instance picker + knobs that edit the code.+ * - Craft: disabled AI chat placeholder.+ * Right panel: toolbar (theme + dark mode · viewport segmented control ·+ * expand · reset · share) over a responsive /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,+ * the Property knobs, the URL hash, and the preview.+ */+'use client';import {useCallback, useEffect, useMemo, useRef, useState} from 'react';import dynamic from 'next/dynamic';+import {loader} from '@monaco-editor/react';+import {useRouter} from 'next/navigation';import * as stylex from '@stylexjs/stylex';import {compressToEncodedURIComponent,@@ -14,13 +34,36 @@ import {XDSSelector} from '@xds/core/Selector';import {XDSHStack} from '@xds/core/Layout';import {XDSText} from '@xds/core/Text';import {XDSStatusDot} from '@xds/core/StatusDot';-import {XDSDivider} from '@xds/core/Divider';+import {XDSToolbar} from '@xds/core/Toolbar';+import {XDSTabList, XDSTab} from '@xds/core/TabList';+import {+ XDSSegmentedControl,+ XDSSegmentedControlItem,+} from '@xds/core/SegmentedControl';import {useXDSResizable, XDSResizeHandle} from '@xds/core/Resizable';+import {+ ArrowLeftIcon,+ MoonIcon,+ SunIcon,+ ComputerDesktopIcon,+ DevicePhoneMobileIcon,+ ArrowsPointingOutIcon,+ ArrowPathIcon,+} from '@heroicons/react/24/outline';import githubLight from './themes/github-light.json';import githubDark from './themes/github-dark.json';+import {PreviewStage, type Viewport} from './PreviewStage';+import {PropertyPanel} from './PropertyPanel';+import {annotateInstanceIds} from './babelParser';import type * as MonacoTypes from 'monaco-editor';+// 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 & {@@ -169,7 +212,6 @@ function configureMonaco(monaco: MonacoInstance) {fetch('/playground-types.json').then(r => r.json()).then((packages: Record<string, Record<string, string>>) => {- // React typesconst reactFiles = packages['react'] ?? {};for (const [fileName, content] of Object.entries(reactFiles)) {ts.addExtraLib(@@ -178,7 +220,6 @@ function configureMonaco(monaco: MonacoInstance) {);}- // StyleX typesconst stylexFiles = packages['@stylexjs/stylex'] ?? {};for (const [fileName, content] of Object.entries(stylexFiles)) {ts.addExtraLib(@@ -187,7 +228,6 @@ function configureMonaco(monaco: MonacoInstance) {);}- // XDS core types — register each .d.ts under its dist path AND subpathconst xdsFiles = packages['@xds/core'] ?? {};const submoduleReexports: string[] = [];@@ -197,7 +237,6 @@ function configureMonaco(monaco: MonacoInstance) {`file:///node_modules/@xds/core/dist/${relPath}`,);- // Also register as @xds/core/<SubModule>/index.d.tsif (relPath.endsWith('/index.d.ts')) {const moduleName = relPath.replace('/index.d.ts', '');ts.addExtraLib(@@ -208,7 +247,6 @@ function configureMonaco(monaco: MonacoInstance) {}}- // Build @xds/core barrel from submodule re-exportsconst barrelContent = submoduleReexports.map(m => `export * from '@xds/core/${m}';`).join('\n');@@ -217,7 +255,6 @@ function configureMonaco(monaco: MonacoInstance) {'file:///node_modules/@xds/core/index.d.ts',);- // Types loaded — enable semantic validationts.setDiagnosticsOptions({noSemanticValidation: false,noSyntaxValidation: false,@@ -228,92 +265,116 @@ function configureMonaco(monaco: MonacoInstance) {});}+type LeftTab = 'code' | 'property' | 'craft';+type BuildStatus = 'idle' | 'building' | 'finished' | 'error';++const BUILD_STATUS_META: Record<+ Exclude<BuildStatus, 'idle'>,+ {variant: 'warning' | 'success' | 'error'; label: string}+> = {+ building: {variant: 'warning', label: 'Building…'},+ finished: {variant: 'success', label: 'Build finished'},+ error: {variant: 'error', label: 'Build error'},+};+const s = stylex.create({root: {display: 'flex',- flexDirection: 'column',height: '100%',overflow: 'hidden',+ backgroundColor: 'var(--color-background-surface)',},- toolbar: {+ leftPanel: {+ flexShrink: 0,display: 'flex',- alignItems: 'center',- justifyContent: 'space-between',- paddingInline: 16,- paddingBlock: 6,+ flexDirection: 'column',+ overflow: 'hidden',+ minWidth: 0,+ },+ panelHeader: {flexShrink: 0,+ padding: 'var(--spacing-2) var(--spacing-2) 0',},- main: {- display: 'flex',+ tabStretch: {flex: 1,- minHeight: 0,- flexDirection: {- default: 'row',- '@media (max-width: 768px)': 'column',- },},- editorPane: {+ tabBody: {+ flex: 1,+ minHeight: 0,display: 'flex',flexDirection: 'column',- flexShrink: 0,+ overflow: 'hidden',+ },+ codePane: {+ flex: 1,+ minHeight: 0,minWidth: 0,- minHeight: {- default: 0,- '@media (max-width: 768px)': 300,- },+ marginBlockStart: 'var(--spacing-1)',+ },+ hidden: {+ display: 'none',},- previewPane: {+ rightPanel: {flex: 1,display: 'flex',flexDirection: 'column',minWidth: 0,- minHeight: {- default: 0,- '@media (max-width: 768px)': 300,- },- },- iframe: {- flex: 1,- border: 'none',- width: '100%',- height: '100%',+ overflow: 'hidden',},- previewBar: {+ buildStatus: {display: 'flex',alignItems: 'center',- justifyContent: 'space-between',- paddingInline: 12,- paddingBlock: 6,- flexShrink: 0,+ gap: 'var(--spacing-2)',+ transitionProperty: 'opacity',+ transitionDuration: '0.5s',+ transitionTimingFunction: 'ease',},});export function PlaygroundClient() {+ const router = useRouter();const [code, setCode] = useState(getInitialCode);- const [theme, setTheme] = useState('default');+ const [theme, setTheme] = useState('neutral');+ const [mode, setMode] = useState<'light' | 'dark'>('light');+ const [activeTab, setActiveTab] = useState<LeftTab>('code');+ const [viewport, setViewport] = useState<Viewport>('desktop');+ const [isFullscreen, setIsFullscreen] = useState(false);+ const [isResizing, setIsResizing] = useState(false);+ const [buildStatus, setBuildStatus] = useState<BuildStatus>('idle');+ const [statusFading, setStatusFading] = useState(false);const [copied, setCopied] = useState(false);const [previewReady, setPreviewReady] = useState(false);- const [previewError, setPreviewError] = useState<string | null>(null);+ 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.+ const seedCodeRef = useRef(code);const iframeRef = useRef<HTMLIFrameElement>(null);const readyRef = useRef(false);const pendingRef = useRef<string | null>(null);const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);+ const editorRef = useRef<MonacoTypes.editor.IStandaloneCodeEditor | null>(+ null,+ );+ // Mirror activeTab in a ref so onMount can read the current tab without+ // re-creating the (stable) mount callback.+ const activeTabRef = useRef(activeTab);+ activeTabRef.current = activeTab;const editorPanel = useXDSResizable({- defaultSize: '50%',- minSizePx: 200,- collapsible: true,- snaps: [400, 600],- autoSaveId: 'xds-playground-editor-width',+ defaultSize: 440,+ minSizePx: 340,+ maxSizePx: 760,+ autoSaveId: 'xds-playground-left-width',});- const [editorTheme, setEditorTheme] = useState('github-dark');-- // Sync editor theme with system preference+ // Sync editor + initial preview mode with system preferenceuseEffect(() => {const mq = window.matchMedia('(prefers-color-scheme: dark)');- const update = () =>+ const update = () => {setEditorTheme(mq.matches ? 'github-dark' : 'github-light');+ setMode(mq.matches ? 'dark' : 'light');+ };update();mq.addEventListener('change', update);return () => mq.removeEventListener('change', update);@@ -324,6 +385,8 @@ export function PlaygroundClient() {const onHashChange = () => {const newCode = getInitialCode();if (newCode !== DEFAULT_CODE) {+ // A new shared/example snippet became the seed — Reset targets it.+ seedCodeRef.current = newCode;setCode(newCode);}};@@ -342,6 +405,21 @@ export function PlaygroundClient() {);}, []);+ // 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).+ const postCode = useCallback(+ (c: string) => send(annotateInstanceIds(c)),+ [send],+ );++ // Flash a focus ring on the DOM node for a given component instance.+ const flashInstance = useCallback((component: string, index: number) => {+ iframeRef.current?.contentWindow?.postMessage(+ {type: 'preview-highlight', id: `${component}#${index}`},+ window.location.origin,+ );+ }, []);+useEffect(() => {const handler = (e: MessageEvent) => {if (e.source !== iframeRef.current?.contentWindow) {@@ -351,20 +429,20 @@ export function PlaygroundClient() {readyRef.current = true;setPreviewReady(true);if (pendingRef.current != null) {- send(pendingRef.current);+ postCode(pendingRef.current);pendingRef.current = null;}}if (e.data?.type === 'preview-rendered') {- setPreviewError(null);+ setBuildStatus('finished');}if (e.data?.type === 'preview-error') {- setPreviewError(e.data.message ?? 'Unknown error');+ setBuildStatus('error');}};window.addEventListener('message', handler);return () => window.removeEventListener('message', handler);- }, [send]);+ }, [postCode]);useEffect(() => {const interval = setInterval(() => {@@ -380,15 +458,19 @@ export function PlaygroundClient() {return () => clearInterval(interval);}, []);+ // Debounced push of code → preview + URL hashuseEffect(() => {if (debounceRef.current) {clearTimeout(debounceRef.current);}debounceRef.current = setTimeout(() => {+ if (code) {+ setBuildStatus('building');+ }if (!readyRef.current) {pendingRef.current = code;} else {- send(code);+ postCode(code);}updateURL(code);}, 400);@@ -397,14 +479,68 @@ export function PlaygroundClient() {clearTimeout(debounceRef.current);}};- }, [code, send]);+ }, [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.useEffect(() => {iframeRef.current?.contentWindow?.postMessage(- {type: 'preview-theme', theme},+ {type: 'preview-theme', theme, mode},window.location.origin,);- }, [theme]);+ }, [theme, mode, previewReady]);++ // While the resize handle is dragged, the cursor can pass over the preview+ // iframe — a separate document that swallows pointer events and stalls the+ // drag (the handle listens on window pointermove without pointer capture).+ // Detect the drag (capture phase, since the handle stops propagation) and+ // disable iframe pointer events so events keep reaching window during resize.+ const handleResizeProbe = useCallback((e: React.PointerEvent) => {+ const el = e.target as HTMLElement | null;+ if (el?.closest('[role="separator"]')) {+ setIsResizing(true);+ }+ }, []);++ useEffect(() => {+ if (!isResizing) {+ return;+ }+ const stop = () => setIsResizing(false);+ window.addEventListener('pointerup', stop);+ window.addEventListener('pointercancel', stop);+ return () => {+ window.removeEventListener('pointerup', stop);+ window.removeEventListener('pointercancel', stop);+ };+ }, [isResizing]);++ // "Build finished" lingers for 5s, then fades out (0.5s) and disappears.+ useEffect(() => {+ if (buildStatus !== 'finished') {+ setStatusFading(false);+ return;+ }+ const fade = setTimeout(() => setStatusFading(true), 5000);+ const hide = setTimeout(() => {+ setBuildStatus('idle');+ setStatusFading(false);+ }, 5500);+ return () => {+ clearTimeout(fade);+ clearTimeout(hide);+ };+ }, [buildStatus]);++ const handleRebuild = useCallback(() => {+ setBuildStatus('building');+ if (readyRef.current) {+ postCode(code);+ } else {+ pendingRef.current = code;+ }+ }, [postCode, code]);const handleShare = useCallback(() => {navigator.clipboard.writeText(window.location.href).then(() => {@@ -414,24 +550,56 @@ export function PlaygroundClient() {}, []);const handleMonacoBeforeMount = useCallback((monaco: MonacoInstance) => {- // Register themes before editor renders so initial theme appliesmonaco.editor.defineTheme('github-light', githubLight);monaco.editor.defineTheme('github-dark', githubDark);}, []);const handleMonacoMount = useCallback(- (_editor: unknown, monaco: MonacoInstance) => {+ (+ editor: MonacoTypes.editor.IStandaloneCodeEditor,+ monaco: MonacoInstance,+ ) => {+ editorRef.current = editor;configureMonaco(monaco);+ // Focus on initial mount if the Code tab is the active one.+ if (activeTabRef.current === 'code') {+ editor.focus();+ }},[],);- const isMobile = typeof window !== 'undefined' && window.innerWidth <= 768;+ // Focus the editor (blinking cursor) whenever the Code tab becomes active.+ useEffect(() => {+ if (activeTab !== 'code') {+ return;+ }+ const id = requestAnimationFrame(() => editorRef.current?.focus());+ return () => cancelAnimationFrame(id);+ }, [activeTab]);++ // Jump to a specific source offset in the editor (used by the Property tab's+ // "set in code" links). Switches to the Code tab, then reveals + selects the+ // position once Monaco is visible.+ const revealInCode = useCallback((offset: number) => {+ setActiveTab('code');+ requestAnimationFrame(() => {+ const editor = editorRef.current;+ const model = editor?.getModel();+ if (!editor || !model) {+ return;+ }+ const pos = model.getPositionAt(offset);+ editor.setPosition(pos);+ editor.revealPositionInCenter(pos);+ editor.focus();+ });+ }, []);const editorOptions = useMemo(() => ({minimap: {enabled: false},- fontSize: isMobile ? 16 : 13,+ fontSize: 13,lineNumbers: 'on' as const,scrollBeyondLastLine: false,automaticLayout: true,@@ -439,107 +607,190 @@ export function PlaygroundClient() {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.+ scrollbar: {+ vertical: 'hidden' as const,+ horizontal: 'hidden' as const,+ verticalScrollbarSize: 0,+ horizontalScrollbarSize: 0,+ useShadows: false,+ },+ overviewRulerLanes: 0,+ overviewRulerBorder: false,+ hideCursorInOverviewRuler: true,}),- [isMobile],+ [],);return (- <div {...stylex.props(s.root)}>- <div {...stylex.props(s.toolbar)}>- <XDSHStack gap={8} align="center">- <XDSStatusDot- variant={- previewError ? 'error' : previewReady ? 'success' : 'warning'- }- label={previewError ? 'Error' : previewReady ? 'Ready' : 'Loading'}- />- <XDSText color="secondary" type="supporting">- {previewError ? 'Error' : previewReady ? 'Ready' : 'Loading…'}- </XDSText>- </XDSHStack>- <XDSHStack gap={4} align="center">- <XDSSelector- label="Theme"- isLabelHidden- options={THEME_OPTIONS}- value={theme}- onChange={setTheme}- size="sm"- />+ <div {...stylex.props(s.root)} onPointerDownCapture={handleResizeProbe}>+ {/* Left panel — editor */}+ <div+ {...stylex.props(s.leftPanel)}+ style={{width: editorPanel.size || 440}}>+ <XDSHStack gap={2} vAlign="center" xstyle={s.panelHeader}><XDSButton- label="Reset"+ label="Back"+ tooltip="Back"variant="ghost"- size="sm"- onClick={() => setCode(DEFAULT_CODE)}- />- <XDSButton- label={copied ? '✓ Copied!' : 'Copy Link'}- variant={copied ? 'primary' : 'secondary'}- size="sm"- onClick={handleShare}+ size="md"+ isIconOnly+ icon={<ArrowLeftIcon width={20} height={20} />}+ onClick={() => router.back()}/>+ <XDSTabList+ value={activeTab}+ onChange={v => setActiveTab(v as LeftTab)}+ size="md"+ xstyle={s.tabStretch}>+ <XDSTab value="code" label="Code" xstyle={s.tabStretch} />+ <XDSTab value="property" label="Properties" xstyle={s.tabStretch} />+ </XDSTabList></XDSHStack>- </div>- <XDSDivider />- <div {...stylex.props(s.main)}>- <div- {...stylex.props(s.editorPane)}- style={- isMobile ? {height: editorPanel.size} : {width: editorPanel.size}- }>- <MonacoEditor- defaultLanguage="typescript"- defaultValue={code}- path="playground.tsx"- theme={editorTheme}- onChange={v => setCode(v ?? '')}- beforeMount={handleMonacoBeforeMount}- onMount={handleMonacoMount}- options={editorOptions}- />- </div>- <XDSResizeHandle- label="Resize editor panel"- direction={isMobile ? 'vertical' : 'horizontal'}- hasDivider- pillPlacement={isMobile ? 'end' : 'auto'}- resizable={editorPanel.props}- />- <div {...stylex.props(s.previewPane)}>- <div {...stylex.props(s.previewBar)}>- <XDSText color="secondary" type="supporting">- Preview- </XDSText>- <XDSText color="disabled" type="supporting">- {theme.charAt(0).toUpperCase() + theme.slice(1)}- </XDSText>++ <div {...stylex.props(s.tabBody)}>+ {/* Code: Monaco stays mounted to preserve typedefs + editor state */}+ <div {...stylex.props(s.codePane, activeTab !== 'code' && s.hidden)}>+ <MonacoEditor+ defaultLanguage="typescript"+ value={code}+ path="playground.tsx"+ theme={editorTheme}+ onChange={v => setCode(v ?? '')}+ beforeMount={handleMonacoBeforeMount}+ onMount={handleMonacoMount}+ options={editorOptions}+ /></div>- <XDSDivider />- <iframe- ref={iframeRef}- src="/playground-preview"- sandbox="allow-scripts allow-same-origin"- title="Preview"- {...stylex.props(s.iframe)}- />++ {activeTab === 'property' && (+ <PropertyPanel+ code={code}+ onCodeChange={setCode}+ onRevealInCode={revealInCode}+ onFlashInstance={flashInstance}+ />+ )}</div></div>- {previewError && (- <>- <XDSDivider />- <div style={{padding: '8px 16px', maxHeight: 120, overflow: 'auto'}}>- <XDSText type="code" color="inherit">- <span- style={{- color: 'var(--color-text-error, #ef4444)',- whiteSpace: 'pre-wrap',- }}>- {previewError}- </span>- </XDSText>- </div>- </>- )}++ <XDSResizeHandle+ label="Resize editor panel"+ resizable={editorPanel.props}+ pillPlacement="center"+ />++ {/* Right panel — preview */}+ <div {...stylex.props(s.rightPanel)}>+ <XDSToolbar+ label="Preview controls"+ startContent={+ <XDSHStack gap={2} vAlign="center">+ <XDSSelector+ label="Theme"+ isLabelHidden+ options={THEME_OPTIONS}+ value={theme}+ onChange={setTheme}+ size="md"+ />+ <XDSButton+ label={mode === 'light' ? 'Switch to dark' : 'Switch to light'}+ tooltip={mode === 'light' ? 'Dark mode' : 'Light mode'}+ variant="ghost"+ size="md"+ isIconOnly+ icon={+ mode === 'light' ? (+ <MoonIcon width={20} height={20} />+ ) : (+ <SunIcon width={20} height={20} />+ )+ }+ onClick={() => setMode(m => (m === 'light' ? 'dark' : 'light'))}+ />+ </XDSHStack>+ }+ centerContent={+ <XDSSegmentedControl+ label="Viewport size"+ size="md"+ value={viewport}+ onChange={v => setViewport(v as Viewport)}>+ <XDSSegmentedControlItem+ value="desktop"+ label="Desktop"+ isLabelHidden+ icon={<ComputerDesktopIcon width={20} height={20} />}+ />+ <XDSSegmentedControlItem+ value="phone"+ label="Phone"+ isLabelHidden+ icon={<DevicePhoneMobileIcon width={20} height={20} />}+ />+ </XDSSegmentedControl>+ }+ endContent={+ <XDSHStack gap={2} vAlign="center">+ {buildStatus !== 'idle' && (+ <div+ {...stylex.props(s.buildStatus)}+ style={{opacity: statusFading ? 0 : 1}}>+ <XDSStatusDot+ variant={BUILD_STATUS_META[buildStatus].variant}+ label={BUILD_STATUS_META[buildStatus].label}+ isPulsing={buildStatus === 'building'}+ />+ <XDSText type="supporting" color="secondary">+ {BUILD_STATUS_META[buildStatus].label}+ </XDSText>+ {buildStatus === 'error' && (+ <XDSButton+ label="Rebuild"+ tooltip="Rebuild"+ variant="ghost"+ size="sm"+ isIconOnly+ icon={<ArrowPathIcon width={16} height={16} />}+ onClick={handleRebuild}+ />+ )}+ </div>+ )}+ <XDSButton+ label="Expand"+ tooltip="Fullscreen preview"+ variant="ghost"+ size="md"+ isIconOnly+ icon={<ArrowsPointingOutIcon width={20} height={20} />}+ onClick={() => setIsFullscreen(true)}+ />+ <XDSButton+ label="Reset"+ variant="ghost"+ size="md"+ onClick={() => setCode(seedCodeRef.current)}+ />+ <XDSButton+ label={copied ? '✓ Copied' : 'Share'}+ variant={copied ? 'primary' : 'secondary'}+ size="md"+ onClick={handleShare}+ />+ </XDSHStack>+ }+ />+ <PreviewStage+ viewport={viewport}+ isFullscreen={isFullscreen}+ onExitFullscreen={() => setIsFullscreen(false)}+ iframeRef={iframeRef}+ isInteractionDisabled={isResizing}+ />+ </div></div>);}diff --git a/apps/docsite/src/app/playground/PreviewStage.tsx b/apps/docsite/src/app/playground/PreviewStage.tsxnew file mode 100644index 0000000000..20c9158634--- /dev/null+++ b/apps/docsite/src/app/playground/PreviewStage.tsx@@ -0,0 +1,136 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file PreviewStage.tsx+ * @input viewport size, fullscreen flag, iframe ref+ * @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.+ */++'use client';++import * as stylex from '@stylexjs/stylex';+import {XDSCard} from '@xds/core/Card';+import {XDSButton} from '@xds/core/Button';+import {ArrowsPointingInIcon} from '@heroicons/react/24/outline';++export type Viewport = 'desktop' | 'phone';++// iPhone 17 logical viewport (402 × 874 CSS px, ~9:19.5).+const PHONE_WIDTH = 402;+const PHONE_HEIGHT = 874;++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)',+ paddingBlockStart: 0,+ backgroundColor: 'var(--color-background-surface)',+ },+ areaCenter: {+ alignItems: 'center',+ },+ fullscreen: {+ position: 'fixed',+ inset: 0,+ zIndex: 50,+ padding: 'var(--spacing-4)',+ },+ card: {+ maxWidth: '100%',+ maxHeight: '100%',+ overflow: 'hidden',+ transitionProperty: 'width, height',+ transitionDuration: 'var(--duration-medium, 410ms)',+ transitionTimingFunction:+ 'var(--ease-standard, cubic-bezier(0.24, 1, 0.4, 1))',+ boxShadow: 'var(--shadow-med)',+ },+ iframe: {+ border: 'none',+ width: '100%',+ height: '100%',+ display: 'block',+ // Transparent so the iframe's own themed body color shows (not the+ // docsite/astryx body color). The selected theme paints inside the iframe.+ backgroundColor: 'transparent',+ },+ // Let pointer events pass through to window while the panel is being resized,+ // so dragging over the iframe doesn't stall the drag.+ iframeInert: {+ pointerEvents: 'none',+ },+ exitButton: {+ position: 'absolute',+ top: 'var(--spacing-4)',+ right: 'var(--spacing-4)',+ zIndex: 51,+ },+});++interface PreviewStageProps {+ viewport: Viewport;+ isFullscreen: boolean;+ onExitFullscreen: () => void;+ iframeRef: React.RefObject<HTMLIFrameElement | null>;+ /** Disable iframe pointer events (e.g. while the panel is being resized). */+ isInteractionDisabled?: boolean;+}++export function PreviewStage({+ viewport,+ isFullscreen,+ onExitFullscreen,+ iframeRef,+ isInteractionDisabled = false,+}: PreviewStageProps) {+ const isPhone = !isFullscreen && viewport === 'phone';+ const width = isPhone ? PHONE_WIDTH : '100%';+ const height = isPhone ? PHONE_HEIGHT : '100%';++ return (+ <div+ {...stylex.props(+ s.area,+ isPhone && s.areaCenter,+ isFullscreen && s.fullscreen,+ )}>+ {isFullscreen && (+ <div {...stylex.props(s.exitButton)}>+ <XDSCard padding={0} style={{boxShadow: 'var(--shadow-med)'}}>+ <XDSButton+ label="Exit fullscreen"+ tooltip="Exit fullscreen"+ variant="ghost"+ size="sm"+ isIconOnly+ icon={<ArrowsPointingInIcon width={16} height={16} />}+ onClick={onExitFullscreen}+ />+ </XDSCard>+ </div>+ )}+ <XDSCard padding={0} xstyle={s.card} style={{width, height}}>+ <iframe+ ref={iframeRef}+ src="/playground-preview"+ sandbox="allow-scripts allow-same-origin"+ title="Preview"+ {...stylex.props(s.iframe, isInteractionDisabled && s.iframeInert)}+ />+ </XDSCard>+ </div>+ );+}diff --git a/apps/docsite/src/app/playground/PropertyPanel.tsx b/apps/docsite/src/app/playground/PropertyPanel.tsxnew file mode 100644index 0000000000..800c022eb6--- /dev/null+++ b/apps/docsite/src/app/playground/PropertyPanel.tsx@@ -0,0 +1,434 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file PropertyPanel.tsx+ * @input Current editor code + onCodeChange callback+ * @output Component selector + instance picker + literal-bound prop knobs+ * @position Playground left panel — "Property" tab.+ *+ * Parses the code, lists the XDS components used, and renders the docs-style+ * props table for the selected component instance. Changing a knob performs a+ * targeted source-range edit (see babelParser) and writes back through+ * onCodeChange — so edits flow into Monaco and the live preview. Only literal+ * props (boolean / enum / string / number) are editable; props set to an+ * expression are shown read-only ("set in code") to avoid clobbering.+ */++'use client';++import {useEffect, useMemo, useRef, useState} from 'react';+import * as stylex from '@stylexjs/stylex';+import {XDSVStack, XDSHStack} from '@xds/core/Layout';+import {XDSText, XDSHeading} from '@xds/core/Text';+import {XDSSelector} from '@xds/core/Selector';+import {XDSLink} from '@xds/core/Link';+import {XDSSwitch} from '@xds/core/Switch';+import {XDSTextInput} from '@xds/core/TextInput';+import {XDSNumberInput} from '@xds/core/NumberInput';+import {XDSDivider} from '@xds/core/Divider';+import {XDSEmptyState} from '@xds/core/EmptyState';+import {+ XDSSegmentedControl,+ XDSSegmentedControlItem,+} from '@xds/core/SegmentedControl';+import {+ coerceDefault,+ parsePropType,+ type PropControlDescriptor,+} from '../../components/component-detail/parsePropType';+import type {PropDoc} from '../../generated/componentRegistry';+import {+ analyzeCode,+ formatAttr,+ removeAttribute,+ setAttribute,+ type AttrInfo,+ type InstanceInfo,+} from './babelParser';+import {getComponentByModule, getUsedComponents} from './usedComponents';++const NUMERIC_RE = /^-?\d+(\.\d+)?$/;++const s = stylex.create({+ root: {+ display: 'flex',+ flexDirection: 'column',+ height: '100%',+ minHeight: 0,+ },+ header: {+ flexShrink: 0,+ padding: 'var(--spacing-3) var(--spacing-3) var(--spacing-2)',+ },+ scroll: {+ flex: 1,+ minHeight: 0,+ overflow: 'auto',+ padding: 'var(--spacing-3)',+ paddingBlockStart: 0,+ },+ row: {+ paddingBlock: 'var(--spacing-2)',+ },+ control: {+ flexBasis: 160,+ flexShrink: 0,+ display: 'flex',+ justifyContent: 'flex-end',+ },+ emptyWrap: {+ flex: 1,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ padding: 'var(--spacing-6)',+ },+});++function isEditable(control: PropControlDescriptor, attr?: AttrInfo): boolean {+ if (attr?.valueKind === 'expression') {+ return false;+ }+ return (+ control.kind === 'boolean' ||+ control.kind === 'enum' ||+ control.kind === 'string' ||+ control.kind === 'number'+ );+}++interface PropRowProps {+ prop: PropDoc;+ instance: InstanceInfo;+ code: string;+ onCodeChange: (code: string) => void;+ onRevealInCode?: (offset: number) => void;+}++function PropRow({+ prop,+ instance,+ code,+ onCodeChange,+ onRevealInCode,+}: PropRowProps) {+ const control = useMemo(+ () => parsePropType(prop.type, prop.name, prop.slotElements),+ [prop],+ );+ const attr = instance.attrs.find(a => a.name === prop.name);+ const editable = isEditable(control, attr);++ const commit = (+ kind: 'boolean' | 'string' | 'number' | 'enum',+ value: string | number | boolean,+ ) => {+ let next: string;+ if (kind === 'boolean') {+ next = value+ ? setAttribute(+ code,+ instance,+ prop.name,+ formatAttr(prop.name, 'boolean', true),+ )+ : removeAttribute(code, instance, prop.name);+ } else if (kind === 'string') {+ next =+ value === ''+ ? removeAttribute(code, instance, prop.name)+ : setAttribute(+ code,+ instance,+ prop.name,+ formatAttr(prop.name, 'string', value),+ );+ } else if (kind === 'number') {+ next = setAttribute(+ code,+ instance,+ prop.name,+ formatAttr(prop.name, 'number', value),+ );+ } else {+ const numeric = NUMERIC_RE.test(String(value));+ next = setAttribute(+ code,+ instance,+ prop.name,+ formatAttr(+ prop.name,+ numeric ? 'number' : 'string',+ numeric ? Number(value) : value,+ ),+ );+ }+ onCodeChange(next);+ };++ let controlEl: React.ReactNode;+ if (!editable) {+ if (attr && onRevealInCode) {+ const line = code.slice(0, attr.start).split('\n').length;+ controlEl = (+ <XDSLink+ href="#code"+ hasUnderline+ tooltip={`Go to line ${line}`}+ onClick={e => {+ e.preventDefault();+ onRevealInCode(attr.start);+ }}>+ <XDSText type="supporting">set in code</XDSText>+ </XDSLink>+ );+ } else {+ controlEl = (+ <XDSText type="supporting" color={attr ? 'secondary' : 'disabled'}>+ {attr ? 'set in code' : '—'}+ </XDSText>+ );+ }+ } else if (control.kind === 'boolean') {+ const checked = attr+ ? attr.value === true+ : coerceDefault(prop.default, control) === true;+ controlEl = (+ <XDSSwitch+ label={prop.name}+ isLabelHidden+ value={!!checked}+ onChange={next => commit('boolean', next)}+ />+ );+ } else if (control.kind === 'enum') {+ const def = coerceDefault(prop.default, control) as string | undefined;+ const value = String(attr?.value ?? def ?? control.options[0]);+ controlEl = (+ <XDSSelector+ label={prop.name}+ isLabelHidden+ size="sm"+ value={value}+ options={control.options}+ onChange={next => commit('enum', next)}+ />+ );+ } else if (control.kind === 'string') {+ const value = typeof attr?.value === 'string' ? attr.value : '';+ controlEl = (+ <XDSTextInput+ label={prop.name}+ isLabelHidden+ placeholder="value"+ value={value}+ onChange={next => commit('string', next)}+ />+ );+ } else {+ const def = coerceDefault(prop.default, control) as number | undefined;+ const value = typeof attr?.value === 'number' ? attr.value : (def ?? 0);+ controlEl = (+ <XDSNumberInput+ label={prop.name}+ isLabelHidden+ value={value}+ onChange={next => commit('number', next)}+ />+ );+ }++ return (+ <div {...stylex.props(s.row)}>+ <XDSHStack gap={3} vAlign="start">+ <div style={{flex: 1, minWidth: 0}}>+ <XDSText type="body" weight="bold">+ {prop.name}+ </XDSText>+ <XDSText type="code" color="secondary" display="block">+ {prop.type}+ </XDSText>+ </div>+ <div {...stylex.props(s.control)}>{controlEl}</div>+ </XDSHStack>+ </div>+ );+}++interface PropertyPanelProps {+ code: string;+ onCodeChange: (code: string) => void;+ onRevealInCode?: (offset: number) => void;+ onFlashInstance?: (component: string, index: number) => void;+}++export function PropertyPanel({+ code,+ onCodeChange,+ onRevealInCode,+ onFlashInstance,+}: PropertyPanelProps) {+ const [selected, setSelected] = useState<string | null>(null);+ const [instanceIndex, setInstanceIndex] = useState(0);+ const lastInstances = useRef<InstanceInfo[]>([]);++ // Re-parse on every code change; keep the last good parse on syntax errors.+ const instances = useMemo(() => {+ const parsed = analyzeCode(code);+ if (parsed != null) {+ lastInstances.current = parsed;+ return parsed;+ }+ return lastInstances.current;+ }, [code]);++ const used = useMemo(() => getUsedComponents(instances), [instances]);++ // Keep selection valid as the code changes.+ useEffect(() => {+ if (used.length === 0) {+ if (selected !== null) {+ setSelected(null);+ }+ return;+ }+ if (selected == null || !used.some(u => u.module === selected)) {+ setSelected(used[0].module);+ setInstanceIndex(0);+ }+ }, [used, selected]);++ const componentInstances = useMemo(+ () => instances.filter(i => i.component === selected),+ [instances, selected],+ );++ // Clamp instance index when the count shrinks.+ useEffect(() => {+ if (instanceIndex > 0 && instanceIndex >= componentInstances.length) {+ setInstanceIndex(Math.max(0, componentInstances.length - 1));+ }+ }, [componentInstances, instanceIndex]);++ if (used.length === 0) {+ return (+ <div {...stylex.props(s.emptyWrap)}>+ <XDSEmptyState+ title="No components detected"+ description="Add an XDS component in the Code tab to edit its props here."+ isCompact+ />+ </div>+ );+ }++ const entry = selected ? getComponentByModule(selected) : undefined;+ const targetInstance =+ componentInstances[Math.min(instanceIndex, componentInstances.length - 1)];+ const props = entry?.props ?? [];+ const required = props.filter(p => p.required);+ const optional = props.filter(p => !p.required);++ const componentOptions = used.map(u => ({+ value: u.module,+ label: u.count > 1 ? `${u.label} (${u.count})` : u.label,+ }));++ return (+ <div {...stylex.props(s.root)}>+ <div {...stylex.props(s.header)}>+ <XDSVStack gap={2}>+ <XDSSelector+ label="Component"+ options={componentOptions}+ value={selected ?? undefined}+ onChange={value => {+ setSelected(value);+ setInstanceIndex(0);+ onFlashInstance?.(value, 0);+ }}+ size="sm"+ />+ {componentInstances.length > 1 && (+ <XDSSegmentedControl+ label="Instance"+ size="sm"+ layout="fill"+ value={String(instanceIndex)}+ onChange={value => {+ const index = Number(value);+ setInstanceIndex(index);+ if (selected) {+ onFlashInstance?.(selected, index);+ }+ }}>+ {componentInstances.map((_, i) => (+ <XDSSegmentedControlItem+ key={i}+ value={String(i)}+ label={`${i + 1}`}+ />+ ))}+ </XDSSegmentedControl>+ )}+ </XDSVStack>+ </div>++ <div {...stylex.props(s.scroll)}>+ {!entry ? (+ <XDSText type="supporting" color="secondary">+ {selected} is not part of @xds/core — no editable props.+ </XDSText>+ ) : props.length === 0 ? (+ <XDSText type="supporting" color="secondary">+ {entry.displayName} has no documented props.+ </XDSText>+ ) : targetInstance == null ? null : (+ <XDSVStack gap={1}>+ {required.length > 0 && (+ <>+ <XDSHeading level={5} color="secondary">+ Required+ </XDSHeading>+ {required.map(prop => (+ <div key={prop.name}>+ <XDSDivider />+ <PropRow+ prop={prop}+ instance={targetInstance}+ code={code}+ onCodeChange={onCodeChange}+ onRevealInCode={onRevealInCode}+ />+ </div>+ ))}+ </>+ )}+ {optional.length > 0 && (+ <>+ <XDSHeading+ level={5}+ color="secondary"+ style={{marginTop: 'var(--spacing-2)'}}>+ Optional+ </XDSHeading>+ {optional.map(prop => (+ <div key={prop.name}>+ <XDSDivider />+ <PropRow+ prop={prop}+ instance={targetInstance}+ code={code}+ onCodeChange={onCodeChange}+ onRevealInCode={onRevealInCode}+ />+ </div>+ ))}+ </>+ )}+ </XDSVStack>+ )}+ </div>+ </div>+ );+}diff --git a/apps/docsite/src/app/playground/babelParser.ts b/apps/docsite/src/app/playground/babelParser.tsnew file mode 100644index 0000000000..dadec3db1a--- /dev/null+++ b/apps/docsite/src/app/playground/babelParser.ts@@ -0,0 +1,253 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file babelParser.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.+ *+ * 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+ * offsets are captured so a prop edit splices a single span of the original+ * source — preserving the rest of the file's formatting and comments.+ *+ * Note: we deliberately use the parser only (no transform) and avoid loading+ * anything from a CDN, since corpnet blocks external CDNs. Monaco's AMD loader+ * would also clobber a global `window.ts`, so the parser stays fully bundled.+ */++import {parse} from '@babel/parser';++/** Literal value kinds we can round-trip through a knob. */+export type AttrValueKind =+ | 'boolean' // boolean shorthand or {true}/{false}+ | 'string' // "..." or {'...'}+ | 'number' // {123}+ | 'expression' // {someExpr} — not a literal, render read-only+ | 'none'; // attribute present but no value we understand++export interface AttrInfo {+ name: string;+ /** Offset of the JSXAttribute node start in the source. */+ start: number;+ /** Offset of the JSXAttribute node end in the source. */+ end: number;+ valueKind: AttrValueKind;+ value?: string | number | boolean;+}++export interface InstanceInfo {+ /** Component module name as written, e.g. `XDSButton`. */+ component: string;+ /** Start offset of the opening element (`<`). */+ openingStart: number;+ /** Offset immediately after the element name — insertion point for new attrs. */+ nameEnd: number;+ attrs: AttrInfo[];+}++type Node = Record<string, unknown>;++function readAttrValue(attr: Node): {+ valueKind: AttrValueKind;+ value?: string | number | boolean;+} {+ const value = attr.value as Node | null | undefined;+ // Boolean shorthand: `<XDSButton isDisabled />`+ if (value == null) {+ return {valueKind: 'boolean', value: true};+ }+ if (value.type === 'StringLiteral') {+ return {valueKind: 'string', value: value.value as string};+ }+ if (value.type === 'JSXExpressionContainer') {+ const expr = value.expression as Node;+ if (!expr) {+ return {valueKind: 'expression'};+ }+ if (expr.type === 'BooleanLiteral') {+ return {valueKind: 'boolean', value: expr.value as boolean};+ }+ if (expr.type === 'NumericLiteral') {+ return {valueKind: 'number', value: expr.value as number};+ }+ if (expr.type === 'StringLiteral') {+ return {valueKind: 'string', value: expr.value as string};+ }+ if (+ expr.type === 'UnaryExpression' &&+ expr.operator === '-' &&+ (expr.argument as Node)?.type === 'NumericLiteral'+ ) {+ return {+ valueKind: 'number',+ value: -((expr.argument as Node).value as number),+ };+ }+ return {valueKind: 'expression'};+ }+ return {valueKind: 'none'};+}++/**+ * Parse code and return every `<XDS*>` instance with attribute offsets.+ * Returns null on a syntax error so callers keep the previous good analysis+ * while the user is mid-edit.+ */+export function analyzeCode(code: string): InstanceInfo[] | null {+ let ast: Node;+ try {+ ast = parse(code, {+ sourceType: 'module',+ plugins: ['jsx', 'typescript'],+ }) as unknown as Node;+ } catch {+ return null;+ }++ const instances: InstanceInfo[] = [];++ const walk = (node: unknown): void => {+ if (!node || typeof node !== 'object') {+ return;+ }+ if (Array.isArray(node)) {+ for (const child of node) {+ walk(child);+ }+ return;+ }+ const n = node as Node;+ if (n.type === 'JSXOpeningElement') {+ const nameNode = n.name as Node;+ if (nameNode?.type === 'JSXIdentifier') {+ const component = nameNode.name as string;+ if (component.startsWith('XDS')) {+ const attrs: AttrInfo[] = [];+ const rawAttrs = (n.attributes as Node[]) ?? [];+ for (const attr of rawAttrs) {+ if (attr.type !== 'JSXAttribute') {+ continue; // skip {...spread}+ }+ const nameField = attr.name as Node;+ const name = nameField?.name;+ if (typeof name !== 'string') {+ continue;+ }+ attrs.push({+ name,+ start: attr.start as number,+ end: attr.end as number,+ ...readAttrValue(attr),+ });+ }+ instances.push({+ component,+ openingStart: n.start as number,+ nameEnd: nameNode.end as number,+ attrs,+ });+ }+ }+ }+ for (const key in n) {+ if (key === 'loc' || key === 'start' || key === 'end') {+ continue;+ }+ walk(n[key]);+ }+ };++ walk(ast);+ return instances;+}++function escapeStringAttr(value: string): string {+ // Plain double-quoted attribute when safe, else an expression container.+ if (/["\\\n]/.test(value)) {+ return JSON.stringify(value); // becomes {"..."} via caller+ }+ return value;+}++/**+ * Build the attribute snippet (no leading space), e.g. `label="Save"`,+ * `isDisabled`, `size="lg"`, or `count={3}`.+ */+export function formatAttr(+ name: string,+ kind: AttrValueKind,+ value: string | number | boolean,+): string {+ if (kind === 'boolean') {+ return value ? name : `${name}={false}`;+ }+ if (kind === 'number') {+ return `${name}={${value}}`;+ }+ // string / enum-as-string+ const str = String(value);+ const safe = escapeStringAttr(str);+ return safe.startsWith('"') ? `${name}={${safe}}` : `${name}="${safe}"`;+}++/** Replace an existing attribute or insert a new one after the element name. */+export function setAttribute(+ code: string,+ instance: InstanceInfo,+ name: string,+ attrText: string,+): string {+ const existing = instance.attrs.find(a => a.name === name);+ if (existing) {+ return code.slice(0, existing.start) + attrText + code.slice(existing.end);+ }+ const at = instance.nameEnd;+ return `${code.slice(0, at)} ${attrText}${code.slice(at)}`;+}++/**+ * 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.+ *+ * Markers are only applied to the copy SENT to the preview — never to the code+ * the user sees, edits, or shares.+ */+export function annotateInstanceIds(code: string): string {+ const instances = analyzeCode(code);+ if (!instances || instances.length === 0) {+ return code;+ }+ const counts = new Map<string, number>();+ const inserts = instances.map(inst => {+ const index = counts.get(inst.component) ?? 0;+ counts.set(inst.component, index + 1);+ return {at: inst.nameEnd, text: ` data-pg-id="${inst.component}#${index}"`};+ });+ // Insert from the end so earlier offsets stay valid.+ inserts.sort((a, b) => b.at - a.at);+ let out = code;+ for (const ins of inserts) {+ out = out.slice(0, ins.at) + ins.text + out.slice(ins.at);+ }+ return out;+}++/** Remove an attribute (and one leading whitespace char, if present). */+export function removeAttribute(+ code: string,+ instance: InstanceInfo,+ name: string,+): string {+ const existing = instance.attrs.find(a => a.name === name);+ if (!existing) {+ return code;+ }+ let start = existing.start;+ if (start > 0 && /\s/.test(code[start - 1])) {+ start -= 1;+ }+ return code.slice(0, start) + code.slice(existing.end);+}diff --git a/apps/docsite/src/app/playground/layout.tsx b/apps/docsite/src/app/playground/layout.tsxindex 61689f034f..b27549e2c7 100644--- a/apps/docsite/src/app/playground/layout.tsx+++ b/apps/docsite/src/app/playground/layout.tsx@@ -1,7 +1,16 @@// Copyright (c) Meta Platforms, Inc. and affiliates.-import {XDSAppShell} from '@xds/core/AppShell';-import {SharedTopNav} from '../../components/SharedTopNav';+/**+ * Page type: playground (full-bleed tool)+ * Renders the interactive code playground full-screen with no marketing top+ * nav / footer chrome — a left editor panel and a right live-preview panel.+ * Theme context is provided by the root <Providers> (app/providers.tsx), so+ * this layout only needs to establish a full-viewport, overflow-hidden frame.+ *+ * @input children — the PlaygroundClient tree+ * @output Full-height surface container+ * @position app/playground layout wrapper+ */export default function PlaygroundLayout({children,@@ -9,12 +18,13 @@ export default function PlaygroundLayout({children: React.ReactNode;}) {return (- <XDSAppShell- variant="surface"- height="fill"- contentPadding={0}- topNav={<SharedTopNav />}>+ <div+ style={{+ height: '100vh',+ overflow: 'hidden',+ backgroundColor: 'var(--color-background-surface)',+ }}>{children}- </XDSAppShell>+ </div>);}diff --git a/apps/docsite/src/app/playground/usedComponents.ts b/apps/docsite/src/app/playground/usedComponents.tsnew file mode 100644index 0000000000..28056336da--- /dev/null+++ b/apps/docsite/src/app/playground/usedComponents.ts@@ -0,0 +1,65 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file usedComponents.ts+ * @input Generated component registry + detected JSX instances+ * @output Module-name → ComponentEntry lookup; distinct used-component list+ * @position Playground Property tab support.+ */++import {+ components,+ type ComponentEntry,+} from '../../generated/componentRegistry';+import type {InstanceInfo} from './babelParser';++const byModuleName: Map<string, ComponentEntry> = (() => {+ const map = new Map<string, ComponentEntry>();+ for (const entries of Object.values(components)) {+ for (const entry of entries) {+ // moduleName is the JSX identifier authored in code, e.g. `XDSButton`.+ if (entry.moduleName && !map.has(entry.moduleName)) {+ map.set(entry.moduleName, entry);+ }+ }+ }+ return map;+})();++export function getComponentByModule(+ moduleName: string,+): ComponentEntry | undefined {+ return byModuleName.get(moduleName);+}++export interface UsedComponent {+ /** JSX identifier as written, e.g. `XDSButton`. */+ module: string;+ /** Friendly label, e.g. `Button` (falls back to the module name). */+ label: string;+ /** Number of instances of this component in the code. */+ count: number;+ /** Whether the registry knows this component (has props/docs). */+ known: boolean;+}++/** Distinct XDS components present in the code, in first-seen order. */+export function getUsedComponents(instances: InstanceInfo[]): UsedComponent[] {+ const order: string[] = [];+ const counts = new Map<string, number>();+ for (const inst of instances) {+ if (!counts.has(inst.component)) {+ order.push(inst.component);+ }+ counts.set(inst.component, (counts.get(inst.component) ?? 0) + 1);+ }+ return order.map(module => {+ const entry = byModuleName.get(module);+ return {+ module,+ label: entry?.displayName ?? module.replace(/^XDS/, ''),+ count: counts.get(module) ?? 0,+ known: entry != null,+ };+ });+}