Skip to content

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

TypeScript

feat(docsite): Playground properties popover (#2873)

Kenton Quatmaned4090765af6
diff --git a/apps/docsite/src/app/(preview)/playground-preview/layout.tsx b/apps/docsite/src/app/(preview)/playground-preview/layout.tsx
index fd85ed6f51..6676f99ca3 100644
--- a/apps/docsite/src/app/(preview)/playground-preview/layout.tsx
+++ b/apps/docsite/src/app/(preview)/playground-preview/layout.tsx
@@ -5,19 +5,6 @@ export default function PreviewLayout({children}: {children: React.ReactNode}) {
<>
<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; }
- }
/* ── Targeting overlay ── */
.pg-targeting { cursor: crosshair !important; }
@@ -40,14 +27,14 @@ export default function PreviewLayout({children}: {children: React.ReactNode}) {
position: absolute;
bottom: 100%;
left: -2px;
- margin-bottom: 4px;
- padding: 2px 8px;
+ 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;
- color: #fff;
background: var(--color-border-focus, #1877f2);
- border-radius: 4px;
+ border-radius: var(--radius-corner, 4px);
white-space: nowrap;
user-select: none;
+ pointer-events: auto;
}
.pg-target-label-bottom {
top: 100%;
diff --git a/apps/docsite/src/app/(preview)/playground-preview/page.tsx b/apps/docsite/src/app/(preview)/playground-preview/page.tsx
index 07b5650027..2cdc3d9206 100644
--- a/apps/docsite/src/app/(preview)/playground-preview/page.tsx
+++ b/apps/docsite/src/app/(preview)/playground-preview/page.tsx
@@ -12,12 +12,22 @@ import React, {
type ErrorInfo,
type ReactNode,
} from 'react';
-import {XDSTheme, defineTheme} from '@xds/core/theme';
+import {createRoot, type Root} from 'react-dom/client';
+import * as stylex from '@stylexjs/stylex';
+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 {astryxTheme} from '../../../themes/astryx';
+import {useThemeMode} from '../../providers';
+import {PropertyPanel} from '../../playground/PropertyPanel';
import {runCode, setTypeScript} from './runner';
import type * as TS from 'typescript';
@@ -94,7 +104,7 @@ function ErrorDisplay({message}: {message: string}) {
type PreviewMessage =
| {type: 'preview-ping'}
- | {type: 'preview-code'; code: string}
+ | {type: 'preview-code'; code: string; source: string}
| {type: 'preview-clear'}
| {
type: 'preview-theme';
@@ -106,11 +116,148 @@ type PreviewMessage =
customTokens?: Record<string, string>;
customComponents?: unknown;
}
- | {type: 'preview-highlight'; id: string}
- | {type: 'preview-select'; id: string}
| {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},
+});
+
+function TargetLabel({
+ name,
+ isInteractive,
+ id,
+ code,
+ onCodeChange,
+}: {
+ name: string;
+ isInteractive: boolean;
+ id: string;
+ code: string;
+ onCodeChange: (code: string) => void;
+}) {
+ const [isOpen, setIsOpen] = useState(false);
+ const badge = (
+ <XDSMediaTheme mode="dark">
+ <XDSHStack gap={2} vAlign="center" xstyle={styles.badge}>
+ <XDSText>{name}</XDSText>
+ {isInteractive && (
+ <XDSHStack xstyle={styles.badgeActions}>
+ <XDSButton
+ label="Properties"
+ variant="ghost"
+ size="sm"
+ isIconOnly
+ icon={<Settings size={12} />}
+ />
+ <XDSButton
+ label="Deselect"
+ variant="ghost"
+ size="sm"
+ isIconOnly
+ icon={<X size={12} />}
+ onClick={() => clearSelectionOverlay()}
+ />
+ </XDSHStack>
+ )}
+ </XDSHStack>
+ </XDSMediaTheme>
+ );
+
+ if (!isInteractive) {
+ return badge;
+ }
+
+ const sep = id.lastIndexOf('#');
+ const component = sep >= 0 ? id.slice(0, sep) : id;
+ const instanceIndex = sep >= 0 ? Number(id.slice(sep + 1)) : 0;
+
+ return (
+ <XDSPopover
+ label="Component properties"
+ placement="below"
+ alignment="start"
+ width={400}
+ isOpen={isOpen}
+ onOpenChange={setIsOpen}
+ xstyle={styles.popover}
+ content={
+ <PropertyPanel
+ code={code}
+ onCodeChange={onCodeChange}
+ externalSelection={{component, instanceIndex}}
+ onApplied={() => setIsOpen(false)}
+ />
+ }>
+ {badge}
+ </XDSPopover>
+ );
+}
+
+const labelRoots = new WeakMap<HTMLElement, Root>();
+const activeLabels = new Set<HTMLDivElement>();
+
+// The selection tool (badges, popover, ring) is Playground chrome, not preview
+// content — it always renders on the site theme (Astryx) so it stays visually
+// distinct from whatever theme the preview is showing. We only track the site
+// color mode so the chrome matches light/dark.
+let activeSiteMode: ThemeMode = 'light';
+
+let cleanSource = '';
+
+function postEditToParent(code: string) {
+ window.parent.postMessage({type: 'preview-edit-code', code}, '*');
+}
+
+function renderTargetLabel(label: HTMLDivElement) {
+ const root = labelRoots.get(label);
+ if (!root) {
+ return;
+ }
+ const name = label.dataset.labelText ?? '';
+ const isInteractive = label.dataset.interactive === 'true';
+ const id = label.dataset.labelId ?? '';
+ root.render(
+ <XDSTheme theme={astryxTheme} mode={activeSiteMode}>
+ <TargetLabel
+ name={name}
+ isInteractive={isInteractive}
+ id={id}
+ code={cleanSource}
+ onCodeChange={postEditToParent}
+ />
+ </XDSTheme>,
+ );
+}
+
+function createTargetLabel(isInteractive: boolean): HTMLDivElement {
+ const label = document.createElement('div');
+ label.className = 'pg-target-label';
+ label.dataset.interactive = String(isInteractive);
+ label.dataset.labelText = '';
+ labelRoots.set(label, createRoot(label));
+ activeLabels.add(label);
+ renderTargetLabel(label);
+ return label;
+}
+
+function setTargetLabelText(label: HTMLDivElement, value: string) {
+ if (label.dataset.labelText === value) {
+ return;
+ }
+ label.dataset.labelText = value;
+ renderTargetLabel(label);
+}
+
+function refreshTargetLabels() {
+ for (const label of activeLabels) {
+ renderTargetLabel(label);
+ }
+}
+
/**
* Persistent selection overlay — same visual treatment as the hover overlay
* (blue border + tinted fill + component name label). Lives in a separate
@@ -129,8 +276,7 @@ function ensureSelectionOverlay() {
}
const overlay = document.createElement('div');
overlay.className = 'pg-target-selection';
- const label = document.createElement('div');
- label.className = 'pg-target-label';
+ const label = createTargetLabel(true);
overlay.appendChild(label);
document.body.appendChild(overlay);
selectionState.overlay = overlay;
@@ -154,8 +300,16 @@ function updateSelectionPosition() {
overlay.style.height = `${rect.height + 4}px`;
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
+ // name or id actually changes (this runs every animation frame).
const sep = id.lastIndexOf('#');
- label.textContent = sep >= 0 ? id.slice(0, sep) : id;
+ const name = sep >= 0 ? id.slice(0, sep) : id;
+ if (label.dataset.labelText !== name || label.dataset.labelId !== id) {
+ label.dataset.labelText = name;
+ label.dataset.labelId = id;
+ renderTargetLabel(label);
+ }
if (rect.top < 28) {
label.classList.add('pg-target-label-bottom');
@@ -192,20 +346,6 @@ function clearSelectionOverlay() {
}
}
-/** 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);
-}
-
/**
* Manages the targeting overlay lifecycle inside the iframe. When enabled,
* intercepts pointer events to highlight hovered XDS components and report
@@ -226,8 +366,7 @@ function createTargetingController(
}
overlayEl = document.createElement('div');
overlayEl.className = 'pg-target-overlay';
- labelEl = document.createElement('div');
- labelEl.className = 'pg-target-label';
+ labelEl = createTargetLabel(false);
overlayEl.appendChild(labelEl);
document.body.appendChild(overlayEl);
}
@@ -267,7 +406,7 @@ function createTargetingController(
overlayEl.dataset.visible = 'true';
const parsed = parsePgId(pgId);
- labelEl.textContent = parsed ? parsed.component : pgId;
+ setTargetLabelText(labelEl, parsed ? parsed.component : pgId);
// Flip label below if it would overflow above the viewport
if (rect.top < 28) {
@@ -456,7 +595,11 @@ export default function PreviewPage() {
if (result.Component) {
setComponent(() => result.Component);
setError(null);
- clearSelectionOverlay();
+ // 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'});
@@ -526,6 +669,10 @@ export default function PreviewPage() {
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':
@@ -534,12 +681,6 @@ export default function PreviewPage() {
case 'preview-theme':
handleTheme(event.data);
break;
- case 'preview-highlight':
- flashElement(event.data.id);
- break;
- case 'preview-select':
- selectElement(event.data.id);
- break;
case 'targeting-enable':
targetingRef.current?.enable();
break;
@@ -585,6 +726,14 @@ export default function PreviewPage() {
[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.
diff --git a/apps/docsite/src/app/playground/PlaygroundClient.tsx b/apps/docsite/src/app/playground/PlaygroundClient.tsx
index f625667de4..1f710a607d 100644
--- a/apps/docsite/src/app/playground/PlaygroundClient.tsx
+++ b/apps/docsite/src/app/playground/PlaygroundClient.tsx
@@ -61,7 +61,6 @@ import {
ExternalLink,
Moon,
Palette,
- SlidersHorizontal,
Sun,
Monitor,
Smartphone,
@@ -81,7 +80,6 @@ import {templates} from '../../generated/templateRegistry';
import {PreviewStage, type Viewport} from './PreviewStage';
import {ConfirmDialog} from './ConfirmDialog';
import {BRAND_ICON} from '../../components/XDSWordmark';
-import {PropertyPanel} from './PropertyPanel';
import {annotateInstanceIds} from './babelParser';
import {trackCopy} from '../../lib/analytics';
import {PlaygroundThemeEditor} from '../../components/themePlayground/PlaygroundThemeEditor';
@@ -288,8 +286,8 @@ function configureMonaco(monaco: MonacoInstance) {
});
}
-type LeftView = 'code' | 'property' | 'theme';
-type MobileTopTab = 'preview' | 'code' | 'property' | 'theme';
+type LeftView = 'code' | 'theme';
+type MobileTopTab = 'preview' | 'code' | 'theme';
type BuildStatus = 'idle' | 'building' | 'finished' | 'error';
const MOBILE_BREAKPOINT_QUERY = '(max-width: 768px)';
@@ -434,10 +432,6 @@ export function PlaygroundClient({defaultIsMobile}: PlaygroundClientProps) {
const [exportTheme, setExportTheme] = useState<XDSDefinedTheme | null>(null);
const [previewReady, setPreviewReady] = useState(false);
const [isTargeting, setIsTargeting] = useState(false);
- const [targetedComponent, setTargetedComponent] = useState<string | null>(
- null,
- );
- const [targetedInstance, setTargetedInstance] = useState(0);
// 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.
@@ -527,21 +521,23 @@ export function PlaygroundClient({defaultIsMobile}: PlaygroundClientProps) {
}
}, [themeParam]);
- const send = useCallback((c: string) => {
+ const send = useCallback((c: string, source?: string) => {
const win = iframeRef.current?.contentWindow;
if (!win) {
return;
}
win.postMessage(
- c ? {type: 'preview-code', code: c} : {type: 'preview-clear'},
+ c ? {type: 'preview-code', code: c, source} : {type: 'preview-clear'},
window.location.origin,
);
}, []);
// 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).
+ // 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
+ // against un-annotated offsets.
const postCode = useCallback(
- (c: string) => send(annotateInstanceIds(c)),
+ (c: string) => send(annotateInstanceIds(c), c),
[send],
);
@@ -563,14 +559,6 @@ export function PlaygroundClient({defaultIsMobile}: PlaygroundClientProps) {
[mode],
);
- // Persistently highlight the DOM node for a given component instance.
- const selectInstance = useCallback((component: string, index: number) => {
- iframeRef.current?.contentWindow?.postMessage(
- {type: 'preview-select', id: `${component}#${index}`},
- window.location.origin,
- );
- }, []);
-
const toggleTargeting = useCallback((pressed?: boolean) => {
setIsTargeting(prev => {
const next = pressed ?? !prev;
@@ -598,13 +586,19 @@ export function PlaygroundClient({defaultIsMobile}: PlaygroundClientProps) {
if (e.data?.type === 'preview-rendered') {
setBuildStatus('finished');
}
+ // A prop knob edited in the in-preview Properties popover sends back the
+ // new clean code; adopt it as the source of truth (drives Monaco, the
+ // URL hash, and the debounced re-render of the preview).
+ if (e.data?.type === 'preview-edit-code') {
+ setCode(e.data.code);
+ }
if (e.data?.type === 'preview-error') {
setBuildStatus('error');
}
if (e.data?.type === 'targeting-select') {
- setTargetedComponent(e.data.component);
- setTargetedInstance(e.data.index);
- setActiveView('property');
+ // The preview draws the selection badge itself; just exit targeting
+ // 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'},
@@ -802,24 +796,6 @@ export function PlaygroundClient({defaultIsMobile}: PlaygroundClientProps) {
return () => cancelAnimationFrame(id);
}, [activeView]);
- // Jump to a specific source offset in the editor (used by the Property view's
- // "set in code" links). Switches to the Code view, then reveals + selects the
- // position once Monaco is visible.
- const revealInCode = useCallback((offset: number) => {
- setActiveView('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();
- });
- }, []);
-
// 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
@@ -894,7 +870,7 @@ export function PlaygroundClient({defaultIsMobile}: PlaygroundClientProps) {
const handleMobileTabChange = useCallback((tab: MobileTopTab) => {
setMobileTab(tab);
- if (tab === 'code' || tab === 'property' || tab === 'theme') {
+ if (tab === 'code' || tab === 'theme') {
setActiveView(tab);
}
}, []);
@@ -928,12 +904,6 @@ export function PlaygroundClient({defaultIsMobile}: PlaygroundClientProps) {
icon={<Code2 size={14} />}
isLabelHidden
/>
- <XDSTab
- value="property"
- label="Properties"
- icon={<SlidersHorizontal size={14} />}
- isLabelHidden
- />
<XDSTab
value="theme"
label="Theme"
@@ -975,15 +945,6 @@ export function PlaygroundClient({defaultIsMobile}: PlaygroundClientProps) {
setMobileTab('code');
}}
/>
- <XDSSideNavItem
- label="Properties"
- icon={SlidersHorizontal}
- isSelected={activeView === 'property'}
- onClick={() => {
- setActiveView('property');
- setMobileTab('property');
- }}
- />
<XDSSideNavItem
label="Theme"
icon={Palette}
@@ -1064,26 +1025,6 @@ export function PlaygroundClient({defaultIsMobile}: PlaygroundClientProps) {
/>
</div>
- {activeView === 'property' && (
- <PropertyPanel
- code={code}
- onCodeChange={setCode}
- onRevealInCode={revealInCode}
- onFlashInstance={selectInstance}
- externalSelection={
- targetedComponent != null
- ? {
- component: targetedComponent,
- instanceIndex: targetedInstance,
- }
- : undefined
- }
- onExternalSelectionConsumed={() => {
- setTargetedComponent(null);
- }}
- />
- )}
-
{/* 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. */}
@@ -1210,8 +1151,6 @@ export function PlaygroundClient({defaultIsMobile}: PlaygroundClientProps) {
onOpenChange={open => {
if (open) {
setShareUrl(window.location.href);
- // Snapshot the live (ref-held) theme so the download
- // link below can derive its href from reactive state.
setExportTheme(
customThemeRef.current ?? editorInitialTheme,
);
@@ -1274,11 +1213,6 @@ export function PlaygroundClient({defaultIsMobile}: PlaygroundClientProps) {
icon={<Download size={16} />}
onClick={() => downloadLinkRef.current?.click()}
/>
- {/* The real download target: a normally-rendered
- link whose href/download come from reactive
- state. The button above clicks it, so the
- browser performs a native download without us
- fabricating an <a> in the handler. */}
{themeExport && (
<a
ref={downloadLinkRef}
diff --git a/apps/docsite/src/app/playground/PropertyPanel.tsx b/apps/docsite/src/app/playground/PropertyPanel.tsx
index c3d98ad45c..72ca556799 100644
--- a/apps/docsite/src/app/playground/PropertyPanel.tsx
+++ b/apps/docsite/src/app/playground/PropertyPanel.tsx
@@ -2,35 +2,33 @@
/**
* @file PropertyPanel.tsx
- * @input Current editor code + onCodeChange callback
- * @output Component selector + instance picker + literal-bound prop knobs
- * @position Playground left panel — "Property" tab.
+ * @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, 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; enum controls preserve
- * typed option values for mixed literal unions. Props set to an expression are
- * shown read-only ("set in code") to avoid clobbering.
+ * 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
+ * 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
+ * values for mixed literal unions. 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 {XDSLayout, XDSLayoutContent, XDSLayoutFooter} from '@xds/core/Layout';
+import {XDSText} 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 {XDSDropdownMenu} from '@xds/core/DropdownMenu';
-// SegmentedControl removed — targeting selects the exact instance.
-import {ChevronDown} from 'lucide-react';
+import {XDSList, XDSListItem} from '@xds/core/List';
+import {XDSButton} from '@xds/core/Button';
import {
coerceDefault,
coerceEnumOption,
@@ -46,36 +44,21 @@ import {
type AttrInfo,
type InstanceInfo,
} from './babelParser';
-import {getComponentByModule, getUsedComponents} from './usedComponents';
+import {getComponentByModule} 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)',
+ // Cap the scrollable content area. The popover itself is unbounded, so the
+ // footer always sits directly below the content, outside the scroll region.
+ contentScroll: {
+ maxHeight: 360,
},
- scroll: {
- flex: 1,
- minHeight: 0,
- overflow: 'auto',
- padding: 'var(--spacing-3)',
- paddingBlockStart: 0,
+ applyBtn: {
+ width: '100%',
},
- row: {
- paddingBlock: 'var(--spacing-2)',
- },
- control: {
- flexBasis: 160,
- flexShrink: 0,
- display: 'flex',
- justifyContent: 'flex-end',
+ inputControl: {
+ width: 160,
},
emptyWrap: {
flex: 1,
@@ -98,21 +81,31 @@ function isEditable(control: PropControlDescriptor, attr?: AttrInfo): boolean {
);
}
+// Prop types that have no inline control in the popover panel 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([
+ 'ReactNode',
+ 'StyleXStyles',
+ 'AriaRole',
+]);
+
+/** Whether a prop can be edited through the panel (and should be shown). */
+function isSupportedProp(prop: PropDoc): boolean {
+ if (UNSUPPORTED_PROP_TYPES.has(prop.type.trim())) {
+ return false;
+ }
+ return isEditable(parsePropType(prop.type, prop.name, prop.slotElements));
+}
+
interface PropRowProps {
prop: PropDoc;
instance: InstanceInfo;
code: string;
onCodeChange: (code: string) => void;
- onRevealInCode?: (offset: number) => void;
}
-function PropRow({
- prop,
- instance,
- code,
- onCodeChange,
- onRevealInCode,
-}: PropRowProps) {
+function PropRow({prop, instance, code, onCodeChange}: PropRowProps) {
const control = useMemo(
() => parsePropType(prop.type, prop.name, prop.slotElements),
[prop],
@@ -172,27 +165,11 @@ function PropRow({
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>
- );
- }
+ controlEl = (
+ <XDSText type="supporting" color={attr ? 'secondary' : 'disabled'}>
+ {attr ? 'set in code' : '—'}
+ </XDSText>
+ );
} else if (control.kind === 'boolean') {
const checked = attr
? attr.value === true
@@ -216,6 +193,7 @@ function PropRow({
value={value}
options={control.options}
onChange={next => commit('enum', coerceEnumOption(control, next))}
+ xstyle={s.inputControl}
/>
);
} else if (control.kind === 'string') {
@@ -227,6 +205,7 @@ function PropRow({
placeholder="value"
value={value}
onChange={next => commit('string', next)}
+ xstyle={s.inputControl}
/>
);
} else {
@@ -238,24 +217,20 @@ function PropRow({
isLabelHidden
value={value}
onChange={next => commit('number', next)}
+ xstyle={s.inputControl}
/>
);
}
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>
+ <XDSListItem
+ label={
+ <XDSText type="body" weight="bold">
+ {prop.name}
+ </XDSText>
+ }
+ endContent={controlEl}
+ />
);
}
@@ -267,77 +242,53 @@ interface ExternalSelection {
interface PropertyPanelProps {
code: string;
onCodeChange: (code: string) => void;
- onRevealInCode?: (offset: number) => void;
- onFlashInstance?: (component: string, index: number) => void;
- /** Driven by the targeting system — overrides the current selection once. */
- externalSelection?: ExternalSelection;
- onExternalSelectionConsumed?: () => void;
+ /** The component instance to edit (chosen via the in-preview selection). */
+ externalSelection: ExternalSelection;
+ /** Called after edits are flushed via "Apply" (e.g. to close the popover). */
+ onApplied?: () => void;
}
export function PropertyPanel({
code,
onCodeChange,
- onRevealInCode,
- onFlashInstance,
externalSelection,
- onExternalSelectionConsumed,
+ onApplied,
}: PropertyPanelProps) {
- const [selected, setSelected] = useState<string | null>(null);
- const [instanceIndex, setInstanceIndex] = useState(0);
+ const {component: selected, instanceIndex} = externalSelection;
const lastInstances = useRef<InstanceInfo[]>([]);
- // Re-parse on every code change; keep the last good parse on syntax errors.
+ // Buffer prop edits locally; knobs mutate the draft and only take effect when
+ // the user clicks "Apply". Re-sync whenever the upstream source changes (after
+ // an Apply round-trips, or when the code is edited elsewhere).
+ const [draft, setDraft] = useState(code);
+ useEffect(() => {
+ setDraft(code);
+ }, [code]);
+ const isDirty = draft !== code;
+ const applyChanges = () => {
+ if (isDirty) {
+ onCodeChange(draft);
+ }
+ onApplied?.();
+ };
+
+ // Re-parse the draft on every change; keep the last good parse on syntax
+ // errors.
const instances = useMemo(() => {
- const parsed = analyzeCode(code);
+ const parsed = analyzeCode(draft);
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]);
+ }, [draft]);
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]);
-
- // Apply external selection from the targeting system.
- useEffect(() => {
- if (!externalSelection) {
- return;
- }
- const {component, instanceIndex: idx} = externalSelection;
- if (used.some(u => u.module === component)) {
- setSelected(component);
- setInstanceIndex(idx);
- }
- onExternalSelectionConsumed?.();
- }, [externalSelection, used, onExternalSelectionConsumed]);
-
- if (used.length === 0) {
+ if (instances.length === 0) {
return (
<div {...stylex.props(s.emptyWrap)}>
<XDSEmptyState
@@ -349,107 +300,64 @@ export function PropertyPanel({
);
}
- const entry = selected ? getComponentByModule(selected) : undefined;
+ const entry = getComponentByModule(selected);
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 selectedLabel =
- used.find(u => u.module === selected)?.label ?? selected;
+ const editableProps = props.filter(isSupportedProp);
+ const required = editableProps.filter(p => p.required);
+ const optional = editableProps.filter(p => !p.required);
- const menuItems =
- used.length > 1
- ? used.map(u => ({
- label: u.count > 1 ? `${u.label} (${u.count})` : u.label,
- onClick: () => {
- setSelected(u.module);
- setInstanceIndex(0);
- onFlashInstance?.(u.module, 0);
- },
- }))
- : [];
+ let body: React.ReactNode;
+ if (!entry) {
+ body = (
+ <XDSText type="supporting" color="secondary">
+ {selected} is not part of @xds/core — no editable props.
+ </XDSText>
+ );
+ } else if (editableProps.length === 0) {
+ body = (
+ <XDSText type="supporting" color="secondary">
+ {entry.displayName} has no editable props.
+ </XDSText>
+ );
+ } else if (targetInstance == null) {
+ body = null;
+ } else {
+ body = (
+ <XDSList>
+ {[...required, ...optional].map(prop => (
+ <PropRow
+ key={prop.name}
+ prop={prop}
+ instance={targetInstance}
+ code={draft}
+ onCodeChange={setDraft}
+ />
+ ))}
+ </XDSList>
+ );
+ }
return (
- <div {...stylex.props(s.root)}>
- <div {...stylex.props(s.header)}>
- <XDSVStack gap={2}>
- <XDSHStack gap={0} vAlign="center">
- <XDSHeading level={3}>{selectedLabel}</XDSHeading>
- {menuItems.length > 0 && (
- <XDSDropdownMenu
- button={{
- label: 'Switch component',
- tooltip: 'Switch component',
- variant: 'ghost',
- size: 'sm',
- isIconOnly: true,
- icon: <ChevronDown size={16} />,
- }}
- hasChevron={false}
- items={menuItems}
- />
- )}
- </XDSHStack>
- </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>
+ <XDSLayout
+ height="auto"
+ content={
+ <XDSLayoutContent padding={3} xstyle={s.contentScroll}>
+ {body}
+ </XDSLayoutContent>
+ }
+ footer={
+ <XDSLayoutFooter hasDivider padding={3}>
+ <XDSButton
+ label="Apply"
+ variant="primary"
+ isDisabled={!isDirty}
+ onClick={applyChanges}
+ xstyle={s.applyBtn}
+ />
+ </XDSLayoutFooter>
+ }
+ />
);
}
diff --git a/apps/docsite/src/app/playground/usedComponents.ts b/apps/docsite/src/app/playground/usedComponents.ts
index 28056336da..0a914a7475 100644
--- a/apps/docsite/src/app/playground/usedComponents.ts
+++ b/apps/docsite/src/app/playground/usedComponents.ts
@@ -2,16 +2,15 @@
/**
* @file usedComponents.ts
- * @input Generated component registry + detected JSX instances
- * @output Module-name → ComponentEntry lookup; distinct used-component list
- * @position Playground Property tab support.
+ * @input Generated component registry
+ * @output Module-name → ComponentEntry lookup
+ * @position Playground Properties popover support.
*/
import {
components,
type ComponentEntry,
} from '../../generated/componentRegistry';
-import type {InstanceInfo} from './babelParser';
const byModuleName: Map<string, ComponentEntry> = (() => {
const map = new Map<string, ComponentEntry>();
@@ -31,35 +30,3 @@ export function getComponentByModule(
): 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,
- };
- });
-}
diff --git a/apps/docsite/src/components/component-detail/parsePropType.ts b/apps/docsite/src/components/component-detail/parsePropType.ts
index 18dc08285e..5ed0ef7e22 100644
--- a/apps/docsite/src/components/component-detail/parsePropType.ts
+++ b/apps/docsite/src/components/component-detail/parsePropType.ts
@@ -221,6 +221,17 @@ export function parsePropType(
}
const parts = splitUnion(t);
+
+ // A union of only the primitives `string`/`number` (e.g. `number | string`,
+ // optionally nullable) is editable as free text — accepts e.g. "64px" or 64.
+ const nonNullishParts = parts.filter(p => p !== 'null' && p !== 'undefined');
+ if (
+ nonNullishParts.length > 0 &&
+ nonNullishParts.every(p => p === 'string' || p === 'number')
+ ) {
+ return {kind: 'string'};
+ }
+
const literals: string[] = [];
const optionValues: Record<string, EnumOptionValue> = {};
let allowEmpty = false;