Skip to content

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

TypeScript

feat(sandbox): add scale support for block previews (#1428)

Joey66579bb9c7ac
diff --git a/apps/sandbox/package.json b/apps/sandbox/package.json
index d18fb63e25..0852a31f60 100644
--- a/apps/sandbox/package.json
+++ b/apps/sandbox/package.json
@@ -6,7 +6,7 @@
"build:deps": "yarn workspace @xds/core build && yarn workspace @xds/theme-default build && yarn workspace @xds/theme-neutral build && yarn workspace @xds/theme-brutalist build && yarn workspace @xds/theme-meta build && yarn workspace @xds/theme-whatsapp build && yarn workspace @xds/theme-daily build",
"generate:versions": "node scripts/generate-versions.js",
"predev": "node ../../scripts/sync-templates.js && yarn generate:versions",
- "dev": "next dev",
+ "dev": "node ../../scripts/sync-templates.js --watch & next dev",
"prebuild": "node ../../scripts/sync-templates.js && yarn generate:versions",
"build": "next build",
"start": "next start",
diff --git a/apps/sandbox/src/app/(fullscreen)/BlockDocContext.tsx b/apps/sandbox/src/app/(fullscreen)/BlockDocContext.tsx
new file mode 100644
index 0000000000..800bc63e84
--- /dev/null
+++ b/apps/sandbox/src/app/(fullscreen)/BlockDocContext.tsx
@@ -0,0 +1,80 @@
+'use client';
+
+import {XDSText} from '@xds/core/Text';
+
+export interface BlockDocMeta {
+ aspectRatio: number;
+ scale: number;
+}
+
+export function BlockPreview({
+ meta,
+ children,
+}: {
+ meta: BlockDocMeta;
+ children: React.ReactNode;
+}) {
+ const ar = meta.aspectRatio;
+ const scale = meta.scale;
+
+ return (
+ <div
+ style={{
+ flex: 1,
+ overflow: 'auto',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ padding: 24,
+ backgroundColor: 'var(--color-background-wash)',
+ }}>
+ <div style={{width: '100%', maxWidth: 600}}>
+ <div
+ style={{
+ width: '100%',
+ aspectRatio: String(ar),
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ border: '1px solid var(--color-border)',
+ borderRadius: 12,
+ backgroundColor: 'var(--color-background-card)',
+ padding: 24,
+ overflow: 'hidden',
+ }}>
+ <div
+ style={{
+ transform: scale !== 1 ? `scale(${scale})` : undefined,
+ transformOrigin: 'center center',
+ }}>
+ {children}
+ </div>
+ </div>
+ <div
+ style={{
+ marginTop: 8,
+ display: 'flex',
+ flexDirection: 'column',
+ gap: 2,
+ textAlign: 'center',
+ }}>
+ <XDSText type="supporting" color="secondary">
+ aspect-ratio:{' '}
+ {ar === 1
+ ? '1'
+ : ar === 4 / 3
+ ? '4/3'
+ : ar === 16 / 9
+ ? '16/9'
+ : String(Math.round(ar * 1000) / 1000)}
+ {' · '}scale: {scale}
+ </XDSText>
+ <XDSText type="supporting" color="secondary" size="xsm">
+ Tweak aspectRatio and scale in the .doc.mjs file so the component
+ fits nicely in this box.
+ </XDSText>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/sandbox/src/app/(fullscreen)/PreviewShell.tsx b/apps/sandbox/src/app/(fullscreen)/PreviewShell.tsx
index 1e43adf6f0..84f7c7c972 100644
--- a/apps/sandbox/src/app/(fullscreen)/PreviewShell.tsx
+++ b/apps/sandbox/src/app/(fullscreen)/PreviewShell.tsx
@@ -222,6 +222,7 @@ function MoonIcon(props: React.SVGProps<SVGSVGElement>) {
</svg>
);
}
+
function SidebarIcon(props: React.SVGProps<SVGSVGElement>) {
return (
<svg
@@ -633,6 +634,12 @@ export function PreviewShell({children}: {children: React.ReactNode}) {
const navTree = useMemo(() => buildNavTree(pathname), [pathname]);
+ const blockEntry = useMemo(
+ () => blocksByHref.get(pathname.replace(/\/$/, '')) ?? null,
+ [pathname],
+ );
+ const isBlock = blockEntry != null;
+
useEffect(() => {
const saved = localStorage.getItem('sandbox-toolbar-hidden');
if (saved === 'true') setToolbarHidden(true);
@@ -653,11 +660,6 @@ export function PreviewShell({children}: {children: React.ReactNode}) {
return () => window.removeEventListener('keydown', handleKeyDown);
}, []);
- const blockEntry = useMemo(
- () => blocksByHref.get(pathname.replace(/\/$/, '')) ?? null,
- [pathname],
- );
-
// Find current page name from the registry
const currentPage = useMemo(() => {
for (const cat of categories) {
@@ -815,7 +817,7 @@ export function PreviewShell({children}: {children: React.ReactNode}) {
/>
</XDSSegmentedControl>
- {view === 'preview' && blockEntry == null && (
+ {view === 'preview' && !isBlock && (
<XDSSegmentedControl
value={viewport}
onChange={v => setViewport(v as ViewportSize)}
@@ -906,59 +908,8 @@ export function PreviewShell({children}: {children: React.ReactNode}) {
{/* Content */}
{view === 'preview' ? (
- blockEntry != null ? (
- <div
- style={{
- flex: 1,
- overflow: 'auto',
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
- padding: 24,
- backgroundColor: 'var(--color-background-wash)',
- }}>
- <div style={{width: '100%', maxWidth: 600}}>
- <div
- style={{
- width: '100%',
- aspectRatio: String(blockEntry.aspectRatio),
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
- border: '1px solid var(--color-border)',
- borderRadius: 12,
- backgroundColor: 'var(--color-background-card)',
- padding: 24,
- }}>
- {children}
- </div>
- <div
- style={{
- marginTop: 8,
- display: 'flex',
- flexDirection: 'column',
- gap: 2,
- textAlign: 'center',
- }}>
- <XDSText type="supporting" color="secondary">
- aspect-ratio:{' '}
- {blockEntry.aspectRatio === 1
- ? '1'
- : blockEntry.aspectRatio === 4 / 3
- ? '4/3'
- : blockEntry.aspectRatio === 16 / 9
- ? '16/9'
- : String(
- Math.round(blockEntry.aspectRatio * 1000) / 1000,
- )}
- </XDSText>
- <XDSText type="supporting" color="secondary" size="xsm">
- Tweak aspectRatio in the .doc.mjs file so the component fits
- nicely in this box.
- </XDSText>
- </div>
- </div>
- </div>
+ isBlock ? (
+ children
) : viewport !== 'desktop' ? (
<div
style={{
diff --git a/apps/sandbox/src/app/(sandbox)/[category]/page.tsx b/apps/sandbox/src/app/(sandbox)/[category]/page.tsx
index f887061b90..34344195bf 100644
--- a/apps/sandbox/src/app/(sandbox)/[category]/page.tsx
+++ b/apps/sandbox/src/app/(sandbox)/[category]/page.tsx
@@ -3,7 +3,9 @@ import {CategoryContent} from './CategoryContent';
// Required for static export — pre-generate all category pages
export function generateStaticParams() {
- return categories.map(c => ({category: c.slug}));
+ return categories
+ .filter(c => c.slug !== 'templates')
+ .map(c => ({category: c.slug}));
}
export default async function CategoryPage({
diff --git a/apps/sandbox/src/app/(sandbox)/templates/page.tsx b/apps/sandbox/src/app/(sandbox)/templates/page.tsx
index 3006eefb01..5c8c2d3f7a 100644
--- a/apps/sandbox/src/app/(sandbox)/templates/page.tsx
+++ b/apps/sandbox/src/app/(sandbox)/templates/page.tsx
@@ -1,6 +1,6 @@
'use client';
-import {useState, useCallback, useMemo} from 'react';
+import {useState, useCallback, useMemo, Suspense} from 'react';
import Link from 'next/link';
import {useSearchParams, useRouter} from 'next/navigation';
import {XDSHeading} from '@xds/core/Text';
@@ -232,6 +232,14 @@ const columns: XDSTableColumn<TemplateRow>[] = [
];
export default function TemplatesPage() {
+ return (
+ <Suspense>
+ <TemplatesPageInner />
+ </Suspense>
+ );
+}
+
+function TemplatesPageInner() {
const {sort, onSortChange, filters, onFilterChange} = useTableSearchParams();
const {config, applyFilters} = usePowerSearchConfig(fieldDefs);
diff --git a/packages/cli/templates/blocks/components/Kbd/KbdInLabel.doc.mjs b/packages/cli/templates/blocks/components/Kbd/KbdInLabel.doc.mjs
index 0df7794ce8..c9e1daaf55 100644
--- a/packages/cli/templates/blocks/components/Kbd/KbdInLabel.doc.mjs
+++ b/packages/cli/templates/blocks/components/Kbd/KbdInLabel.doc.mjs
@@ -5,5 +5,6 @@ export const doc = {
description: 'Keyboard shortcut used inline within a text label.',
isReady: true,
aspectRatio: 1,
+
componentsUsed: ['Kbd'],
};
diff --git a/packages/core/src/docs-types.ts b/packages/core/src/docs-types.ts
index 24e2fe53b9..85fc10ac53 100644
--- a/packages/core/src/docs-types.ts
+++ b/packages/core/src/docs-types.ts
@@ -450,6 +450,8 @@ export interface BlockTemplateDoc extends BaseTemplateDoc {
type: 'block';
/** Width-to-height ratio for preview containers (e.g. 16/9, 1, 3/4). */
aspectRatio: number;
+ /** Scale factor for the block preview (default 1). */
+ scale?: number;
/** Component names this block uses, for cross-referencing. */
componentsUsed: string[];
}
diff --git a/scripts/sync-templates.js b/scripts/sync-templates.js
index 2dc868815b..d9300c3ed5 100644
--- a/scripts/sync-templates.js
+++ b/scripts/sync-templates.js
@@ -99,6 +99,7 @@ async function discoverBlocks() {
isReady: doc.isReady ?? false,
component: componentFolder,
aspectRatio: doc.aspectRatio ?? 4 / 3,
+ scale: doc.scale ?? 1,
sourceDir: path.dirname(tsxPath),
sourceFile: basename + '.tsx',
relPath: path.relative(BLOCKS_DIR, path.dirname(tsxPath)),
@@ -188,15 +189,37 @@ export {default} from '${depth}/${template.dirName}/page';
}
function generateBlockRouteWrapper(block) {
- const relFromRoute = path.relative(
+ const componentRel = path.relative(
path.join(ROUTES_DIR, block.dirName),
path.join(block.sourceDir, path.basename(block.sourceFile, '.tsx')),
);
- return `/**
+ const docBasename = path.basename(block.sourceFile, '.tsx') + '.doc.mjs';
+ const docRel = path.relative(
+ path.join(ROUTES_DIR, block.dirName),
+ path.join(block.sourceDir, docBasename),
+ );
+ const contextRel = path.relative(
+ path.join(ROUTES_DIR, block.dirName),
+ path.join(SANDBOX_DIR, 'src', 'app', '(fullscreen)', 'BlockDocContext'),
+ );
+ return `'use client';
+/**
* AUTO-GENERATED by scripts/sync-templates.js — do not edit.
* Block: ${block.name}
*/
-export {default} from '${relFromRoute}';
+import Component from '${componentRel}';
+import {doc} from '${docRel}';
+import {BlockPreview} from '${contextRel}';
+
+const d = doc as {aspectRatio?: number; scale?: number};
+
+export default function Page() {
+ return (
+ <BlockPreview meta={{aspectRatio: d.aspectRatio ?? 4 / 3, scale: d.scale ?? 1}}>
+ <Component />
+ </BlockPreview>
+ );
+}
`;
}
@@ -215,7 +238,7 @@ async function main() {
console.log(` wrote ${path.relative(ROOT, registryPath)}`);
const blockRegistryPath = path.join(GENERATED_DIR, 'blockRegistry.ts');
- fs.writeFileSync(blockRegistryPath, generateRegistry(blocks, 'blocks', 'BlockEntry', ['component', 'aspectRatio']));
+ fs.writeFileSync(blockRegistryPath, generateRegistry(blocks, 'blocks', 'BlockEntry', ['component', 'aspectRatio', 'scale']));
console.log(` wrote ${path.relative(ROOT, blockRegistryPath)}`);
const sourceRegistryPath = path.join(GENERATED_DIR, 'sourceRegistry.ts');
@@ -241,7 +264,27 @@ async function main() {
console.log('Done.');
}
-main().catch(err => {
- console.error(err);
- process.exit(1);
-});
+main()
+ .then(() => {
+ if (process.argv.includes('--watch')) {
+ const chokidar = require('chokidar');
+ const watchPaths = [
+ PAGES_DIR + '/**/template.doc.mjs',
+ BLOCKS_DIR + '/**/*.doc.mjs',
+ ];
+ let debounce = null;
+ const rerun = () => {
+ if (debounce) clearTimeout(debounce);
+ debounce = setTimeout(() => {
+ console.log('\n .doc.mjs changed — re-syncing...');
+ main().catch(console.error);
+ }, 300);
+ };
+ chokidar.watch(watchPaths, {ignoreInitial: true}).on('all', rerun);
+ console.log(' Watching .doc.mjs files for changes...');
+ }
+ })
+ .catch(err => {
+ console.error(err);
+ process.exit(1);
+ });