Skip to content

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

TypeScript

feat(templates): auto-discovery system with template.doc.mjs (#1101)

Joey421524dba271
diff --git a/apps/sandbox/.gitignore b/apps/sandbox/.gitignore
index 56a9886c54..d70417698e 100644
--- a/apps/sandbox/.gitignore
+++ b/apps/sandbox/.gitignore
@@ -5,3 +5,7 @@ xds.config.mjs
out
.next
next-env.d.ts
+
+# Auto-generated by scripts/sync-templates.js
+src/generated/
+src/app/(fullscreen)/templates/
diff --git a/apps/sandbox/package.json b/apps/sandbox/package.json
index 14d88afa2c..deba042677 100644
--- a/apps/sandbox/package.json
+++ b/apps/sandbox/package.json
@@ -3,7 +3,9 @@
"version": "0.0.1",
"private": true,
"scripts": {
+ "predev": "node ../../scripts/sync-templates.js",
"dev": "next dev",
+ "prebuild": "node ../../scripts/sync-templates.js",
"build": "next build",
"start": "next start",
"postinstall": "xds agent-docs"
diff --git a/apps/sandbox/postcss.config.js b/apps/sandbox/postcss.config.js
index a5f4dcd783..af668d9eb3 100644
--- a/apps/sandbox/postcss.config.js
+++ b/apps/sandbox/postcss.config.js
@@ -7,10 +7,12 @@ const rootDir = path.resolve(__dirname, '../..');
module.exports = {
plugins: {
'@stylexjs/postcss-plugin': {
- // Only compile StyleX in sandbox page files.
- // @xds/core and theme packages use pre-built dist CSS
- // (imported in layout.tsx via @layer xds-base / xds-theme).
- include: ['src/**/*.{js,jsx,ts,tsx}'],
+ include: [
+ 'src/**/*.{js,jsx,ts,tsx}',
+ path.join(rootDir, 'packages/core/src/**/*.{ts,tsx}'),
+ path.join(rootDir, 'packages/themes/default/src/**/*.{ts,tsx}'),
+ path.join(rootDir, 'packages/themes/neutral/src/**/*.{ts,tsx}'),
+ ],
babelConfig: {
babelrc: false,
parserOpts: {
@@ -18,13 +20,13 @@ module.exports = {
},
presets: [
['@babel/preset-react', {runtime: 'automatic'}],
+ // Must come after preset-react (runs first due to reverse order)
+ // to strip TypeScript type assertions before StyleX evaluates them.
'@babel/preset-typescript',
],
plugins: babelConfig.plugins,
},
- // Don't use CSS layers for sandbox page styles — they should be
- // unlayered (highest priority), same as consumer styles would be.
- useCSSLayers: false,
+ useCSSLayers: true,
},
},
};
diff --git a/apps/sandbox/src/app/sandboxPages.ts b/apps/sandbox/src/app/sandboxPages.ts
index 1b4c98515d..1a60f2b043 100644
--- a/apps/sandbox/src/app/sandboxPages.ts
+++ b/apps/sandbox/src/app/sandboxPages.ts
@@ -2,16 +2,26 @@
* @file sandboxPages.ts
* @position Central registry of all sandbox pages, grouped by category.
*
- * To add a new page:
- * 1. Create the page under the appropriate route group:
- * - `src/app/(sandbox)/pages/<name>/page.tsx` for standard layout
- * - `src/app/(fullscreen)/pages/<name>/page.tsx` for fullscreen
- * 2. Add an entry to the appropriate category below
+ * The "Templates" category is auto-populated from packages/cli/templates/
+ * via `node scripts/sync-templates.js`. Each template has a template.doc.mjs
+ * that provides metadata. The sync script generates a registry file at
+ * src/generated/templateRegistry.ts.
+ *
+ * To add a new template:
+ * 1. Create packages/cli/templates/<name>/page.tsx + template.doc.mjs
+ * 2. Run `node scripts/sync-templates.js`
+ * 3. It appears in the sandbox and CLI automatically
+ *
+ * To add a non-template sandbox page:
+ * 1. Create the page under the appropriate route group
+ * 2. Add an entry to the appropriate category below
*
* Note: hrefs use trailing slashes because the sandbox is a static export
* with `trailingSlash: true` in next.config.mjs.
*/
+import {templates as autoDiscoveredTemplates} from '../generated/templateRegistry';
+
export interface SandboxPage {
/** Display name shown on the card */
name: string;
@@ -144,6 +154,12 @@ export const categories: SandboxCategory[] = [
description:
'Block-based page builder with sidebar config and live preview',
},
+ // Auto-discovered templates from packages/cli/templates/
+ ...autoDiscoveredTemplates.map(t => ({
+ name: t.isReady ? t.name : t.name + ' (WIP)',
+ href: t.href,
+ description: t.description,
+ })),
],
},
{
diff --git a/packages/cli/src/commands/template.mjs b/packages/cli/src/commands/template.mjs
index b179c86297..e91134704f 100644
--- a/packages/cli/src/commands/template.mjs
+++ b/packages/cli/src/commands/template.mjs
@@ -2,19 +2,46 @@
* @file template command — Inject page templates
*
* Copies template files from packages/cli/templates/{name}/ to a target path.
+ * Template metadata comes from template.doc.mjs files (TemplateDoc type).
+ * Templates without a doc file fall back to directory name only.
*/
import * as fs from 'node:fs';
import * as path from 'node:path';
import {CLI_ROOT} from '../utils/paths.mjs';
-/**
- * List available templates by scanning the templates directory.
- */
-export function listTemplates() {
+async function loadTemplateDoc(templateDir) {
+ const docPath = path.join(templateDir, 'template.doc.mjs');
+ if (!fs.existsSync(docPath)) return null;
+ const docModule = await import(`file://${docPath}`);
+ return docModule.doc;
+}
+
+export async function discoverTemplates() {
const templatesDir = path.join(CLI_ROOT, 'templates');
if (!fs.existsSync(templatesDir)) return [];
+ const dirs = fs
+ .readdirSync(templatesDir, {withFileTypes: true})
+ .filter(e => e.isDirectory())
+ .sort((a, b) => a.name.localeCompare(b.name));
+
+ const templates = [];
+ for (const dir of dirs) {
+ const doc = await loadTemplateDoc(path.join(templatesDir, dir.name));
+ templates.push({
+ dirName: dir.name,
+ name: doc?.name || dir.name,
+ description: doc?.description || '',
+ isReady: doc?.isReady ?? true,
+ });
+ }
+ return templates;
+}
+
+export function listTemplates() {
+ const templatesDir = path.join(CLI_ROOT, 'templates');
+ if (!fs.existsSync(templatesDir)) return [];
return fs
.readdirSync(templatesDir, {withFileTypes: true})
.filter(e => e.isDirectory())
@@ -22,34 +49,30 @@ export function listTemplates() {
.sort();
}
-const TEMPLATE_DESCRIPTIONS = {
- blank: 'Minimal scaffold',
- table: 'Data table with actions',
- login: 'Auth form with inputs',
-};
-
export function registerTemplate(program) {
program
.command('template [name] [path]')
.description('Inject a page template')
.option('--list', 'List available templates')
- .action((name, targetPath, options) => {
- const templates = listTemplates();
+ .action(async (name, targetPath, options) => {
+ const templates = await discoverTemplates();
+ const templateNames = templates.map(t => t.dirName);
if (options.list || !name) {
console.log('\nAvailable templates:\n');
for (const t of templates) {
- const desc = TEMPLATE_DESCRIPTIONS[t] || '';
- console.log(` ${t} — ${desc}`);
+ const status = t.isReady ? '' : ' (WIP)';
+ const desc = t.description ? ` — ${t.description}` : '';
+ console.log(` ${t.dirName}${status}${desc}`);
}
- console.log(`\nUsage: xds template <name> [target-path]\n`);
+ console.log('\nUsage: xds template <name> [target-path]\n');
console.log('Example: xds template blank ./src/pages/home\n');
return;
}
- if (!templates.includes(name)) {
+ if (!templateNames.includes(name)) {
console.error(`Error: Unknown template "${name}".`);
- console.error(`Available: ${templates.join(', ')}`);
+ console.error(`Available: ${templateNames.join(', ')}`);
process.exit(1);
}
@@ -65,10 +88,10 @@ export function registerTemplate(program) {
let copied = 0;
for (const file of files) {
+ if (file === 'template.doc.mjs') continue;
const srcPath = path.join(templateDir, file);
const stat = fs.statSync(srcPath);
if (!stat.isFile()) continue;
-
fs.copyFileSync(srcPath, path.join(outputDir, file));
copied++;
}
diff --git a/packages/cli/templates/demo-dashboard/page.tsx b/packages/cli/templates/demo-dashboard/page.tsx
new file mode 100644
index 0000000000..966f81804b
--- /dev/null
+++ b/packages/cli/templates/demo-dashboard/page.tsx
@@ -0,0 +1,209 @@
+'use client';
+
+import {useState} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {XDSAppShell} from '@xds/core/AppShell';
+import {XDSSideNav, XDSSideNavItem, XDSSideNavSection} from '@xds/core/SideNav';
+import {XDSText, XDSHeading} from '@xds/core/Text';
+import {XDSCard} from '@xds/core/Card';
+import {XDSBadge} from '@xds/core/Badge';
+import {XDSDivider} from '@xds/core/Divider';
+import {colorVars, spacingVars} from '@xds/core/theme/tokens.stylex';
+
+const kpis = [
+ {label: 'Total Users', value: '12,847', change: '+14%', trend: 'up' as const},
+ {label: 'Active Now', value: '1,024', change: '+3%', trend: 'up' as const},
+ {label: 'Revenue', value: '$48.2k', change: '-2%', trend: 'down' as const},
+ {label: 'Conversion', value: '3.2%', change: '+0.4%', trend: 'up' as const},
+];
+
+const recentItems = [
+ {id: 1, name: 'Acme Corp', status: 'Active', amount: '$12,400'},
+ {id: 2, name: 'Globex Inc', status: 'Pending', amount: '$8,200'},
+ {id: 3, name: 'Initech', status: 'Active', amount: '$6,800'},
+ {id: 4, name: 'Umbrella Ltd', status: 'Churned', amount: '$3,100'},
+ {id: 5, name: 'Stark Industries', status: 'Active', amount: '$22,900'},
+];
+
+const styles = stylex.create({
+ content: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: spacingVars['--spacing-6'],
+ maxWidth: 1200,
+ },
+ kpiGrid: {
+ display: 'grid',
+ gridTemplateColumns: 'repeat(4, 1fr)',
+ gap: spacingVars['--spacing-4'],
+ },
+ kpiCard: {
+ padding: spacingVars['--spacing-5'],
+ display: 'flex',
+ flexDirection: 'column',
+ gap: spacingVars['--spacing-2'],
+ },
+ kpiValue: {
+ fontSize: 28,
+ fontWeight: 700,
+ color: colorVars['--color-text-primary'],
+ },
+ table: {
+ width: '100%',
+ borderCollapse: 'collapse',
+ },
+ th: {
+ textAlign: 'start' as const,
+ padding: `${spacingVars['--spacing-3']} ${spacingVars['--spacing-4']}`,
+ borderBottom: `1px solid ${colorVars['--color-border']}`,
+ color: colorVars['--color-text-secondary'],
+ fontSize: 13,
+ fontWeight: 500,
+ },
+ td: {
+ padding: `${spacingVars['--spacing-3']} ${spacingVars['--spacing-4']}`,
+ borderBottom: `1px solid ${colorVars['--color-border']}`,
+ },
+});
+
+const HomeIcon = (props: React.SVGProps<SVGSVGElement>) => (
+ <svg
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth={2}
+ width={20}
+ height={20}
+ {...props}>
+ <path d="M3 12l9-8 9 8" strokeLinecap="round" strokeLinejoin="round" />
+ <path
+ d="M5 10v10a1 1 0 001 1h3v-6h6v6h3a1 1 0 001-1V10"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ </svg>
+);
+
+const ChartIcon = (props: React.SVGProps<SVGSVGElement>) => (
+ <svg
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth={2}
+ width={20}
+ height={20}
+ {...props}>
+ <rect x="3" y="12" width="4" height="9" rx="1" />
+ <rect x="10" y="7" width="4" height="14" rx="1" />
+ <rect x="17" y="3" width="4" height="18" rx="1" />
+ </svg>
+);
+
+const UsersIcon = (props: React.SVGProps<SVGSVGElement>) => (
+ <svg
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth={2}
+ width={20}
+ height={20}
+ {...props}>
+ <circle cx="9" cy="7" r="4" />
+ <path d="M3 21v-2a4 4 0 014-4h4a4 4 0 014 4v2" />
+ <circle cx="17" cy="9" r="3" />
+ <path d="M21 21v-2a3 3 0 00-2-2.83" />
+ </svg>
+);
+
+function statusVariant(status: string) {
+ if (status === 'Active') return 'success' as const;
+ if (status === 'Pending') return 'warning' as const;
+ return 'error' as const;
+}
+
+export default function DemoDashboard() {
+ const [activePage, setActivePage] = useState('dashboard');
+
+ return (
+ <XDSAppShell
+ sideNav={
+ <XDSSideNav>
+ <XDSSideNavSection title="Main" isHeaderHidden>
+ <XDSSideNavItem
+ label="Home"
+ icon={HomeIcon}
+ isSelected={activePage === 'home'}
+ onClick={() => setActivePage('home')}
+ />
+ <XDSSideNavItem
+ label="Dashboard"
+ icon={ChartIcon}
+ isSelected={activePage === 'dashboard'}
+ onClick={() => setActivePage('dashboard')}
+ />
+ <XDSSideNavItem
+ label="Customers"
+ icon={UsersIcon}
+ isSelected={activePage === 'customers'}
+ onClick={() => setActivePage('customers')}
+ />
+ </XDSSideNavSection>
+ </XDSSideNav>
+ }
+ contentPadding={6}>
+ <div {...stylex.props(styles.content)}>
+ <XDSHeading level={1}>Dashboard</XDSHeading>
+
+ <div {...stylex.props(styles.kpiGrid)}>
+ {kpis.map(kpi => (
+ <XDSCard key={kpi.label}>
+ <div {...stylex.props(styles.kpiCard)}>
+ <XDSText type="body" color="secondary" size="sm">
+ {kpi.label}
+ </XDSText>
+ <div {...stylex.props(styles.kpiValue)}>{kpi.value}</div>
+ <XDSBadge
+ variant={kpi.trend === 'up' ? 'success' : 'error'}
+ label={kpi.change}
+ />
+ </div>
+ </XDSCard>
+ ))}
+ </div>
+
+ <XDSDivider />
+
+ <div>
+ <XDSHeading level={2}>Recent Customers</XDSHeading>
+ <table {...stylex.props(styles.table)}>
+ <thead>
+ <tr>
+ <th {...stylex.props(styles.th)}>Name</th>
+ <th {...stylex.props(styles.th)}>Status</th>
+ <th {...stylex.props(styles.th)}>Amount</th>
+ </tr>
+ </thead>
+ <tbody>
+ {recentItems.map(item => (
+ <tr key={item.id}>
+ <td {...stylex.props(styles.td)}>
+ <XDSText type="body">{item.name}</XDSText>
+ </td>
+ <td {...stylex.props(styles.td)}>
+ <XDSBadge
+ variant={statusVariant(item.status)}
+ label={item.status}
+ />
+ </td>
+ <td {...stylex.props(styles.td)}>
+ <XDSText type="body">{item.amount}</XDSText>
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ </div>
+ </XDSAppShell>
+ );
+}
diff --git a/packages/cli/templates/demo-dashboard/template.doc.mjs b/packages/cli/templates/demo-dashboard/template.doc.mjs
new file mode 100644
index 0000000000..98ac22431b
--- /dev/null
+++ b/packages/cli/templates/demo-dashboard/template.doc.mjs
@@ -0,0 +1,6 @@
+/** @type {import('@xds/core').TemplateDoc} */
+export const doc = {
+ name: 'Dashboard',
+ description: 'Analytics dashboard with KPI cards and a data table.',
+ isReady: true,
+};
diff --git a/packages/core/src/docs-types.ts b/packages/core/src/docs-types.ts
index 4dc85adafd..06a2e5b9d1 100644
--- a/packages/core/src/docs-types.ts
+++ b/packages/core/src/docs-types.ts
@@ -390,3 +390,27 @@ export interface ReferenceTranslationDoc {
)[];
}[];
}
+
+/**
+ * Documentation for a page template.
+ *
+ * Every template directory under `packages/cli/templates/` has a
+ * `template.doc.mjs` that exports a single `doc` constant:
+ *
+ * /** @type {import('@xds/core').TemplateDoc} *\/
+ * export const doc = { ... };
+ *
+ * The CLI and sandbox import these for discovery and display.
+ */
+export interface TemplateDoc {
+ /** Display name shown in the sandbox gallery and CLI.
+ * e.g. "Dashboard", "Login (Card)", "Settings (Sidebar)" */
+ name: string;
+
+ /** One-sentence description of what the template provides. */
+ description: string;
+
+ /** Whether this template is ready for use. Templates with
+ * isReady: false show as "(WIP)" in the gallery and CLI. */
+ isReady: boolean;
+}
diff --git a/scripts/sync-templates.js b/scripts/sync-templates.js
new file mode 100644
index 0000000000..f3726543a3
--- /dev/null
+++ b/scripts/sync-templates.js
@@ -0,0 +1,124 @@
+#!/usr/bin/env node
+
+/**
+ * @file sync-templates.js
+ *
+ * Reads packages/cli/templates/{name}/template.doc.mjs and generates:
+ * 1. A template registry (apps/sandbox/src/generated/templateRegistry.ts)
+ * 2. Thin route wrappers under (fullscreen)/templates/{slug}/page.tsx
+ *
+ * Run: node scripts/sync-templates.js
+ */
+
+const fs = require('fs');
+const path = require('path');
+
+const ROOT = path.resolve(__dirname, '..');
+const TEMPLATES_DIR = path.join(ROOT, 'packages', 'cli', 'templates');
+const SANDBOX_DIR = path.join(ROOT, 'apps', 'sandbox');
+const GENERATED_DIR = path.join(SANDBOX_DIR, 'src', 'generated');
+const ROUTES_DIR = path.join(
+ SANDBOX_DIR, 'src', 'app', '(fullscreen)', 'templates'
+);
+
+async function discoverTemplates() {
+ if (!fs.existsSync(TEMPLATES_DIR)) return [];
+
+ const dirs = fs.readdirSync(TEMPLATES_DIR, {withFileTypes: true})
+ .filter(e => e.isDirectory());
+
+ const templates = [];
+
+ for (const dir of dirs) {
+ const docPath = path.join(TEMPLATES_DIR, dir.name, 'template.doc.mjs');
+ const pagePath = path.join(TEMPLATES_DIR, dir.name, 'page.tsx');
+
+ if (!fs.existsSync(docPath)) continue;
+
+ if (!fs.existsSync(pagePath)) {
+ console.warn(` skip ${dir.name}/ (has doc but missing page.tsx)`);
+ continue;
+ }
+
+ const docModule = await import(`file://${docPath}`);
+ const doc = docModule.doc;
+
+ templates.push({
+ dirName: dir.name,
+ name: doc.name,
+ description: doc.description,
+ isReady: doc.isReady ?? false,
+ });
+ }
+
+ return templates.sort((a, b) => a.name.localeCompare(b.name));
+}
+
+function generateRegistry(templates) {
+ const entries = templates.map(t => ` {
+ name: ${JSON.stringify(t.name)},
+ slug: ${JSON.stringify(t.dirName)},
+ description: ${JSON.stringify(t.description)},
+ isReady: ${JSON.stringify(t.isReady)},
+ href: '/templates/${t.dirName}/',
+ }`);
+
+ return `/**
+ * AUTO-GENERATED by scripts/sync-templates.js — do not edit.
+ */
+
+export interface TemplateEntry {
+ name: string;
+ slug: string;
+ description: string;
+ isReady: boolean;
+ href: string;
+}
+
+export const templates: TemplateEntry[] = [
+${entries.join(',\n')}
+];
+`;
+}
+
+function generateRouteWrapper(template) {
+ const depth = '../../../../../../../packages/cli/templates';
+ return `/**
+ * AUTO-GENERATED by scripts/sync-templates.js — do not edit.
+ * Template: ${template.name}
+ */
+export {default} from '${depth}/${template.dirName}/page';
+`;
+}
+
+async function main() {
+ console.log('Syncing templates...');
+
+ const templates = await discoverTemplates();
+ console.log(` found ${templates.length} template(s) with doc files`);
+
+ fs.mkdirSync(GENERATED_DIR, {recursive: true});
+
+ if (fs.existsSync(ROUTES_DIR)) {
+ fs.rmSync(ROUTES_DIR, {recursive: true});
+ }
+
+ const registryPath = path.join(GENERATED_DIR, 'templateRegistry.ts');
+ fs.writeFileSync(registryPath, generateRegistry(templates));
+ console.log(` wrote ${path.relative(ROOT, registryPath)}`);
+
+ for (const t of templates) {
+ const routeDir = path.join(ROUTES_DIR, t.dirName);
+ fs.mkdirSync(routeDir, {recursive: true});
+ const wrapperPath = path.join(routeDir, 'page.tsx');
+ fs.writeFileSync(wrapperPath, generateRouteWrapper(t));
+ console.log(` wrote ${path.relative(ROOT, wrapperPath)}`);
+ }
+
+ console.log('Done.');
+}
+
+main().catch(err => {
+ console.error(err);
+ process.exit(1);
+});