An open source design system that's fully customizable and agent ready
TypeScript
feat(docsite): point-and-click element targeting for playground preview (#2488)
Ernest599dcbc96245
diff --git a/apps/docsite/src/app/(preview)/playground-preview/layout.tsx b/apps/docsite/src/app/(preview)/playground-preview/layout.tsxindex 88cd1effad..fd85ed6f51 100644--- a/apps/docsite/src/app/(preview)/playground-preview/layout.tsx+++ b/apps/docsite/src/app/(preview)/playground-preview/layout.tsx@@ -18,6 +18,67 @@ export default function PreviewLayout({children}: {children: React.ReactNode}) {@media (prefers-reduced-motion: reduce) {.pg-flash { animation-duration: 0.01ms; }}++ /* ── Targeting overlay ── */+ .pg-targeting { cursor: crosshair !important; }+ .pg-targeting * { cursor: crosshair !important; }++ .pg-target-overlay {+ position: fixed;+ pointer-events: none;+ z-index: 999999;+ border: 2px solid var(--color-border-focus, #1877f2);+ border-radius: var(--radius-element, 6px);+ background: rgba(24, 119, 242, 0.06);+ transition: top 80ms ease-out, left 80ms ease-out,+ width 80ms ease-out, height 80ms ease-out;+ display: none;+ }+ .pg-target-overlay[data-visible="true"] { display: block; }++ .pg-target-label {+ position: absolute;+ bottom: 100%;+ left: -2px;+ margin-bottom: 4px;+ padding: 2px 8px;+ font: 500 11px/16px ui-sans-serif, system-ui, sans-serif;+ color: #fff;+ background: var(--color-border-focus, #1877f2);+ border-radius: 4px;+ white-space: nowrap;+ user-select: none;+ }+ .pg-target-label-bottom {+ top: 100%;+ bottom: auto;+ margin-top: 4px;+ margin-bottom: 0;+ }++ .pg-target-selection {+ position: fixed;+ pointer-events: none;+ z-index: 999998;+ border: 2px solid var(--color-border-focus, #1877f2);+ border-radius: var(--radius-element, 6px);+ background: rgba(24, 119, 242, 0.06);+ display: none;+ }+ .pg-target-selection[data-visible="true"] { display: block; }++ .pg-target-selection .pg-target-label {+ position: absolute;+ bottom: 100%;+ left: -2px;+ margin-bottom: 4px;+ }+ .pg-target-selection .pg-target-label-bottom {+ top: 100%;+ bottom: auto;+ margin-top: 4px;+ margin-bottom: 0;+ }`}</style>{children}</>diff --git a/apps/docsite/src/app/(preview)/playground-preview/page.tsx b/apps/docsite/src/app/(preview)/playground-preview/page.tsxindex 5376fd7e74..baa2061390 100644--- a/apps/docsite/src/app/(preview)/playground-preview/page.tsx+++ b/apps/docsite/src/app/(preview)/playground-preview/page.tsx@@ -97,7 +97,91 @@ type PreviewMessage =| {type: 'preview-code'; code: string}| {type: 'preview-clear'}| {type: 'preview-theme'; mode?: string; theme?: string}- | {type: 'preview-highlight'; id: string};+ | {type: 'preview-highlight'; id: string}+ | {type: 'preview-select'; id: string}+ | {type: 'targeting-enable'}+ | {type: 'targeting-disable'};++/**+ * Persistent selection overlay — same visual treatment as the hover overlay+ * (blue border + tinted fill + component name label). Lives in a separate+ * DOM element so it can coexist with (or be hidden by) the hover overlay.+ */+const selectionState = {+ overlay: null as HTMLDivElement | null,+ label: null as HTMLDivElement | null,+ id: null as string | null,+ rafId: 0,+};++function ensureSelectionOverlay() {+ if (selectionState.overlay) {+ return;+ }+ const overlay = document.createElement('div');+ overlay.className = 'pg-target-selection';+ const label = document.createElement('div');+ label.className = 'pg-target-label';+ overlay.appendChild(label);+ document.body.appendChild(overlay);+ selectionState.overlay = overlay;+ selectionState.label = label;+}++function updateSelectionPosition() {+ const {overlay, label, id} = selectionState;+ if (!overlay || !label || !id) {+ return;+ }+ const el = document.querySelector<HTMLElement>(`[data-pg-id="${id}"]`);+ if (!el) {+ overlay.dataset.visible = 'false';+ return;+ }+ const rect = el.getBoundingClientRect();+ overlay.style.top = `${rect.top - 2}px`;+ overlay.style.left = `${rect.left - 2}px`;+ overlay.style.width = `${rect.width + 4}px`;+ overlay.style.height = `${rect.height + 4}px`;+ overlay.dataset.visible = 'true';++ const sep = id.lastIndexOf('#');+ label.textContent = sep >= 0 ? id.slice(0, sep) : id;++ if (rect.top < 28) {+ label.classList.add('pg-target-label-bottom');+ } else {+ label.classList.remove('pg-target-label-bottom');+ }+}++function selectElement(id: string) {+ ensureSelectionOverlay();+ selectionState.id = id;+ const el = document.querySelector<HTMLElement>(`[data-pg-id="${id}"]`);+ if (el) {+ el.scrollIntoView({block: 'nearest', behavior: 'smooth'});+ }+ updateSelectionPosition();++ // Keep the overlay positioned during scroll.+ cancelAnimationFrame(selectionState.rafId);+ const track = () => {+ updateSelectionPosition();+ if (selectionState.id === id) {+ selectionState.rafId = requestAnimationFrame(track);+ }+ };+ selectionState.rafId = requestAnimationFrame(track);+}++function clearSelectionOverlay() {+ cancelAnimationFrame(selectionState.rafId);+ selectionState.id = null;+ if (selectionState.overlay) {+ selectionState.overlay.dataset.visible = 'false';+ }+}/** Briefly flash a focus ring on the element marked with the given data-pg-id. */function flashElement(id: string) {@@ -113,6 +197,191 @@ function flashElement(id: string) {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+ * clicks back to the parent frame.+ */+function createTargetingController(+ postToParent: (msg: Record<string, unknown>) => void,+) {+ let enabled = false;+ let overlayEl: HTMLDivElement | null = null;+ let labelEl: HTMLDivElement | null = null;+ let rafId = 0;+ let lastHoveredId: string | null = null;++ function ensureOverlay() {+ if (overlayEl) {+ return;+ }+ overlayEl = document.createElement('div');+ overlayEl.className = 'pg-target-overlay';+ labelEl = document.createElement('div');+ labelEl.className = 'pg-target-label';+ overlayEl.appendChild(labelEl);+ document.body.appendChild(overlayEl);+ }++ function findTargetable(el: Element | null): HTMLElement | null {+ let node = el;+ while (node && node !== document.body) {+ if (node instanceof HTMLElement && node.dataset.pgId) {+ return node;+ }+ node = node.parentElement;+ }+ return null;+ }++ function parsePgId(id: string): {component: string; index: number} | null {+ const sep = id.lastIndexOf('#');+ if (sep < 0) {+ return null;+ }+ return {component: id.slice(0, sep), index: parseInt(id.slice(sep + 1), 10)};+ }++ function positionOverlay(target: HTMLElement) {+ if (!overlayEl || !labelEl) {+ return;+ }+ const rect = target.getBoundingClientRect();+ const pgId = target.dataset.pgId ?? '';+ overlayEl.style.top = `${rect.top - 2}px`;+ overlayEl.style.left = `${rect.left - 2}px`;+ overlayEl.style.width = `${rect.width + 4}px`;+ overlayEl.style.height = `${rect.height + 4}px`;+ overlayEl.dataset.visible = 'true';++ const parsed = parsePgId(pgId);+ labelEl.textContent = parsed ? parsed.component : pgId;++ // Flip label below if it would overflow above the viewport+ if (rect.top < 28) {+ labelEl.classList.add('pg-target-label-bottom');+ } else {+ labelEl.classList.remove('pg-target-label-bottom');+ }+ }++ function hideOverlay() {+ if (overlayEl) {+ overlayEl.dataset.visible = 'false';+ }+ lastHoveredId = null;+ }++ function clearSelection() {+ clearSelectionOverlay();+ }++ function onMouseMove(e: MouseEvent) {+ cancelAnimationFrame(rafId);+ rafId = requestAnimationFrame(() => {+ // Hide overlay temporarily to hit-test through it+ if (overlayEl) {+ overlayEl.style.display = 'none';+ }+ const hit = document.elementFromPoint(e.clientX, e.clientY);+ if (overlayEl) {+ overlayEl.style.display = '';+ }++ const target = findTargetable(hit);+ if (!target) {+ hideOverlay();+ postToParent({type: 'targeting-hover', id: null});+ return;+ }++ const id = target.dataset.pgId ?? '';+ if (id !== lastHoveredId) {+ lastHoveredId = id;+ positionOverlay(target);+ const parsed = parsePgId(id);+ postToParent({+ type: 'targeting-hover',+ id,+ component: parsed?.component ?? null,+ index: parsed?.index ?? 0,+ });+ }+ });+ }++ function onClick(e: MouseEvent) {+ e.preventDefault();+ e.stopPropagation();+ e.stopImmediatePropagation();++ if (overlayEl) {+ overlayEl.style.display = 'none';+ }+ const hit = document.elementFromPoint(e.clientX, e.clientY);+ if (overlayEl) {+ overlayEl.style.display = '';+ }++ const target = findTargetable(hit);+ if (!target) {+ return;+ }++ const id = target.dataset.pgId ?? '';+ const parsed = parsePgId(id);+ if (!parsed) {+ return;+ }++ clearSelection();+ selectElement(id);++ postToParent({+ type: 'targeting-select',+ id,+ component: parsed.component,+ index: parsed.index,+ });+ }++ function onKeyDown(e: KeyboardEvent) {+ if (e.key === 'Escape') {+ e.preventDefault();+ disable();+ postToParent({type: 'targeting-exit'});+ }+ }++ function enable() {+ if (enabled) {+ return;+ }+ enabled = true;+ clearSelection();+ ensureOverlay();+ document.documentElement.classList.add('pg-targeting');+ document.addEventListener('mousemove', onMouseMove, true);+ document.addEventListener('click', onClick, true);+ document.addEventListener('keydown', onKeyDown, true);+ }++ function disable() {+ if (!enabled) {+ return;+ }+ enabled = false;+ cancelAnimationFrame(rafId);+ document.documentElement.classList.remove('pg-targeting');+ document.removeEventListener('mousemove', onMouseMove, true);+ document.removeEventListener('click', onClick, true);+ document.removeEventListener('keydown', onKeyDown, true);+ hideOverlay();+ }++ return {enable, disable, clearSelection};+}+function isPreviewMessage(data: unknown): data is PreviewMessage {return (typeof data === 'object' &&@@ -159,14 +428,18 @@ export default function PreviewPage() {window.parent.postMessage(msg, '*');}, []);+ const targetingRef = useRef<ReturnType<typeof createTargetingController> | null>(null);+ if (targetingRef.current == null && typeof window !== 'undefined') {+ targetingRef.current = createTargetingController(postToParent);+ }+const handleCode = useCallback((code: string) => {const result = runCode(code);if (result.Component) {setComponent(() => result.Component);setError(null);- // Reset to fill so the next measurement runs against natural (block- // flow) sizing rather than a previously-centered layout.+ clearSelectionOverlay();setFill(true);setResetKey(k => k + 1);postToParent({type: 'preview-rendered'});@@ -223,6 +496,15 @@ export default function PreviewPage() {case 'preview-highlight':flashElement(event.data.id);break;+ case 'preview-select':+ selectElement(event.data.id);+ break;+ case 'targeting-enable':+ targetingRef.current?.enable();+ break;+ case 'targeting-disable':+ targetingRef.current?.disable();+ break;}}diff --git a/apps/docsite/src/app/(site)/templates/[slug]/page.tsx b/apps/docsite/src/app/(site)/templates/[slug]/page.tsxindex 2a5c2e79b8..f1a27c3c16 100644--- a/apps/docsite/src/app/(site)/templates/[slug]/page.tsx+++ b/apps/docsite/src/app/(site)/templates/[slug]/page.tsx@@ -1,17 +1,12 @@// Copyright (c) Meta Platforms, Inc. and affiliates./**- * Page type: template viewer- * Preview a template + view its source code.+ * Redirect /templates/<slug> to /templates?preview=<slug> so the preview+ * dialog opens on the gallery page. Keeps old direct links working.*/-import {notFound} from 'next/navigation';-import {XDSHeading, XDSText} from '@xds/core/Text';-import {XDSVStack} from '@xds/core/Layout';-import {XDSSection} from '@xds/core/Section';-import {XDSCodeBlock} from '@xds/core/CodeBlock';+import {redirect} from 'next/navigation';import {templates} from '../../../../generated/templateRegistry';-import {PlaygroundButton} from '../../../../components/PlaygroundButton';export function generateStaticParams() {return templates.map(t => ({slug: t.slug}));@@ -23,25 +18,5 @@ export default async function TemplatePage({params: Promise<{slug: string}>;}) {const {slug} = await params;- const template = templates.find(t => t.slug === slug);- if (!template) {- notFound();- }-- return (- <XDSSection maxWidth="lg" padding={6}>- <XDSVStack gap={4}>- <XDSHeading level={1}>{template.name}</XDSHeading>- <XDSText type="body" color="secondary">- {template.description}- </XDSText>- {template.source && (- <>- <PlaygroundButton source={template.source} />- <XDSCodeBlock code={template.source} language="tsx" hasCopyButton />- </>- )}- </XDSVStack>- </XDSSection>- );+ redirect(`/templates?preview=${slug}`);}diff --git a/apps/docsite/src/app/(site)/templates/page.tsx b/apps/docsite/src/app/(site)/templates/page.tsxindex b3f646d872..3403670d78 100644--- a/apps/docsite/src/app/(site)/templates/page.tsx+++ b/apps/docsite/src/app/(site)/templates/page.tsx@@ -6,7 +6,8 @@'use client';-import {useMemo} from 'react';+import {useCallback, useMemo} from 'react';+import {useSearchParams, useRouter, usePathname} from 'next/navigation';import * as stylex from '@stylexjs/stylex';import {XDSText, XDSHeading} from '@xds/core/Text';import {XDSVStack, XDSHStack} from '@xds/core/Layout';@@ -18,6 +19,11 @@ import {XDSBadge} from '@xds/core/Badge';import {templates} from '../../../generated/templateRegistry';import {TemplateThumbnail} from '../../../components/TemplateThumbnail';import {buildPlaygroundHref} from '../../../components/playgroundLink';+import {TemplatePreviewDialog} from '../../../components/TemplatePreviewDialog';+import type {TemplatePreviewItem} from '../../../components/TemplatePreviewDialog';++const GALLERY_MAX_WIDTH = 1600;+const CARD_MIN_WIDTH = 480;const styles = stylex.create({section: {@@ -26,25 +32,16 @@ const styles = stylex.create({heroTitle: {textAlign: 'center' as const,},- // Establishes a query container so the grid responds to its own available- // width (the content area), not the viewport.- gridContainer: {- containerType: 'inline-size',+ galleryWrap: {+ maxWidth: GALLERY_MAX_WIDTH,+ marginInline: 'auto',+ width: '100%',},- // Mobile-first: 1 column by default, 2 columns at >=800px, 3 at >=1200px of- // container width. min-width queries are used because StyleX reorders- // overlapping max-width queries (the wider one wins), which would prevent- // the 1-column case from ever triggering. Uses 1fr tracks so cards always- // fill the row width at every column count.grid: {display: 'grid',- columnGap: 'var(--spacing-4)',- rowGap: 'var(--spacing-6)',- gridTemplateColumns: {- default: 'minmax(0, 1fr)',- '@container (min-width: 800px)': 'repeat(2, minmax(0, 1fr))',- '@container (min-width: 1200px)': 'repeat(3, minmax(0, 1fr))',- },+ gap: 'var(--spacing-4)',+ justifyContent: 'center',+ gridTemplateColumns: `repeat(auto-fill, minmax(max(${CARD_MIN_WIDTH}px, calc((100% - var(--spacing-4)) / 2)), 1fr))`,},cardImage: {display: 'block',@@ -53,6 +50,13 @@ const styles = stylex.create({backgroundColor: 'var(--color-background-muted)',borderRadius: 'var(--radius-container)',},+ clickableCard: {+ outline: {+ default: 'none',+ ':focus-visible': '2px solid var(--color-accent)',+ },+ outlineOffset: '2px',+ },comingSoon: {height: '100%',display: 'flex',@@ -161,8 +165,60 @@ export default function TemplatesPage() {);}, []);+ // Flattened display-order list backing the preview dialog's prev/next+ // navigation, plus a slug -> index lookup for opening at a given card.+ const flatItems = useMemo<TemplatePreviewItem[]>(+ () =>+ groups.flatMap(g =>+ g.items.map(i => ({+ slug: i.slug,+ name: i.name,+ description: i.description,+ source: i.source,+ category: groupOf(i.category),+ })),+ ),+ [groups],+ );+ const indexBySlug = useMemo(() => {+ const m = new Map<string, number>();+ flatItems.forEach((it, i) => m.set(it.slug, i));+ return m;+ }, [flatItems]);++ const searchParams = useSearchParams();+ const router = useRouter();+ const pathname = usePathname();++ const previewSlug = searchParams.get('preview');+ const openIndex = previewSlug != null ? (indexBySlug.get(previewSlug) ?? null) : null;++ const setOpenIndex = useCallback(+ (index: number | null) => {+ const params = new URLSearchParams(searchParams.toString());+ if (index !== null && flatItems[index]) {+ params.set('preview', flatItems[index].slug);+ } else {+ params.delete('preview');+ }+ const qs = params.toString();+ router.replace(`${pathname}${qs ? `?${qs}` : ''}`, {scroll: false});+ },+ [searchParams, flatItems, router, pathname],+ );++ const openPreview = useCallback(+ (slug: string) => {+ const i = indexBySlug.get(slug);+ if (i !== undefined) {+ setOpenIndex(i);+ }+ },+ [indexBySlug, setOpenIndex],+ );+return (- <XDSSection maxWidth={2000} padding={6} xstyle={styles.section}>+ <XDSSection maxWidth={GALLERY_MAX_WIDTH} padding={6} xstyle={styles.section}><XDSVStack gap={8}><XDSVStack gap={2} style={{alignItems: 'center'}}><XDSHeading level={1} type="display-2" xstyle={styles.heroTitle}>@@ -176,20 +232,30 @@ export default function TemplatesPage() {{groups.map(({group, items}) => (<XDSVStack key={group} gap={4}><XDSHeading level={2}>{GROUP_LABELS[group] ?? group}</XDSHeading>- <div {...stylex.props(styles.gridContainer)}>+ <div {...stylex.props(styles.galleryWrap)}><div {...stylex.props(styles.grid)}>{items.map(item => (- <XDSCard key={item.slug} padding={0}>- {/* Inline style overrides --color-overlay for a stronger scrim.- CSS variable overrides in stylex.create hit a type mismatch- with StyleXStyles in TS 6+ / StyleX 0.18+ strict mode. */}- <div- style={- {- '--color-overlay':- 'color-mix(in srgb, var(--color-on-light) 78%, transparent)',- } as React.CSSProperties- }>+ <XDSCard+ key={item.slug}+ padding={0}+ xstyle={styles.clickableCard}+ role="button"+ tabIndex={0}+ aria-label={`Preview ${item.name}`}+ onClick={() => openPreview(item.slug)}+ onKeyDown={(e: React.KeyboardEvent) => {+ if (e.key === 'Enter' || e.key === ' ') {+ e.preventDefault();+ openPreview(item.slug);+ }+ }}+ style={+ {+ '--color-overlay':+ 'color-mix(in srgb, var(--color-on-light) 78%, transparent)',+ cursor: 'pointer',+ } as React.CSSProperties+ }><XDSOverlayshowOn="hover"scrim="dark"@@ -197,38 +263,42 @@ export default function TemplatesPage() {<div {...stylex.props(styles.overlayInner)}><XDSVStack gap={2}><XDSVStack gap={0.5}>- <XDSText- type="body"- weight="bold"+ <XDSHeading+ level={3}style={{color: '#fff'}}>{item.name}- </XDSText>+ </XDSHeading><XDSText- type="supporting"+ type="body"style={{color: 'rgba(255,255,255,0.7)'}}>{item.description.slice(0, 80)}{item.description.length > 80 ? '\u2026' : ''}</XDSText></XDSVStack>- <XDSHStack gap={2}>- <XDSButton- label="Preview"- variant="secondary"- size="sm"- href={item.href}- />- {item.source && (+ {/* Stop card-level click/keys from firing for+ the action buttons so each keeps its own+ behavior (the card itself opens the preview). */}+ <div+ onClick={e => e.stopPropagation()}+ onKeyDown={e => e.stopPropagation()}>+ <XDSHStack gap={2}><XDSButton- label="Open in Playground"+ label="Preview"variant="secondary"- size="sm"- onClick={() => {- window.location.href =- buildPlaygroundHref(item.source);- }}+ onClick={() => openPreview(item.slug)}/>- )}- </XDSHStack>+ {item.source && (+ <XDSButton+ label="Open in Playground"+ variant="secondary"+ onClick={() => {+ window.location.href =+ buildPlaygroundHref(item.source);+ }}+ />+ )}+ </XDSHStack>+ </div></XDSVStack></div>}>@@ -242,7 +312,6 @@ export default function TemplatesPage() {</div>)}</XDSOverlay>- </div></XDSCard>))}</div>@@ -250,6 +319,18 @@ export default function TemplatesPage() {</XDSVStack>))}</XDSVStack>++ <TemplatePreviewDialog+ items={flatItems}+ index={openIndex ?? 0}+ isOpen={openIndex !== null}+ onOpenChange={open => {+ if (!open) {+ setOpenIndex(null);+ }+ }}+ onIndexChange={setOpenIndex}+ /></XDSSection>);}diff --git a/apps/docsite/src/app/playground/PlaygroundClient.tsx b/apps/docsite/src/app/playground/PlaygroundClient.tsxindex b3e9f2f432..36bbf56700 100644--- a/apps/docsite/src/app/playground/PlaygroundClient.tsx+++ b/apps/docsite/src/app/playground/PlaygroundClient.tsx@@ -41,6 +41,7 @@ import {XDSSegmentedControlItem,} from '@xds/core/SegmentedControl';import {useXDSResizable, XDSResizeHandle} from '@xds/core/Resizable';+import {XDSToggleButton} from '@xds/core/ToggleButton';import {ArrowLeft,Moon,@@ -49,6 +50,7 @@ import {Smartphone,Maximize2,RotateCw,+ Crosshair,} from 'lucide-react';import githubLight from './themes/github-light.json';import githubDark from './themes/github-dark.json';@@ -355,6 +357,9 @@ export function PlaygroundClient() {const [statusFading, setStatusFading] = useState(false);const [copied, setCopied] = useState(false);const [previewReady, setPreviewReady] = useState(false);+ const [isTargeting, setIsTargeting] = useState(false);+ const [targetedComponent, setTargetedComponent] = useState<string | null>(null);+ const [targetedInstance, setTargetedInstance] = useState(0);// 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.@@ -420,14 +425,25 @@ export function PlaygroundClient() {[send],);- // Flash a focus ring on the DOM node for a given component instance.- const flashInstance = useCallback((component: string, index: number) => {+ // Persistently highlight the DOM node for a given component instance.+ const selectInstance = useCallback((component: string, index: number) => {iframeRef.current?.contentWindow?.postMessage(- {type: 'preview-highlight', id: `${component}#${index}`},+ {type: 'preview-select', id: `${component}#${index}`},window.location.origin,);}, []);+ const toggleTargeting = useCallback((pressed?: boolean) => {+ setIsTargeting(prev => {+ const next = pressed ?? !prev;+ iframeRef.current?.contentWindow?.postMessage(+ {type: next ? 'targeting-enable' : 'targeting-disable'},+ window.location.origin,+ );+ return next;+ });+ }, []);+useEffect(() => {const handler = (e: MessageEvent) => {if (e.source !== iframeRef.current?.contentWindow) {@@ -447,6 +463,19 @@ export function PlaygroundClient() {if (e.data?.type === 'preview-error') {setBuildStatus('error');}+ if (e.data?.type === 'targeting-select') {+ setTargetedComponent(e.data.component);+ setTargetedInstance(e.data.index);+ setActiveTab('property');+ setIsTargeting(false);+ iframeRef.current?.contentWindow?.postMessage(+ {type: 'targeting-disable'},+ window.location.origin,+ );+ }+ if (e.data?.type === 'targeting-exit') {+ setIsTargeting(false);+ }};window.addEventListener('message', handler);return () => window.removeEventListener('message', handler);@@ -677,7 +706,14 @@ export function PlaygroundClient() {code={code}onCodeChange={setCode}onRevealInCode={revealInCode}- onFlashInstance={flashInstance}+ onFlashInstance={selectInstance}+ externalSelection={targetedComponent != null ? {+ component: targetedComponent,+ instanceIndex: targetedInstance,+ } : undefined}+ onExternalSelectionConsumed={() => {+ setTargetedComponent(null);+ }}/>)}</div>@@ -712,6 +748,15 @@ export function PlaygroundClient() {icon={mode === 'light' ? <Moon size={20} /> : <Sun size={20} />}onClick={() => setMode(m => (m === 'light' ? 'dark' : 'light'))}/>+ <XDSToggleButton+ label="Target element"+ tooltip={isTargeting ? 'Exit targeting (Esc)' : 'Click to select an element'}+ isPressed={isTargeting}+ onPressedChange={toggleTargeting}+ size="md"+ isIconOnly+ icon={<Crosshair size={20} />}+ /></XDSHStack>}centerContent={diff --git a/apps/docsite/src/app/playground/PropertyPanel.tsx b/apps/docsite/src/app/playground/PropertyPanel.tsxindex 8f9967bd7b..69baab8b0a 100644--- a/apps/docsite/src/app/playground/PropertyPanel.tsx+++ b/apps/docsite/src/app/playground/PropertyPanel.tsx@@ -27,10 +27,9 @@ 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 {XDSDropdownMenu} from '@xds/core/DropdownMenu';+// SegmentedControl removed — targeting selects the exact instance.+import {ChevronDown} from 'lucide-react';import {coerceDefault,parsePropType,@@ -255,11 +254,19 @@ function PropRow({);}+interface ExternalSelection {+ component: string;+ instanceIndex: number;+}+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;}export function PropertyPanel({@@ -267,6 +274,8 @@ export function PropertyPanel({onCodeChange,onRevealInCode,onFlashInstance,+ externalSelection,+ onExternalSelectionConsumed,}: PropertyPanelProps) {const [selected, setSelected] = useState<string | null>(null);const [instanceIndex, setInstanceIndex] = useState(0);@@ -310,6 +319,19 @@ export function PropertyPanel({}}, [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) {return (<div {...stylex.props(s.emptyWrap)}>@@ -329,48 +351,42 @@ export function PropertyPanel({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,- }));+ const selectedLabel = used.find(u => u.module === selected)?.label ?? selected;++ 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);+ },+ }))+ : [];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>- )}+ <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>diff --git a/apps/docsite/src/components/TemplatePreviewDialog.tsx b/apps/docsite/src/components/TemplatePreviewDialog.tsxnew file mode 100644index 0000000000..bff843ab5f--- /dev/null+++ b/apps/docsite/src/components/TemplatePreviewDialog.tsx@@ -0,0 +1,343 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * TemplatePreviewDialog — opens a single template's live preview in a+ * large centered modal (instead of navigating to a full page), with+ * prev/next arrows to move quickly between templates in the gallery's+ * display order. Arrow keys (←/→) also navigate; Escape closes.+ *+ * The footer surfaces template metadata (category + name, description),+ * a copy-to-clipboard CLI scaffold command, and an Open in Playground+ * action. A floating close button sits at the top-right corner.+ *+ * The prev/next arrows are position:fixed inside the top-layer <dialog>,+ * so they sit in the backdrop gutters outside the dialog box.+ */++import {+ useCallback,+ useEffect,+ useDeferredValue,+ useState,+ useTransition,+} from 'react';+import * as stylex from '@stylexjs/stylex';+import {XDSIcon} from '@xds/core/Icon';+import {XDSText, XDSHeading} from '@xds/core/Text';+import {+ XDSVStack,+ XDSHStack,+ XDSLayout,+ XDSLayoutContent,+ XDSLayoutFooter,+} from '@xds/core/Layout';+import {XDSButton} from '@xds/core/Button';+import {XDSSkeleton} from '@xds/core/Skeleton';+import {XDSDialog} from '@xds/core/Dialog';+import {XDSTooltip} from '@xds/core/Tooltip';+import {TemplatePreviewSurface} from './TemplatePreviewSurface';+import {buildPlaygroundHref} from './playgroundLink';++export interface TemplatePreviewItem {+ slug: string;+ name: string;+ description?: string;+ source?: string;+ category?: string;+}++interface TemplatePreviewDialogProps {+ items: TemplatePreviewItem[];+ /** Index into `items` of the template to show. */+ index: number;+ isOpen: boolean;+ onOpenChange: (open: boolean) => void;+ /** Request a different template (prev/next). */+ onIndexChange: (index: number) => void;+}++const styles = stylex.create({+ dialogTall: {+ height: '86vh',+ borderRadius: 'var(--radius-page)',+ },+ body: {+ position: 'relative',+ display: 'flex',+ height: '100%',+ minHeight: 0,+ boxSizing: 'border-box',+ padding: '16px',+ },+ footerRow: {+ width: '100%',+ paddingInlineStart: '4px',+ paddingBlockEnd: '4px',+ },+ footerMeta: {+ flex: 1,+ minWidth: 0,+ },+ categoryPrefix: {+ color: 'var(--color-text-primary)',+ },+ footerNoPadding: {+ padding: 0,+ },+ copyPill: {+ display: 'inline-flex',+ alignItems: 'center',+ gap: 'var(--spacing-2)',+ backgroundColor: 'var(--color-background-card)',+ borderRadius: 'var(--radius-element)',+ paddingInline: 'var(--spacing-3)',+ height: 'var(--size-element-lg, 36px)',+ cursor: 'pointer',+ borderWidth: 'var(--border-width, 1px)',+ borderStyle: 'solid',+ borderColor: 'var(--color-border)',+ fontFamily: 'var(--font-family-mono, ui-monospace, monospace)',+ fontSize: 'var(--font-size-sm, 13px)',+ color: 'var(--color-text-primary)',+ userSelect: 'none',+ transitionProperty: 'background-color, border-color',+ transitionDuration: 'var(--duration-fast-min, 130ms)',+ transitionTimingFunction:+ 'var(--ease-standard, cubic-bezier(0.24, 1, 0.4, 1))',+ },+ copyPillHover: {+ backgroundColor: {+ ':hover':+ 'var(--color-background-card-hover, var(--color-background-muted))',+ },+ },+ copyPillText: {+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ },+ skeletonOverlay: {+ position: 'absolute',+ inset: '16px',+ zIndex: 5,+ borderRadius: 'var(--radius-container)',+ overflow: 'hidden',+ },+ closeButton: {+ position: 'absolute',+ top: 'var(--spacing-3)',+ insetInlineEnd: 'var(--spacing-3)',+ zIndex: 10,+ borderRadius: 'var(--radius-full)',+ backgroundColor: 'var(--color-background-card)',+ boxShadow: 'var(--shadow-high)',+ },+ navArrow: {+ position: 'fixed',+ top: '50%',+ transform: 'translateY(-50%)',+ zIndex: 1000,+ },+ navPrev: {+ insetInlineStart: 'var(--spacing-5)',+ },+ navNext: {+ insetInlineEnd: 'var(--spacing-5)',+ },+ navArrowButton: {+ borderRadius: 'var(--radius-full)',+ backgroundColor: 'var(--color-background-card)',+ boxShadow: 'var(--shadow-high)',+ },+});++export function TemplatePreviewDialog({+ items,+ index,+ isOpen,+ onOpenChange,+ onIndexChange,+}: TemplatePreviewDialogProps) {+ const [cmdCopied, setCmdCopied] = useState(false);+ const [isPending, startTransition] = useTransition();++ const count = items.length;+ const current = items[index];+ // The deferred index drives the heavy preview surface — it lags behind+ // the committed index during a transition, keeping the old template+ // visible and the dialog interactive while the next one loads.+ const deferredIndex = useDeferredValue(index);+ const deferredCurrent = items[deferredIndex];++ const go = (delta: number) => {+ if (count === 0) {+ return;+ }+ startTransition(() => {+ onIndexChange((index + delta + count) % count);+ });+ };++ useEffect(() => {+ if (!isOpen) {+ return;+ }+ const onKey = (e: KeyboardEvent) => {+ if (e.key === 'ArrowLeft') {+ e.preventDefault();+ go(-1);+ } else if (e.key === 'ArrowRight') {+ e.preventDefault();+ go(1);+ }+ };+ window.addEventListener('keydown', onKey);+ return () => window.removeEventListener('keydown', onKey);+ }, [isOpen, index, count]);++ // Reset the share-copied state when switching templates.+ useEffect(() => {+ setCmdCopied(false);+ }, [index]);++ if (!current) {+ return null;+ }++ const useCommand = `npx xds template ${current.slug} ./src/app/${current.slug}`;+ // Capture in a local const so the narrowing survives into the onClick+ // closure below (property access on `current` widens back to+ // `string | undefined` inside a deferred callback).+ const playgroundSource = current.source;++ const handleCopyCmd = useCallback(() => {+ navigator.clipboard.writeText(useCommand).then(() => {+ setCmdCopied(true);+ setTimeout(() => setCmdCopied(false), 2000);+ });+ }, [useCommand]);++ return (+ <XDSDialog+ isOpen={isOpen}+ onOpenChange={onOpenChange}+ width={1400}+ maxHeight="92vh"+ xstyle={styles.dialogTall}+ aria-label={current.name}>+ <XDSLayout+ height="fill"+ content={+ <XDSLayoutContent isScrollable={false} padding={0}>+ <div {...stylex.props(styles.body)}>+ <TemplatePreviewSurface+ key={deferredCurrent.slug}+ slug={deferredCurrent.slug}+ />+ {isPending && (+ <div {...stylex.props(styles.skeletonOverlay)}>+ <XDSSkeleton width="100%" height="100%" />+ </div>+ )}+ <div {...stylex.props(styles.closeButton)}>+ <XDSButton+ variant="ghost"+ isIconOnly+ label="Close preview"+ size="lg"+ icon={<XDSIcon icon="close" color="inherit" />}+ onClick={() => onOpenChange(false)}+ />+ </div>+ </div>+ </XDSLayoutContent>+ }+ footer={+ <XDSLayoutFooter xstyle={styles.footerNoPadding}>+ <XDSHStack gap={4} vAlign="end" xstyle={styles.footerRow}>+ <XDSVStack gap={0.5} xstyle={styles.footerMeta}>+ <XDSHeading level={2}>+ {current.category && (+ <span {...stylex.props(styles.categoryPrefix)}>+ {current.category}{' '}+ </span>+ )}+ {current.name}+ </XDSHeading>+ {current.description && (+ <XDSText type="body" color="primary">+ {current.description}+ </XDSText>+ )}+ </XDSVStack>+ <XDSHStack gap={2} vAlign="center">+ <button+ type="button"+ onClick={handleCopyCmd}+ aria-label="Copy install command"+ {...stylex.props(styles.copyPill, styles.copyPillHover)}>+ <span {...stylex.props(styles.copyPillText)}>+ {cmdCopied ? 'Copied!' : `npx xds template ${current.slug}`}+ </span>+ <XDSIcon+ icon={cmdCopied ? 'check' : 'copy'}+ size="sm"+ color="inherit"+ />+ </button>+ {playgroundSource && (+ <XDSButton+ label="Open in Playground"+ variant="primary"+ size="lg"+ onClick={() => {+ window.location.href =+ buildPlaygroundHref(playgroundSource);+ }}+ />+ )}+ </XDSHStack>+ </XDSHStack>+ </XDSLayoutFooter>+ }+ />++ {count > 1 && (+ <>+ <div {...stylex.props(styles.navArrow, styles.navPrev)}>+ <XDSTooltip+ content={`Previous: ${items[(index - 1 + count) % count]?.name}`}+ placement="end">+ <XDSButton+ variant="secondary"+ size="lg"+ isIconOnly+ label="Previous template"+ icon={<XDSIcon icon="chevronLeft" color="inherit" />}+ onClick={() => go(-1)}+ xstyle={styles.navArrowButton}+ />+ </XDSTooltip>+ </div>+ <div {...stylex.props(styles.navArrow, styles.navNext)}>+ <XDSTooltip+ content={`Next: ${items[(index + 1) % count]?.name}`}+ placement="start">+ <XDSButton+ variant="secondary"+ size="lg"+ isIconOnly+ label="Next template"+ icon={<XDSIcon icon="chevronRight" color="inherit" />}+ onClick={() => go(1)}+ xstyle={styles.navArrowButton}+ />+ </XDSTooltip>+ </div>+ </>+ )}+ </XDSDialog>+ );+}diff --git a/apps/docsite/src/components/TemplatePreviewSurface.module.css b/apps/docsite/src/components/TemplatePreviewSurface.module.cssnew file mode 100644index 0000000000..b71dd8f912--- /dev/null+++ b/apps/docsite/src/components/TemplatePreviewSurface.module.css@@ -0,0 +1,36 @@+/* Copyright (c) Meta Platforms, Inc. and affiliates. */++/* The preview "window". A fixed-height frame (flex-filled by the page+ wrapper) that contains the live template. It does not scroll itself —+ the template's own content region is the single scroll container. */+.frame {+ position: relative;+ width: 100%;+ max-width: 1600px;+ margin-inline: auto;+ flex: 1 1 auto;+ min-height: 0;+ /* The frame is the single scroll container. Fill-mode templates fit the+ frame exactly and scroll their own content region internally (no frame+ scroll); auto-height templates that are taller than the frame scroll+ here instead of pushing the document. */+ overflow: auto;+ border-radius: var(--radius-container);+ border: var(--border-width) solid var(--color-border);+ /* Read as a real themed app on the theme's body color. */+ background-color: var(--color-background-body);+}++/* Host nested app-shell templates.++ XDSAppShell fill mode sizes the shell to 100dvh (the viewport). Inside+ this preview frame that would overflow the frame and create a second+ (outer) scrollbar. Pin the shell to THIS frame's height instead so the+ template's own content region (#xds-app-shell-main) is the single+ scroll container, and the header + side nav stay fixed. The descendant+ selector outweighs StyleX's single-class height:100dvh without+ !important. */+.frame :global(.xds-app-shell) {+ height: 100%;+ min-height: 0;+}diff --git a/apps/docsite/src/components/TemplatePreviewSurface.tsx b/apps/docsite/src/components/TemplatePreviewSurface.tsxnew file mode 100644index 0000000000..c44a8c48ab--- /dev/null+++ b/apps/docsite/src/components/TemplatePreviewSurface.tsx@@ -0,0 +1,64 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * TemplatePreviewSurface — the live preview "window" for one template.+ *+ * Renders the template's real page.tsx component (shared+ * TEMPLATE_COMPONENTS map) at true scale inside the framed, internally-+ * scrollable surface (see TemplatePreviewSurface.module.css `.frame`).+ * Used by the preview dialog (TemplatePreviewDialog).+ */++import {Suspense} from 'react';+import * as stylex from '@stylexjs/stylex';+import {XDSText} from '@xds/core/Text';+import {XDSSkeleton} from '@xds/core/Skeleton';+import {XDSTheme} from '@xds/core/theme';+import {neutralTheme} from '@xds/theme-neutral/built';+import {useThemeMode} from '../app/providers';+import {getTemplateComponent} from './templateComponents';+import css from './TemplatePreviewSurface.module.css';++const styles = stylex.create({+ emptyState: {+ height: '100%',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ padding: 'var(--spacing-8)',+ },+ skeleton: {+ width: '100%',+ height: '100%',+ },+});++export function TemplatePreviewSurface({slug}: {slug: string}) {+ const {mode} = useThemeMode();+ const Component = getTemplateComponent(slug);++ return (+ <div className={css.frame}>+ {Component ? (+ <Suspense+ fallback={+ <div {...stylex.props(styles.skeleton)}>+ <XDSSkeleton width="100%" height="100%" />+ </div>+ }>+ <XDSTheme theme={neutralTheme} mode={mode}>+ <Component />+ </XDSTheme>+ </Suspense>+ ) : (+ <div {...stylex.props(styles.emptyState)}>+ <XDSText type="body" color="secondary">+ A live preview isn’t available for this template yet.+ </XDSText>+ </div>+ )}+ </div>+ );+}diff --git a/apps/docsite/src/components/TemplateThumbnail.tsx b/apps/docsite/src/components/TemplateThumbnail.tsxindex eba65263a4..1e5a2feae5 100644--- a/apps/docsite/src/components/TemplateThumbnail.tsx+++ b/apps/docsite/src/components/TemplateThumbnail.tsx@@ -2,8 +2,7 @@'use client';-import React, {- lazy,+import {Suspense,useRef,useState,@@ -15,6 +14,7 @@ import {XDSSkeleton} from '@xds/core/Skeleton';import {XDSTheme} from '@xds/core/theme';import {neutralTheme} from '@xds/theme-neutral/built';import {useThemeMode} from '../app/providers';+import {TEMPLATE_COMPONENTS} from './templateComponents';const FIXED_SCALE = 0.5;@@ -33,7 +33,7 @@ const styles = stylex.create({position: 'absolute' as const,top: 0,left: 0,- height: '200%',+ height: `${100 / FIXED_SCALE}%`,transformOrigin: 'top left',pointerEvents: 'none' as const,overflow: 'hidden',@@ -52,143 +52,6 @@ const styles = stylex.create({},});-/**- * Lazy-loaded template component registry.- * Maps slugs to dynamically imported template page components.- */-const TEMPLATE_COMPONENTS: Record<- string,- React.LazyExoticComponent<React.ComponentType>-> = {- 'ai-chat': lazy(- () => import('../../../../packages/cli/templates/pages/ai-chat/page'),- ),- 'ai-chat-artifact': lazy(- () =>- import('../../../../packages/cli/templates/pages/ai-chat-artifact/page'),- ),- 'ai-chat-landing': lazy(- () =>- import('../../../../packages/cli/templates/pages/ai-chat-landing/page'),- ),- blank: lazy(- () => import('../../../../packages/cli/templates/pages/blank/page'),- ),- 'centered-hero': lazy(- () => import('../../../../packages/cli/templates/pages/centered-hero/page'),- ),- 'classic-gallery': lazy(- () =>- import('../../../../packages/cli/templates/pages/classic-gallery/page'),- ),- 'contact-form': lazy(- () => import('../../../../packages/cli/templates/pages/contact-form/page'),- ),- dashboard: lazy(- () => import('../../../../packages/cli/templates/pages/dashboard/page'),- ),- 'dashboard-portfolio': lazy(- () =>- import('../../../../packages/cli/templates/pages/dashboard-portfolio/page'),- ),- 'detail-page': lazy(- () => import('../../../../packages/cli/templates/pages/detail-page/page'),- ),- documentation: lazy(- () => import('../../../../packages/cli/templates/pages/documentation/page'),- ),- 'documentation-design': lazy(- () =>- import('../../../../packages/cli/templates/pages/documentation-design/page'),- ),- 'documentation-technical': lazy(- () =>- import('../../../../packages/cli/templates/pages/documentation-technical/page'),- ),- editor: lazy(- () => import('../../../../packages/cli/templates/pages/editor/page'),- ),- 'file-explorer': lazy(- () => import('../../../../packages/cli/templates/pages/file-explorer/page'),- ),- 'form-two-column': lazy(- () =>- import('../../../../packages/cli/templates/pages/form-two-column/page'),- ),- 'gallery-hero': lazy(- () => import('../../../../packages/cli/templates/pages/gallery-hero/page'),- ),- ide: lazy(() => import('../../../../packages/cli/templates/pages/ide/page')),- library: lazy(- () => import('../../../../packages/cli/templates/pages/library/page'),- ),- login: lazy(- () => import('../../../../packages/cli/templates/pages/login/page'),- ),- 'login-card': lazy(- () => import('../../../../packages/cli/templates/pages/login-card/page'),- ),- 'login-split': lazy(- () => import('../../../../packages/cli/templates/pages/login-split/page'),- ),- 'login-sso': lazy(- () => import('../../../../packages/cli/templates/pages/login-sso/page'),- ),- 'mixed-gallery': lazy(- () => import('../../../../packages/cli/templates/pages/mixed-gallery/page'),- ),- 'payment-form': lazy(- () => import('../../../../packages/cli/templates/pages/payment-form/page'),- ),- 'product-detail': lazy(- () =>- import('../../../../packages/cli/templates/pages/product-detail/page'),- ),- 'product-gallery': lazy(- () =>- import('../../../../packages/cli/templates/pages/product-gallery/page'),- ),- settings: lazy(- () => import('../../../../packages/cli/templates/pages/settings/page'),- ),- 'settings-dialog': lazy(- () =>- import('../../../../packages/cli/templates/pages/settings-dialog/page'),- ),- 'settings-sidebar': lazy(- () =>- import('../../../../packages/cli/templates/pages/settings-sidebar/page'),- ),- 'side-gallery': lazy(- () => import('../../../../packages/cli/templates/pages/side-gallery/page'),- ),- table: lazy(- () => import('../../../../packages/cli/templates/pages/table/page'),- ),- 'table-grouped': lazy(- () => import('../../../../packages/cli/templates/pages/table-grouped/page'),- ),- 'table-page': lazy(- () => import('../../../../packages/cli/templates/pages/table-page/page'),- ),- 'table-page-chart': lazy(- () =>- import('../../../../packages/cli/templates/pages/table-page-chart/page'),- ),- 'table-page-heatmap-status': lazy(- () =>- import(- '../../../../packages/cli/templates/pages/table-page-heatmap-status/page'- ),- ),- 'table-page-shoe-store-heatmap': lazy(- () =>- import(- '../../../../packages/cli/templates/pages/table-page-shoe-store-heatmap/page'- ),- ),-};-export function TemplateThumbnail({slug}: {slug: string}) {const {mode} = useThemeMode();const containerRef = useRef<HTMLDivElement>(null);diff --git a/apps/docsite/src/components/templateComponents.ts b/apps/docsite/src/components/templateComponents.tsnew file mode 100644index 0000000000..9fc03e055f--- /dev/null+++ b/apps/docsite/src/components/templateComponents.ts@@ -0,0 +1,156 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * Shared lazy-loaded registry of template page components, keyed by slug.+ *+ * Both the templates gallery thumbnails (TemplateThumbnail) and the+ * preview dialog (TemplatePreviewDialog) render the template's real+ * `page.tsx` component, so the lazy import map lives here to keep a+ * single source of truth.+ *+ * SYNC: when a page template is added under+ * packages/cli/templates/pages/<slug>/, add a matching entry here.+ */++import {lazy} from 'react';+import type React from 'react';++export const TEMPLATE_COMPONENTS: Record<+ string,+ React.LazyExoticComponent<React.ComponentType>+> = {+ 'ai-chat': lazy(+ () => import('../../../../packages/cli/templates/pages/ai-chat/page'),+ ),+ 'ai-chat-artifact': lazy(+ () =>+ import('../../../../packages/cli/templates/pages/ai-chat-artifact/page'),+ ),+ 'ai-chat-landing': lazy(+ () =>+ import('../../../../packages/cli/templates/pages/ai-chat-landing/page'),+ ),+ blank: lazy(+ () => import('../../../../packages/cli/templates/pages/blank/page'),+ ),+ 'centered-hero': lazy(+ () => import('../../../../packages/cli/templates/pages/centered-hero/page'),+ ),+ 'classic-gallery': lazy(+ () =>+ import('../../../../packages/cli/templates/pages/classic-gallery/page'),+ ),+ 'contact-form': lazy(+ () => import('../../../../packages/cli/templates/pages/contact-form/page'),+ ),+ dashboard: lazy(+ () => import('../../../../packages/cli/templates/pages/dashboard/page'),+ ),+ 'dashboard-portfolio': lazy(+ () =>+ import('../../../../packages/cli/templates/pages/dashboard-portfolio/page'),+ ),+ 'detail-page': lazy(+ () => import('../../../../packages/cli/templates/pages/detail-page/page'),+ ),+ documentation: lazy(+ () => import('../../../../packages/cli/templates/pages/documentation/page'),+ ),+ 'documentation-design': lazy(+ () =>+ import('../../../../packages/cli/templates/pages/documentation-design/page'),+ ),+ 'documentation-technical': lazy(+ () =>+ import('../../../../packages/cli/templates/pages/documentation-technical/page'),+ ),+ editor: lazy(+ () => import('../../../../packages/cli/templates/pages/editor/page'),+ ),+ 'file-explorer': lazy(+ () => import('../../../../packages/cli/templates/pages/file-explorer/page'),+ ),+ 'form-two-column': lazy(+ () =>+ import('../../../../packages/cli/templates/pages/form-two-column/page'),+ ),+ 'gallery-hero': lazy(+ () => import('../../../../packages/cli/templates/pages/gallery-hero/page'),+ ),+ ide: lazy(() => import('../../../../packages/cli/templates/pages/ide/page')),+ library: lazy(+ () => import('../../../../packages/cli/templates/pages/library/page'),+ ),+ login: lazy(+ () => import('../../../../packages/cli/templates/pages/login/page'),+ ),+ 'login-card': lazy(+ () => import('../../../../packages/cli/templates/pages/login-card/page'),+ ),+ 'login-split': lazy(+ () => import('../../../../packages/cli/templates/pages/login-split/page'),+ ),+ 'login-sso': lazy(+ () => import('../../../../packages/cli/templates/pages/login-sso/page'),+ ),+ 'mixed-gallery': lazy(+ () => import('../../../../packages/cli/templates/pages/mixed-gallery/page'),+ ),+ 'payment-form': lazy(+ () => import('../../../../packages/cli/templates/pages/payment-form/page'),+ ),+ 'product-detail': lazy(+ () =>+ import('../../../../packages/cli/templates/pages/product-detail/page'),+ ),+ 'product-gallery': lazy(+ () =>+ import('../../../../packages/cli/templates/pages/product-gallery/page'),+ ),+ settings: lazy(+ () => import('../../../../packages/cli/templates/pages/settings/page'),+ ),+ 'settings-dialog': lazy(+ () =>+ import('../../../../packages/cli/templates/pages/settings-dialog/page'),+ ),+ 'settings-sidebar': lazy(+ () =>+ import('../../../../packages/cli/templates/pages/settings-sidebar/page'),+ ),+ 'side-gallery': lazy(+ () => import('../../../../packages/cli/templates/pages/side-gallery/page'),+ ),+ table: lazy(+ () => import('../../../../packages/cli/templates/pages/table/page'),+ ),+ 'table-grouped': lazy(+ () => import('../../../../packages/cli/templates/pages/table-grouped/page'),+ ),+ 'table-page': lazy(+ () => import('../../../../packages/cli/templates/pages/table-page/page'),+ ),+ 'table-page-chart': lazy(+ () =>+ import('../../../../packages/cli/templates/pages/table-page-chart/page'),+ ),+ 'table-page-heatmap-status': lazy(+ () =>+ import(+ '../../../../packages/cli/templates/pages/table-page-heatmap-status/page'+ ),+ ),+ 'table-page-shoe-store-heatmap': lazy(+ () =>+ import(+ '../../../../packages/cli/templates/pages/table-page-shoe-store-heatmap/page'+ ),+ ),+};++/** Resolve a template's lazy component by slug, or `undefined` if unknown. */+export function getTemplateComponent(+ slug: string,+): React.LazyExoticComponent<React.ComponentType> | undefined {+ return TEMPLATE_COMPONENTS[slug];+}