An open source design system that's fully customizable and agent ready
TypeScript
feat(sandbox): v0-style preview shell with live previews (#1203)
David Petersen470c29236385
diff --git a/apps/sandbox/next.config.mjs b/apps/sandbox/next.config.mjsindex fe32ba179b..8340223093 100644--- a/apps/sandbox/next.config.mjs+++ b/apps/sandbox/next.config.mjs@@ -20,6 +20,9 @@ const nextConfig = {output: 'export',trailingSlash: true,basePath: process.env.SANDBOX_BASE_PATH || '',+ env: {+ NEXT_PUBLIC_BASE_PATH: process.env.SANDBOX_BASE_PATH || '',+ },transpilePackages: [// Only transpile @xds/core in source mode — in dist mode, it's pre-built....(useSource ? ['@xds/core'] : []),diff --git a/apps/sandbox/src/app/(fullscreen)/PreviewShell.tsx b/apps/sandbox/src/app/(fullscreen)/PreviewShell.tsxnew file mode 100644index 0000000000..1943becd27--- /dev/null+++ b/apps/sandbox/src/app/(fullscreen)/PreviewShell.tsx@@ -0,0 +1,320 @@+'use client';++import {useState, useCallback, useMemo} from 'react';+import {usePathname, useRouter} from 'next/navigation';+import {XDSText} from '@xds/core/Text';+import {XDSButton} from '@xds/core/Button';+import {XDSCodeBlock} from '@xds/core/CodeBlock';+import {XDSCommandPalette} from '@xds/core/CommandPalette';+import {createStaticSource} from '@xds/core/Typeahead';+import {+ XDSSegmentedControl,+ XDSSegmentedControlItem,+} from '@xds/core/SegmentedControl';+import {categories} from '../sandboxPages';+import {sourceRegistry} from '../../generated/sourceRegistry';++function EyeIcon(props: React.SVGProps<SVGSVGElement>) {+ return (+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" {...props}>+ <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" />+ <circle cx="12" cy="12" r="3" />+ </svg>+ );+}++function CodeIcon(props: React.SVGProps<SVGSVGElement>) {+ return (+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" {...props}>+ <polyline points="16 18 22 12 16 6" />+ <polyline points="8 6 2 12 8 18" />+ </svg>+ );+}++function CopyIcon(props: React.SVGProps<SVGSVGElement>) {+ return (+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" {...props}>+ <rect x="9" y="9" width="13" height="13" rx="2" ry="2" />+ <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" />+ </svg>+ );+}++function CheckIcon(props: React.SVGProps<SVGSVGElement>) {+ return (+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" {...props}>+ <polyline points="20 6 9 17 4 12" />+ </svg>+ );+}++function DesktopIcon(props: React.SVGProps<SVGSVGElement>) {+ return (+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" {...props}>+ <rect x="2" y="3" width="20" height="14" rx="2" ry="2" />+ <line x1="8" y1="21" x2="16" y2="21" />+ <line x1="12" y1="17" x2="12" y2="21" />+ </svg>+ );+}++function TabletIcon(props: React.SVGProps<SVGSVGElement>) {+ return (+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" {...props}>+ <rect x="4" y="2" width="16" height="20" rx="2" ry="2" />+ <line x1="12" y1="18" x2="12.01" y2="18" />+ </svg>+ );+}++function PhoneIcon(props: React.SVGProps<SVGSVGElement>) {+ return (+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" {...props}>+ <rect x="5" y="2" width="14" height="20" rx="2" ry="2" />+ <line x1="12" y1="18" x2="12.01" y2="18" />+ </svg>+ );+}++function ChevronDownIcon(props: React.SVGProps<SVGSVGElement>) {+ return (+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" {...props}>+ <polyline points="6 9 12 15 18 9" />+ </svg>+ );+}++type ViewportSize = 'desktop' | 'tablet' | 'mobile';+const viewportWidths: Record<ViewportSize, string> = {+ desktop: '100%',+ tablet: '768px',+ mobile: '375px',+};++export function PreviewShell({children}: {children: React.ReactNode}) {+ const pathname = usePathname();+ const router = useRouter();+ const [view, setView] = useState<'preview' | 'code'>('preview');+ const [viewport, setViewport] = useState<ViewportSize>('desktop');+ const [copied, setCopied] = useState(false);++ // Find current page name from the registry+ const currentPage = useMemo(() => {+ for (const cat of categories) {+ for (const page of cat.pages) {+ const normalizedHref = page.href.replace(/\/$/, '');+ const normalizedPath = pathname.replace(/\/$/, '');+ if (normalizedHref === normalizedPath) return {page, category: cat.label};+ }+ }+ return null;+ }, [pathname]);++ const pageName = currentPage?.page.name ?? (() => {+ const segments = pathname.replace(/\/$/, '').split('/');+ return segments[segments.length - 1]+ ?.replace(/-/g, ' ')+ .replace(/\b\w/g, c => c.toUpperCase()) ?? 'Preview';+ })();++ const [paletteOpen, setPaletteOpen] = useState(false);++ // Build searchable items for the command palette+ const searchSource = useMemo(() => {+ const items = categories.flatMap(cat =>+ cat.pages.map(page => ({+ id: page.href,+ label: page.name,+ auxiliaryData: {group: cat.label, description: page.description},+ })),+ );+ return createStaticSource(items);+ }, []);++ const resolvedSource = sourceRegistry[pathname] ?? sourceRegistry[pathname.replace(/\/$/, '') + '/'] ?? null;++ const handleViewChange = useCallback(+ (v: string) => {+ setView(v as 'preview' | 'code');+ },+ [],+ );++ const handleCopy = useCallback(async () => {+ if (!resolvedSource) return;+ await navigator.clipboard.writeText(resolvedSource);+ setCopied(true);+ setTimeout(() => setCopied(false), 2000);+ }, [resolvedSource]);++ return (+ <div style={{display: 'flex', flexDirection: 'column', height: '100vh'}}>+ {/* Toolbar */}+ <div+ style={{+ display: 'flex',+ alignItems: 'center',+ gap: 8,+ padding: '6px 12px',+ borderBottom: '1px solid var(--color-border-emphasized)',+ backgroundColor: '#f8f8f8',+ flexShrink: 0,+ zIndex: 10,+ }}>+ <div style={{flex: 1, minWidth: 0}}>+ <button+ onClick={() => setPaletteOpen(true)}+ style={{+ display: 'inline-flex',+ alignItems: 'center',+ gap: 4,+ padding: '4px 8px',+ border: 'none',+ background: 'none',+ cursor: 'pointer',+ borderRadius: 6,+ fontSize: 13,+ fontWeight: 600,+ color: 'inherit',+ }}>+ {pageName}+ <ChevronDownIcon width={14} height={14} style={{opacity: 0.5}} />+ </button>+ </div>++ <XDSCommandPalette+ isOpen={paletteOpen}+ onOpenChange={setPaletteOpen}+ searchSource={searchSource}+ label="Navigate to page"+ onValueChange={value => {+ router.push(value);+ setPaletteOpen(false);+ }}+ width={480}+ renderItem={(item, isSelected) => (+ <div style={{+ display: 'flex',+ flexDirection: 'column',+ gap: 2,+ padding: '2px 0',+ fontWeight: isSelected ? 600 : 400,+ }}>+ <span>{item.label}</span>+ {(item.auxiliaryData as {description?: string})?.description && (+ <span style={{fontSize: 12, opacity: 0.6}}>+ {(item.auxiliaryData as {description?: string}).description}+ </span>+ )}+ </div>+ )}+ />++ <XDSSegmentedControl+ value={view}+ onChange={handleViewChange}+ label="Toggle preview or code view"+ size="sm">+ <XDSSegmentedControlItem+ value="preview"+ label="Preview"+ isLabelHidden+ icon={<EyeIcon width={14} height={14} />}+ />+ <XDSSegmentedControlItem+ value="code"+ label="Code"+ isLabelHidden+ icon={<CodeIcon width={14} height={14} />}+ />+ </XDSSegmentedControl>++ {view === 'preview' && (+ <XDSSegmentedControl+ value={viewport}+ onChange={v => setViewport(v as ViewportSize)}+ label="Viewport size"+ size="sm">+ <XDSSegmentedControlItem+ value="desktop"+ label="Desktop"+ isLabelHidden+ icon={<DesktopIcon width={14} height={14} />}+ />+ <XDSSegmentedControlItem+ value="tablet"+ label="Tablet"+ isLabelHidden+ icon={<TabletIcon width={14} height={14} />}+ />+ <XDSSegmentedControlItem+ value="mobile"+ label="Mobile"+ isLabelHidden+ icon={<PhoneIcon width={14} height={14} />}+ />+ </XDSSegmentedControl>+ )}++ <XDSButton+ variant="ghost"+ size="sm"+ label={copied ? 'Copied' : 'Copy source'}+ icon={+ copied+ ? <CheckIcon width={14} height={14} />+ : <CopyIcon width={14} height={14} />+ }+ onClick={handleCopy}+ />+ </div>++ {/* Content */}+ {view === 'preview' ? (+ <div+ style={{+ flex: 1,+ overflow: 'auto',+ display: 'flex',+ justifyContent: 'center',+ padding: viewport !== 'desktop' ? '24px 16px' : 0,+ backgroundColor: viewport === 'desktop'+ ? 'transparent'+ : '#f0f0f0',+ }}>+ <div+ style={{+ width: viewportWidths[viewport],+ maxWidth: '100%',+ height: viewport !== 'desktop' ? 'fit-content' : '100%',+ minHeight: viewport !== 'desktop' ? '100%' : undefined,+ overflow: 'auto',+ border: viewport !== 'desktop'+ ? '1px solid var(--color-border-emphasized)'+ : 'none',+ borderRadius: viewport !== 'desktop' ? 8 : 0,+ backgroundColor: 'var(--color-background-card)',+ }}>+ {children}+ </div>+ </div>+ ) : (+ <div style={{flex: 1, overflow: 'auto'}}>+ {resolvedSource ? (+ <XDSCodeBlock+ code={resolvedSource}+ language="tsx"+ hasLineNumbers+ hasCopyButton+ />+ ) : (+ <div style={{padding: 24, display: 'flex', alignItems: 'center', justifyContent: 'center'}}>+ <XDSText type="body" color="secondary">Source not available</XDSText>+ </div>+ )}+ </div>+ )}+ </div>+ );+}diff --git a/apps/sandbox/src/app/(fullscreen)/layout.tsx b/apps/sandbox/src/app/(fullscreen)/layout.tsxindex 582a783144..6179e6b201 100644--- a/apps/sandbox/src/app/(fullscreen)/layout.tsx+++ b/apps/sandbox/src/app/(fullscreen)/layout.tsx@@ -1,7 +1,9 @@+import {PreviewShell} from './PreviewShell';+export default function FullscreenLayout({children,}: {children: React.ReactNode;}) {- return <>{children}</>;+ return <PreviewShell>{children}</PreviewShell>;}diff --git a/apps/sandbox/src/app/ProjectCard.tsx b/apps/sandbox/src/app/ProjectCard.tsxindex 00017138f7..adbd5bfa8b 100644--- a/apps/sandbox/src/app/ProjectCard.tsx+++ b/apps/sandbox/src/app/ProjectCard.tsx@@ -1,16 +1,19 @@'use client';+import {useState} from 'react';import Link from 'next/link';import {XDSText} from '@xds/core/Text';import type {SandboxPage} from './sandboxPages';import {ImageIcon} from './icons';+const basePath = process.env.NEXT_PUBLIC_BASE_PATH || '';+export function ProjectCard({page}: {page: SandboxPage}) {+ const [iframeError, setIframeError] = useState(false);+return (<Linkhref={page.href}- target="_blank"- rel="noopener noreferrer"style={{textDecoration: 'none', color: 'inherit', display: 'flex'}}><divstyle={{@@ -27,20 +30,33 @@ export function ProjectCard({page}: {page: SandboxPage}) {width: '100%',height: 160,backgroundColor: 'var(--color-background-body)',- display: 'flex',- alignItems: 'center',- justifyContent: 'center',overflow: 'hidden',- flexShrink: 0,+ position: 'relative',}}>- <ImageIcon- style={{- width: 48,- height: 48,- opacity: 0.3,- color: 'var(--color-text-disabled)',- }}- />+ {iframeError ? (+ <div style={{display: 'flex', alignItems: 'center', justifyContent: 'center', height: '100%'}}>+ <ImageIcon style={{width: 48, height: 48, opacity: 0.3, color: 'var(--color-text-disabled)'}} />+ </div>+ ) : (+ <iframe+ src={`${basePath}${page.href}`}+ title={page.name}+ onError={() => setIframeError(true)}+ style={{+ width: 1280,+ height: 800,+ border: 'none',+ transform: 'scale(0.2)',+ transformOrigin: 'top left',+ position: 'absolute',+ top: 0,+ left: 0,+ pointerEvents: 'none',+ }}+ tabIndex={-1}+ loading="lazy"+ />+ )}</div><divstyle={{@@ -48,7 +64,6 @@ export function ProjectCard({page}: {page: SandboxPage}) {flexDirection: 'column',gap: 4,padding: '12px 16px',- flex: 1,}}><XDSText type="body" weight="semibold" maxLines={1}>{page.name}diff --git a/scripts/sync-templates.js b/scripts/sync-templates.jsindex f3726543a3..e75dd025bf 100644--- a/scripts/sync-templates.js+++ b/scripts/sync-templates.js@@ -81,6 +81,24 @@ ${entries.join(',\n')}`;}+function generateSourceRegistry(templates) {+ const entries = templates.map(t => {+ const pagePath = path.join(TEMPLATES_DIR, t.dirName, 'page.tsx');+ const source = fs.readFileSync(pagePath, 'utf-8');+ return ` ${JSON.stringify('/templates/' + t.dirName + '/')}: ${JSON.stringify(source)}`;+ });++ return `/**+ * AUTO-GENERATED by scripts/sync-templates.js — do not edit.+ * Maps template hrefs to their raw source code.+ */++export const sourceRegistry: Record<string, string> = {+${entries.join(',\n')}+};+`;+}+function generateRouteWrapper(template) {const depth = '../../../../../../../packages/cli/templates';return `/**@@ -107,6 +125,10 @@ async function main() {fs.writeFileSync(registryPath, generateRegistry(templates));console.log(` wrote ${path.relative(ROOT, registryPath)}`);+ const sourceRegistryPath = path.join(GENERATED_DIR, 'sourceRegistry.ts');+ fs.writeFileSync(sourceRegistryPath, generateSourceRegistry(templates));+ console.log(` wrote ${path.relative(ROOT, sourceRegistryPath)}`);+for (const t of templates) {const routeDir = path.join(ROUTES_DIR, t.dirName);fs.mkdirSync(routeDir, {recursive: true});