Skip to content

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

TypeScript

refactor(cli): convert docs to typed .doc.mjs with --detail and --lang (#636)

Joey7f0eea191a0a
diff --git a/.claude/skills/writing-component-docs.md b/.claude/skills/writing-component-docs.md
index f481e8b675..89ba555f3b 100644
--- a/.claude/skills/writing-component-docs.md
+++ b/.claude/skills/writing-component-docs.md
@@ -117,3 +117,26 @@ npx xds --detail compact --lang dense component Button # Compact + compressed
```
`--lang` controls which prose translation is used. `--detail` controls how much detail (full, compact, brief). They compose independently.
+
+## Reference Docs (non-component)
+
+Reference docs (tokens, principles, theme) use a different type: `ReferenceDoc` from `docs-types.ts`.
+
+They live in `packages/cli/docs/` as `.doc.mjs` files with translations in `*.doc.dense.mjs` and `*.doc.zh.mjs`.
+
+Content is structured as sections with ordered content blocks:
+
+- `prose` — translatable text
+- `code` — code examples (not translated)
+- `table` — data tables (not translated)
+- `list` — rules, anti-patterns, tips (translatable)
+
+To add a new reference doc: create `packages/cli/docs/mytopic.doc.mjs` exporting a `docs` constant. It auto-discovers.
+
+```bash
+npx xds docs # list topics
+npx xds docs tokens # full output
+npx xds docs tokens spacing # single section
+npx xds --detail compact docs tokens # agent-friendly
+npx xds --lang dense docs tokens # compressed prose
+```
diff --git a/packages/cli/docs/principles.doc.dense.mjs b/packages/cli/docs/principles.doc.dense.mjs
new file mode 100644
index 0000000000..c6f63f321f
--- /dev/null
+++ b/packages/cli/docs/principles.doc.dense.mjs
@@ -0,0 +1,12 @@
+/** @type {import('../../core/src/docs-types').ReferenceTranslationDoc} */
+
+export const docsDense = {
+ description: 'design rules + anti-patterns',
+ sections: [
+ { title: 'Rules', content: [{ type: 'list', items: ['use XDS components', 'StyleX for styling', 'semantic tokens only', 'CSS vars for colors', 'controlled form inputs'] }] },
+ { title: 'xstyle prop', content: [{ type: 'prose', text: 'xstyle accepts inline obj, stylex.create, or CSS class string.' }, null, null, null, { type: 'list', items: ['1-2 props: inline', '3+ props: stylex.create', 'pseudo-classes: stylex.create required', ':hover needs @media (hover: hover)'] }] },
+ { title: 'Anti-Patterns', content: [{ type: 'list', items: ['no inline styles on raw elements', 'no hardcoded colors', 'no hardcoded spacing', 'read docs before inventing props'] }] },
+ { title: 'StyleX', content: [null] },
+ { title: 'Token Quick Ref', content: [{ type: 'prose', text: 'see xds docs tokens' }, null] },
+ ],
+};
diff --git a/packages/cli/docs/principles.doc.mjs b/packages/cli/docs/principles.doc.mjs
new file mode 100644
index 0000000000..bb7911be72
--- /dev/null
+++ b/packages/cli/docs/principles.doc.mjs
@@ -0,0 +1,128 @@
+/** @type {import('../../core/src/docs-types').ReferenceDoc} */
+
+export const docs = {
+ name: 'principles',
+ title: 'XDS Principles',
+ description: 'Design principles, rules, and anti-patterns for XDS.',
+
+ sections: [
+ {
+ title: 'Rules',
+ content: [
+ {
+ type: 'list',
+ style: 'ordered',
+ items: [
+ 'Use XDS components for everything they cover',
+ 'StyleX for styling (not inline styles)',
+ 'Semantic tokens, not hardcoded values',
+ 'CSS variables for colors, not hex',
+ 'Form inputs are controlled (value + onChange)',
+ ],
+ },
+ ],
+ },
+ {
+ title: 'Style Overrides: xstyle prop',
+ content: [
+ {
+ type: 'prose',
+ text: 'Most XDS components accept an xstyle prop for customizing styles. It supports three formats.',
+ },
+ {
+ type: 'code',
+ lang: 'tsx',
+ label: 'Inline styles',
+ code: `<XDSTextInput label="Name" xstyle={{ maxWidth: 300 }} />
+<XDSCard xstyle={{ height: 200, padding: 16 }} />`,
+ },
+ {
+ type: 'code',
+ lang: 'tsx',
+ label: 'StyleX styles',
+ code: `import * as stylex from '@stylexjs/stylex';
+const overrides = stylex.create({
+ hoverCard: {
+ boxShadow: {
+ default: 'none',
+ ':hover': {'@media (hover: hover)': '0 4px 12px rgba(0,0,0,0.15)'},
+ },
+ },
+});
+<XDSCard xstyle={overrides.hoverCard} />;`,
+ },
+ {
+ type: 'code',
+ lang: 'tsx',
+ label: 'CSS class name',
+ code: `<XDSCard xstyle="my-custom-card" />
+<XDSCard xstyle={styles.customCard} /> // CSS Module`,
+ },
+ {
+ type: 'list',
+ style: 'unordered',
+ items: [
+ '1-2 simple properties: use inline',
+ '3+ properties, reusable, or named: use stylex.create',
+ 'Pseudo-classes (:hover, :focus-visible): use stylex.create (required)',
+ 'All :hover MUST use @media (hover: hover) guards',
+ ],
+ },
+ ],
+ },
+ {
+ title: 'Anti-Patterns',
+ content: [
+ {
+ type: 'list',
+ style: 'dont',
+ items: [
+ 'Inline styles on raw elements. Use xstyle on XDS components',
+ 'Hardcoded colors (#fff). Use var(--color-*)',
+ 'Hardcoded spacing (16px). Use spacing tokens or var(--spacing-*)',
+ 'Inventing props. Read component docs first',
+ ],
+ },
+ ],
+ },
+ {
+ title: 'StyleX Usage',
+ content: [
+ {
+ type: 'code',
+ lang: 'tsx',
+ label: 'Basic StyleX pattern',
+ code: `import * as stylex from '@stylexjs/stylex';
+
+const styles = stylex.create({
+ container: {
+ padding: 'var(--spacing-4)',
+ backgroundColor: 'var(--color-surface)',
+ borderRadius: 'var(--radius-element)',
+ },
+});
+
+<div {...stylex.props(styles.container)}>`,
+ },
+ ],
+ },
+ {
+ title: 'Quick Token Reference',
+ content: [
+ {
+ type: 'prose',
+ text: 'See `xds docs tokens` for the full list. Key values:',
+ },
+ {
+ type: 'table',
+ headers: ['Category', 'Values'],
+ rows: [
+ ['Spacing', '0=0px | 0.5=2px | 1=4px | 2=8px | 3=12px | 4=16px | 5=20px | 6=24px | 7=32px'],
+ ['Radius', 'rounded=pill | container=12px | element=8px | content=4px'],
+ ['Colors', 'accent, surface, wash, positive, negative, warning'],
+ ],
+ },
+ ],
+ },
+ ],
+};
diff --git a/packages/cli/docs/principles.doc.zh.mjs b/packages/cli/docs/principles.doc.zh.mjs
new file mode 100644
index 0000000000..d335ecf060
--- /dev/null
+++ b/packages/cli/docs/principles.doc.zh.mjs
@@ -0,0 +1,12 @@
+/** @type {import('../../core/src/docs-types').ReferenceTranslationDoc} */
+
+export const docsZh = {
+ description: 'XDS 设计原则、规则和反模式。',
+ sections: [
+ { title: '规则', content: [{ type: 'list', items: ['所有支持的场景都使用 XDS 组件', '使用 StyleX 进行样式设置(不使用内联样式)', '使用语义化令牌,不使用硬编码值', '使用 CSS 变量设置颜色,不使用十六进制值', '表单输入为受控组件(value + onChange)'] }] },
+ { title: '样式覆盖:xstyle 属性', content: [{ type: 'prose', text: '大多数 XDS 组件接受 xstyle 属性来自定义样式。支持三种格式。' }, null, null, null, { type: 'list', items: ['1-2 个简单属性:使用内联', '3+ 个属性、可复用或命名的:使用 stylex.create', '伪类(:hover、:focus-visible):必须使用 stylex.create', '所有 :hover 必须使用 @media (hover: hover) 守卫'] }] },
+ { title: '反模式', content: [{ type: 'list', items: ['不要在原始元素上使用内联样式。使用 XDS 组件的 xstyle', '不要硬编码颜色(#fff)。使用 var(--color-*)', '不要硬编码间距(16px)。使用间距令牌或 var(--spacing-*)', '不要自创属性。先阅读组件文档'] }] },
+ { title: 'StyleX 用法', content: [null] },
+ { title: '快速令牌参考', content: [{ type: 'prose', text: '完整列表请查看 `xds docs tokens`。主要值:' }, null] },
+ ],
+};
diff --git a/packages/cli/docs/theme.doc.dense.mjs b/packages/cli/docs/theme.doc.dense.mjs
new file mode 100644
index 0000000000..f140df2c80
--- /dev/null
+++ b/packages/cli/docs/theme.doc.dense.mjs
@@ -0,0 +1,16 @@
+/** @type {import('../../core/src/docs-types').ReferenceTranslationDoc} */
+
+export const docsDense = {
+ description: 'XDSTheme provider, custom themes, light/dark, component overrides',
+ sections: [
+ { title: 'Quick Start', content: [null] },
+ { title: 'Themes', content: [null, { type: 'prose', text: 'xds theme --list to see project themes' }] },
+ { title: 'Props', content: [null] },
+ { title: 'Custom Theme', content: [{ type: 'prose', text: 'CLI wizard or manual. only override token groups that differ.' }, null, null, { type: 'prose', text: 'token groups: colors/spacing/size/radius/elevation/transition/typography/textSize/lineHeight/fontWeight' }, { type: 'list', items: ['no variable refs in createTheme (static analysis)', 'no spread in createTheme'] }] },
+ { title: 'Light/Dark', content: [{ type: 'prose', text: 'light-dark() in token values. mode=system follows OS.' }, null, null] },
+ { title: 'Nesting', content: [{ type: 'prose', text: 'wrap sections in separate <XDSTheme> providers' }, null] },
+ { title: 'Page Background', content: [{ type: 'prose', text: 'XDSTheme is display:contents. apply bg to wrapper.' }, null] },
+ { title: 'Component Overrides', content: [{ type: 'prose', text: 'themes override component styles via components field + module augmentation' }, null, null, { type: 'prose', text: 'xds --detail compact component <Name> for themeable slots' }] },
+ { title: 'useXDSTheme', content: [null, { type: 'prose', text: 'read-only. manage state at app level.' }] },
+ ],
+};
diff --git a/packages/cli/docs/theme.doc.mjs b/packages/cli/docs/theme.doc.mjs
new file mode 100644
index 0000000000..5760d6d4cb
--- /dev/null
+++ b/packages/cli/docs/theme.doc.mjs
@@ -0,0 +1,270 @@
+/** @type {import('../../core/src/docs-types').ReferenceDoc} */
+
+export const docs = {
+ name: 'theme',
+ title: 'XDS Theme System',
+ description: 'XDSTheme provider, custom themes, light/dark mode, and component style overrides.',
+
+ sections: [
+ {
+ title: 'Quick Start',
+ content: [
+ {
+ type: 'code',
+ lang: 'tsx',
+ label: 'Basic theme setup',
+ code: `import {XDSTheme} from '@xds/core';
+import {defaultTheme} from '@xds/theme/default';
+
+function App() {
+ return (
+ <XDSTheme theme={defaultTheme}>
+ <YourApp />
+ </XDSTheme>
+ );
+}`,
+ },
+ ],
+ },
+ {
+ title: 'Available Themes',
+ content: [
+ {
+ type: 'table',
+ headers: ['Theme', 'Import', 'Description'],
+ rows: [
+ ['Default', "import {defaultTheme} from '@xds/theme/default'", 'Blue accent, system fonts, light/dark'],
+ ['Neutral', "import {neutralTheme} from '@xds/theme/neutral'", 'Grayscale, shadcn-inspired'],
+ ],
+ },
+ {
+ type: 'prose',
+ text: "Run `npx xds theme --list` to see themes in your project.",
+ },
+ ],
+ },
+ {
+ title: 'XDSTheme Props',
+ content: [
+ {
+ type: 'table',
+ headers: ['Prop', 'Type', 'Default', 'Description'],
+ rows: [
+ ['theme', 'Theme', '—', 'Theme object (required)'],
+ ['mode', "'system' | 'light' | 'dark'", "'system'", 'Color mode. system follows OS preference.'],
+ ['children', 'ReactNode', '—', 'App content'],
+ ],
+ },
+ ],
+ },
+ {
+ title: 'Creating a Custom Theme',
+ content: [
+ {
+ type: 'prose',
+ text: "Use the CLI wizard (recommended) or create manually. Only override token groups that differ from defaults — omitted groups use defineVars defaults from @xds/core.",
+ },
+ {
+ type: 'code',
+ lang: 'bash',
+ label: 'Scaffold with CLI',
+ code: 'npx xds theme',
+ },
+ {
+ type: 'code',
+ lang: 'tsx',
+ label: 'Manual creation',
+ code: `import * as stylex from '@stylexjs/stylex';
+import type {ThemeType as Theme} from '@xds/core/theme';
+import {colorVars, colorDefaults} from '@xds/core/theme/tokens.stylex';
+
+const colorOverrides = {
+ '--color-accent': 'light-dark(#7B61FF, #9B85FF)',
+ '--color-surface': 'light-dark(#FFFFFF, #1A1A2E)',
+ // ... all ~60 color tokens (see npx xds docs tokens)
+} as const;
+
+const colorTheme = stylex.createTheme(
+ colorVars,
+ colorOverrides as unknown as typeof colorDefaults,
+);
+
+export const myTheme: Theme = {
+ name: 'my-theme',
+ styles: {
+ colors: colorTheme,
+ // spacing, radius, etc. omitted — uses defaults
+ },
+ raw: {
+ colors: colorOverrides,
+ },
+};`,
+ },
+ {
+ type: 'prose',
+ text: "Token groups (all optional in styles): colors, spacing, size, radius, elevation, transition, typography, textSize, lineHeight, fontWeight. Omitted groups use defineVars defaults.",
+ },
+ {
+ type: 'list',
+ style: 'dont',
+ items: [
+ "Variable references in stylex.createTheme(). StyleX requires inline object literals for static analysis.",
+ "Spread expressions in createTheme(). Same static analysis constraint.",
+ ],
+ },
+ ],
+ },
+ {
+ title: 'Light/Dark Mode',
+ content: [
+ {
+ type: 'prose',
+ text: "Use light-dark() in token values for automatic mode switching. Use mode='system' (default) on XDSTheme to follow OS preference.",
+ },
+ {
+ type: 'code',
+ lang: 'tsx',
+ label: 'Automatic with light-dark()',
+ code: "'--color-accent': 'light-dark(#0064E0, #2694FE)',\n// ^light ^dark",
+ },
+ {
+ type: 'code',
+ lang: 'tsx',
+ label: 'Toggle with a button',
+ code: `const [mode, setMode] = useState<'light' | 'dark'>('light');
+
+<XDSTheme theme={myTheme} mode={mode}>
+ <XDSButton
+ label={mode === 'light' ? 'Switch to Dark' : 'Switch to Light'}
+ onClick={() => setMode(m => (m === 'light' ? 'dark' : 'light'))}
+ />
+</XDSTheme>;`,
+ },
+ ],
+ },
+ {
+ title: 'Nesting Themes',
+ content: [
+ {
+ type: 'prose',
+ text: "Wrap different sections in separate <XDSTheme> providers.",
+ },
+ {
+ type: 'code',
+ lang: 'tsx',
+ label: 'Dark sidebar with light content',
+ code: `<XDSTheme theme={lightTheme} mode="light">
+ <XDSLayout
+ header={<XDSLayoutHeader>...</XDSLayoutHeader>}
+ start={
+ <XDSTheme theme={darkTheme} mode="dark">
+ <XDSLayoutPanel>{/* Dark sidebar */}</XDSLayoutPanel>
+ </XDSTheme>
+ }
+ content={<XDSLayoutContent>{/* Light content */}</XDSLayoutContent>}
+ />
+</XDSTheme>`,
+ },
+ ],
+ },
+ {
+ title: 'Page Background',
+ content: [
+ {
+ type: 'prose',
+ text: "XDSTheme uses display: contents — it doesn't create a visual box. Apply the theme's background color to a wrapper element via StyleX.",
+ },
+ {
+ type: 'code',
+ lang: 'tsx',
+ label: 'Applying background color',
+ code: `const styles = stylex.create({
+ page: {
+ backgroundColor: 'var(--color-wash)',
+ minHeight: '100vh',
+ },
+});
+
+<XDSTheme theme={myTheme}>
+ <div {...stylex.props(styles.page)}>
+ <XDSLayout>...</XDSLayout>
+ </div>
+</XDSTheme>;`,
+ },
+ ],
+ },
+ {
+ title: 'Component Style Overrides',
+ content: [
+ {
+ type: 'prose',
+ text: "Themes can override individual component styles via the components field. Components register themeable properties via module augmentation, and your theme provides StyleX overrides.",
+ },
+ {
+ type: 'code',
+ lang: 'tsx',
+ label: 'Card with gradient border',
+ code: `const cardOverrides = stylex.create({
+ container: {
+ borderRadius: '20px',
+ background: 'linear-gradient(135deg, var(--color-accent), var(--color-positive))',
+ padding: '2px',
+ },
+ content: {
+ backgroundColor: 'var(--color-card)',
+ borderRadius: '18px',
+ },
+});
+
+export const myTheme: Theme = {
+ name: 'my-theme',
+ styles: { colors: colorTheme },
+ components: {
+ card: {
+ container: cardOverrides.container,
+ content: cardOverrides.content,
+ },
+ } as Theme['components'],
+};`,
+ },
+ {
+ type: 'table',
+ headers: ['Component', 'Key', 'Slots', 'What to customize'],
+ rows: [
+ ['Button', 'button', 'variants (by variant name)', 'Background, border, shadow per variant'],
+ ['Card', 'card', 'container, content', 'Border, radius, shadow, background'],
+ ['Heading', 'heading', 'styles (h1-h6), editorialStyles (h1-h6)', 'Font, size, weight, color per level'],
+ ['Text', 'text', 'styles (body, large, label, supporting, code)', 'Font, size, weight, color per type'],
+ ['Prose', 'prose', 'base, styles (p, ul, ol, li, blockquote, code, pre, hr, strong, em, a)', 'Prose element styling'],
+ ],
+ },
+ {
+ type: 'prose',
+ text: "Run `npx xds --detail compact component <Name>` to see a component's themeable slots.",
+ },
+ ],
+ },
+ {
+ title: 'useXDSTheme Hook',
+ content: [
+ {
+ type: 'code',
+ lang: 'tsx',
+ label: 'Access current theme',
+ code: `import {useXDSTheme} from '@xds/core';
+
+function MyComponent() {
+ const ctx = useXDSTheme();
+ // ctx.theme — the Theme object
+ // ctx.mode — 'system' | 'light' | 'dark'
+ return null;
+}`,
+ },
+ {
+ type: 'prose',
+ text: "This is read-only. To change the theme/mode, manage state at the app level and pass it to <XDSTheme>.",
+ },
+ ],
+ },
+ ],
+};
diff --git a/packages/cli/docs/theme.doc.zh.mjs b/packages/cli/docs/theme.doc.zh.mjs
new file mode 100644
index 0000000000..dd31045bbf
--- /dev/null
+++ b/packages/cli/docs/theme.doc.zh.mjs
@@ -0,0 +1,16 @@
+/** @type {import('../../core/src/docs-types').ReferenceTranslationDoc} */
+
+export const docsZh = {
+ description: 'XDSTheme 提供者、自定义主题、亮/暗模式和组件样式覆盖。',
+ sections: [
+ { title: '快速开始', content: [null] },
+ { title: '可用主题', content: [null, { type: 'prose', text: '运行 `npx xds theme --list` 查看项目中的主题。' }] },
+ { title: 'XDSTheme 属性', content: [null] },
+ { title: '创建自定义主题', content: [{ type: 'prose', text: '使用 CLI 向导(推荐)或手动创建。只覆盖与默认值不同的令牌组,省略的组会自动使用 @xds/core 的 defineVars 默认值。' }, null, null, { type: 'prose', text: '令牌组(styles 中均为可选):colors、spacing、size、radius、elevation、transition、typography、textSize、lineHeight、fontWeight。省略的组使用 defineVars 默认值。' }, { type: 'list', items: ['stylex.createTheme() 中不能使用变量引用。StyleX 需要内联对象字面量进行静态分析。', 'createTheme() 中不能使用展开表达式。同样的静态分析约束。'] }] },
+ { title: '亮/暗模式', content: [{ type: 'prose', text: "在令牌值中使用 light-dark() 实现自动模式切换。在 XDSTheme 上使用 mode='system'(默认)跟随系统偏好。" }, null, null] },
+ { title: '嵌套主题', content: [{ type: 'prose', text: '将不同部分包裹在独立的 <XDSTheme> 提供者中。' }, null] },
+ { title: '页面背景', content: [{ type: 'prose', text: 'XDSTheme 使用 display: contents,不会创建视觉容器。通过 StyleX 将主题背景色应用到包裹元素。' }, null] },
+ { title: '组件样式覆盖', content: [{ type: 'prose', text: '主题可以通过 components 字段覆盖单个组件样式。组件通过模块增强注册可主题化的属性,主题提供 StyleX 覆盖。' }, null, null, { type: 'prose', text: '运行 `npx xds --detail compact component <Name>` 查看组件的可主题化插槽。' }] },
+ { title: 'useXDSTheme 钩子', content: [null, { type: 'prose', text: '这是只读的。要更改主题/模式,在应用层管理状态并传递给 <XDSTheme>。' }] },
+ ],
+};
diff --git a/packages/cli/docs/tokens.doc.dense.mjs b/packages/cli/docs/tokens.doc.dense.mjs
new file mode 100644
index 0000000000..177bc31097
--- /dev/null
+++ b/packages/cli/docs/tokens.doc.dense.mjs
@@ -0,0 +1,14 @@
+/** @type {import('../../core/src/docs-types').ReferenceTranslationDoc} */
+
+export const docsDense = {
+ description: 'spacing/color/radius/type/elevation token ref',
+ sections: [
+ { title: 'Spacing', content: [{ type: 'prose', text: 'defined in tokens.stylex.ts. gap props use space0-space12.' }, null] },
+ { title: 'Size', content: [{ type: 'prose', text: 'control heights for buttons/inputs/selectors.' }, null] },
+ { title: 'Color', content: [{ type: 'prose', text: 'semantic colors, support light-dark() auto switching.' }, null, null, null] },
+ { title: 'Radius', content: [null] },
+ { title: 'Elevation', content: [null] },
+ { title: 'Typography', content: [null, null, null, null] },
+ { title: 'StyleX Usage', content: [null, null] },
+ ],
+};
diff --git a/packages/cli/docs/tokens.doc.mjs b/packages/cli/docs/tokens.doc.mjs
new file mode 100644
index 0000000000..a37c5b0985
--- /dev/null
+++ b/packages/cli/docs/tokens.doc.mjs
@@ -0,0 +1,216 @@
+/** @type {import('../../core/src/docs-types').ReferenceDoc} */
+
+export const docs = {
+ name: 'tokens',
+ title: 'XDS Design Tokens',
+ description: 'Spacing, color, radius, typography, and elevation token reference.',
+
+ sections: [
+ {
+ title: 'Spacing Tokens',
+ content: [
+ {
+ type: 'prose',
+ text: 'All design tokens are defined in packages/core/src/theme/tokens.stylex.ts. Component gap props use space0-space12 which map to these tokens.',
+ },
+ {
+ type: 'table',
+ headers: ['Token', 'Value', 'Usage'],
+ rows: [
+ ['--spacing-0', '0px', 'No spacing'],
+ ['--spacing-0-5', '2px', 'Hairline spacing'],
+ ['--spacing-1', '4px', 'Tight spacing'],
+ ['--spacing-2', '8px', 'Compact spacing'],
+ ['--spacing-3', '12px', 'Default small'],
+ ['--spacing-4', '16px', 'Default medium'],
+ ['--spacing-5', '20px', 'Comfortable'],
+ ['--spacing-6', '24px', 'Loose'],
+ ['--spacing-7', '28px', 'Semi-loose'],
+ ['--spacing-8', '32px', 'Extra loose'],
+ ['--spacing-9', '36px', 'Spacious'],
+ ['--spacing-10', '40px', 'Extra spacious'],
+ ['--spacing-11', '44px', 'Ultra spacious'],
+ ['--spacing-12', '48px', 'Maximum spacing'],
+ ],
+ },
+ ],
+ },
+ {
+ title: 'Size Tokens',
+ content: [
+ {
+ type: 'prose',
+ text: 'Control heights for consistent sizing across buttons, inputs, and selectors.',
+ },
+ {
+ type: 'table',
+ headers: ['Token', 'Value', 'Usage'],
+ rows: [
+ ['--size-sm', '28px', 'Compact controls'],
+ ['--size-md', '32px', 'Default control size'],
+ ['--size-lg', '36px', 'Larger, more prominent controls'],
+ ],
+ },
+ ],
+ },
+ {
+ title: 'Color Tokens',
+ content: [
+ {
+ type: 'prose',
+ text: 'Semantic colors for consistent theming. All colors support light-dark() for automatic mode switching.',
+ },
+ {
+ type: 'table',
+ headers: ['Token', 'Usage'],
+ rows: [
+ ['--color-accent', 'Primary action color'],
+ ['--color-surface', 'Background surface'],
+ ['--color-wash', 'Secondary background'],
+ ['--color-positive', 'Success states'],
+ ['--color-negative', 'Error states'],
+ ['--color-warning', 'Warning states'],
+ ],
+ },
+ {
+ type: 'table',
+ headers: ['Token', 'Usage'],
+ rows: [
+ ['--color-text-primary', 'Main text'],
+ ['--color-text-secondary', 'Secondary text'],
+ ['--color-text-disabled', 'Disabled text'],
+ ['--color-text-link', 'Link text'],
+ ],
+ },
+ {
+ type: 'table',
+ headers: ['Token', 'Usage'],
+ rows: [
+ ['--color-icon-primary', 'Main icons'],
+ ['--color-icon-secondary', 'Secondary icons'],
+ ['--color-icon-disabled', 'Disabled icons'],
+ ],
+ },
+ ],
+ },
+ {
+ title: 'Radius Tokens',
+ content: [
+ {
+ type: 'table',
+ headers: ['Token', 'Value', 'Usage'],
+ rows: [
+ ['--radius-rounded', '9999px', 'Pills, avatars'],
+ ['--radius-container', '12px', 'Cards, modals'],
+ ['--radius-element', '8px', 'Buttons, inputs'],
+ ['--radius-content', '4px', 'Small elements'],
+ ['--radius-inner', '0px', 'No radius'],
+ ],
+ },
+ ],
+ },
+ {
+ title: 'Elevation Tokens',
+ content: [
+ {
+ type: 'table',
+ headers: ['Token', 'Usage'],
+ rows: [
+ ['--elevation-base', 'Subtle shadow'],
+ ['--elevation-thumb', 'Slider thumbs'],
+ ['--elevation-menu', 'Dropdowns, menus'],
+ ['--elevation-dialog', 'Modals, dialogs'],
+ ['--elevation-hover', 'Hover states'],
+ ],
+ },
+ ],
+ },
+ {
+ title: 'Typography Tokens',
+ content: [
+ {
+ type: 'list',
+ style: 'unordered',
+ items: [
+ '--font-body: System UI font stack',
+ '--font-code: Monospace font stack',
+ '--font-heading: System UI font stack',
+ ],
+ },
+ {
+ type: 'table',
+ headers: ['Token', 'Value'],
+ rows: [
+ ['--text-4xs', '8px'],
+ ['--text-3xs', '10px'],
+ ['--text-2xs', '11px'],
+ ['--text-xsm', '12px'],
+ ['--text-sm', '13px'],
+ ['--text-base', '14px (default)'],
+ ['--text-lg', '16px'],
+ ['--text-xl', '18px'],
+ ['--text-2xl', '20px'],
+ ['--text-3xl', '24px'],
+ ['--text-4xl', '32px'],
+ ],
+ },
+ {
+ type: 'list',
+ style: 'unordered',
+ items: [
+ '--font-weight-normal: 400',
+ '--font-weight-medium: 500',
+ '--font-weight-semibold: 600',
+ '--font-weight-bold: 700',
+ ],
+ },
+ {
+ type: 'table',
+ headers: ['Token', 'Value', 'Usage'],
+ rows: [
+ ['--leading-tight', '1.25', 'Display text, headings'],
+ ['--leading-snug', '1.375', 'Compact body text, headings'],
+ ['--leading-base', '1.4286', 'Body text with --text-base'],
+ ['--leading-normal', '1.5', 'Body text, large body'],
+ ['--leading-relaxed', '1.625', 'Editorial body, reading text'],
+ ],
+ },
+ ],
+ },
+ {
+ title: 'Usage in StyleX',
+ content: [
+ {
+ type: 'code',
+ lang: 'tsx',
+ label: 'Using token imports',
+ code: `import * as stylex from '@stylexjs/stylex';
+import {colorVars, spacingVars, sizeVars, radiusVars} from '@xds/core';
+
+const styles = stylex.create({
+ card: {
+ padding: spacingVars['--spacing-4'],
+ backgroundColor: colorVars['--color-surface'],
+ borderRadius: radiusVars['--radius-container'],
+ },
+ button: {
+ height: sizeVars['--size-md'],
+ },
+});`,
+ },
+ {
+ type: 'code',
+ lang: 'tsx',
+ label: 'Using CSS custom properties directly',
+ code: `const styles = stylex.create({
+ card: {
+ padding: 'var(--spacing-4)',
+ backgroundColor: 'var(--color-surface)',
+ borderRadius: 'var(--radius-container)',
+ },
+});`,
+ },
+ ],
+ },
+ ],
+};
diff --git a/packages/cli/docs/tokens.doc.zh.mjs b/packages/cli/docs/tokens.doc.zh.mjs
new file mode 100644
index 0000000000..960c0ad685
--- /dev/null
+++ b/packages/cli/docs/tokens.doc.zh.mjs
@@ -0,0 +1,14 @@
+/** @type {import('../../core/src/docs-types').ReferenceTranslationDoc} */
+
+export const docsZh = {
+ description: '间距、颜色、圆角、排版和阴影设计令牌参考。',
+ sections: [
+ { title: '间距令牌', content: [{ type: 'prose', text: '所有设计令牌定义在 packages/core/src/theme/tokens.stylex.ts 中。组件的 gap 属性使用 space0-space12 映射到这些令牌。' }, null] },
+ { title: '尺寸令牌', content: [{ type: 'prose', text: '控制按钮、输入框和选择器的一致高度。' }, null] },
+ { title: '颜色令牌', content: [{ type: 'prose', text: '语义化颜色,支持 light-dark() 自动切换模式。' }, null, null, null] },
+ { title: '圆角令牌', content: [null] },
+ { title: '阴影令牌', content: [null] },
+ { title: '排版令牌', content: [null, null, null, null] },
+ { title: 'StyleX 用法', content: [null, null] },
+ ],
+};
diff --git a/packages/cli/src/commands/docs.mjs b/packages/cli/src/commands/docs.mjs
index a41fb30410..ec80a14801 100644
--- a/packages/cli/src/commands/docs.mjs
+++ b/packages/cli/src/commands/docs.mjs
@@ -1,54 +1,245 @@
/**
* @file docs command — Print XDS reference docs
*
- * `xds docs` lists available topics.
- * `xds docs <topic>` prints the doc content.
+ * Auto-discovers .doc.mjs files from the docs/ directory.
+ * Supports --detail (full|compact|brief) and --lang (en|zh|dense).
+ *
+ * Usage:
+ * xds docs List available topics
+ * xds docs <topic> Print full doc
+ * xds docs <topic> <section> Print one section
*/
import * as fs from 'node:fs';
import * as path from 'node:path';
+import {pathToFileURL} from 'node:url';
import {CLI_ROOT} from '../utils/paths.mjs';
const DOCS_DIR = path.join(CLI_ROOT, 'docs');
-const TOPICS = {
- principles: 'XDS design principles, rules, and anti-patterns',
- tokens: 'Full design token reference (spacing, colors, radius, typography)',
- theme: 'Theme system: XDSTheme, custom themes, overrides, light/dark mode',
-};
+// ─── Discovery ───────────────────────────────────────────────────────────────
+
+/**
+ * Discover all .doc.mjs files in the docs directory.
+ * Returns a map of topic name -> file path.
+ */
+function discoverTopics() {
+ const topics = {};
+ if (!fs.existsSync(DOCS_DIR)) return topics;
+
+ for (const file of fs.readdirSync(DOCS_DIR)) {
+ // Match foo.doc.mjs but not foo.doc.dense.mjs or foo.doc.zh.mjs
+ const match = file.match(/^(\w+)\.doc\.mjs$/);
+ if (match) {
+ topics[match[1]] = path.join(DOCS_DIR, file);
+ }
+ }
+ return topics;
+}
+
+// ─── Loading ─────────────────────────────────────────────────────────────────
+
+/**
+ * Load a reference doc, optionally merging a translation overlay.
+ */
+async function loadReferenceDocs(docPath, {lang} = {}) {
+ const mod = await import(pathToFileURL(docPath).href);
+ const docs = mod.docs;
+
+ if (!lang || lang === 'en') return docs;
+
+ // Try loading translation file: foo.doc.zh.mjs or foo.doc.dense.mjs
+ const dir = path.dirname(docPath);
+ const base = path.basename(docPath, '.doc.mjs');
+ const locale = lang === 'dense' ? 'dense' : lang;
+ const translationPath = path.join(dir, `${base}.doc.${locale}.mjs`);
+
+ if (!fs.existsSync(translationPath)) return docs;
+
+ const translationMod = await import(pathToFileURL(translationPath).href);
+ const translation = translationMod.docsZh || translationMod.docsDense;
+
+ if (!translation) return docs;
+
+ return mergeTranslation(docs, translation);
+}
+
+/**
+ * Merge a translation overlay onto a base reference doc.
+ * Prose and list blocks get swapped. Code and table blocks pass through.
+ */
+function mergeTranslation(base, translation) {
+ return {
+ ...base,
+ description: translation.description || base.description,
+ sections: base.sections.map((section, si) => {
+ const ts = translation.sections?.[si];
+ if (!ts) return section;
+
+ return {
+ ...section,
+ title: ts.title || section.title,
+ content: section.content.map((block, bi) => {
+ const tb = ts.content?.[bi];
+ if (!tb) return block;
+
+ if (tb.type === 'prose' && block.type === 'prose') {
+ return {...block, text: tb.text};
+ }
+ if (tb.type === 'list' && block.type === 'list') {
+ return {...block, items: tb.items};
+ }
+ return block;
+ }),
+ };
+ }),
+ };
+}
+
+// ─── Formatting ──────────────────────────────────────────────────────────────
+
+function formatTable(headers, rows) {
+ const widths = headers.map((h, i) =>
+ Math.max(h.length, ...rows.map(r => (r[i] || '').length)),
+ );
+ const sep = widths.map(w => '-'.repeat(w)).join(' | ');
+ const head = headers.map((h, i) => h.padEnd(widths[i])).join(' | ');
+ const body = rows
+ .map(r => r.map((c, i) => (c || '').padEnd(widths[i])).join(' | '))
+ .join('\n');
+ return `${head}\n${sep}\n${body}`;
+}
+
+function formatTableCompact(headers, rows) {
+ // key=value pairs, one line per row
+ return rows.map(r => r.join(' = ')).join('\n');
+}
+
+function formatBlock(block, detail) {
+ switch (block.type) {
+ case 'prose':
+ return block.text;
+
+ case 'code':
+ if (detail === 'compact' || detail === 'brief') return null;
+ const label = block.label ? `// ${block.label}\n` : '';
+ return `\`\`\`${block.lang}\n${label}${block.code}\n\`\`\``;
+
+ case 'table':
+ if (detail === 'brief') {
+ // One-liner: first two columns as key=value
+ return block.rows.map(r => r.slice(0, 2).join('=')).join(' | ');
+ }
+ if (detail === 'compact') {
+ return formatTableCompact(block.headers, block.rows);
+ }
+ return formatTable(block.headers, block.rows);
+
+ case 'list': {
+ const prefix = block.style === 'ordered' ? (i) => `${i + 1}. `
+ : block.style === 'dont' ? () => '❌ '
+ : block.style === 'do' ? () => '✓ '
+ : () => '- ';
+ return block.items.map((item, i) => `${prefix(i)}${item}`).join('\n');
+ }
+
+ default:
+ return null;
+ }
+}
+
+function formatSection(section, detail) {
+ const blocks = section.content
+ .map(b => formatBlock(b, detail))
+ .filter(Boolean);
+
+ if (detail === 'brief') {
+ // Just the first prose block or first table one-liner
+ const first = blocks[0] || '';
+ return `${section.title}: ${first.split('\n')[0]}`;
+ }
+
+ const heading = detail === 'compact' ? `[${section.title}]` : `## ${section.title}`;
+ return `${heading}\n\n${blocks.join('\n\n')}`;
+}
+
+function formatReferenceFull(docs, detail) {
+ if (detail === 'brief') {
+ const header = `${docs.title}: ${docs.description}`;
+ const sections = docs.sections.map(s => formatSection(s, detail));
+ return `${header}\n${sections.join('\n')}`;
+ }
+
+ const header = detail === 'compact'
+ ? `# ${docs.title}\n${docs.description}`
+ : `# ${docs.title}\n\n${docs.description}`;
+ const sections = docs.sections.map(s => formatSection(s, detail));
+ const sep = detail === 'compact' ? '\n\n' : '\n\n';
+ return `${header}\n\n${sections.join(sep)}`;
+}
+
+// ─── Command ─────────────────────────────────────────────────────────────────
export function registerDocs(program) {
program
- .command('docs [topic]')
- .description('Print XDS reference docs (principles, tokens)')
- .action(topic => {
+ .command('docs [topic] [section]')
+ .description('Print XDS reference docs')
+ .action(async (topic, section) => {
+ const topics = discoverTopics();
+ const lang = program.opts().lang || null;
+ const zh = program.opts().zh || false;
+ const dense = program.opts().dense || false;
+ const detail = program.opts().detail || 'full';
+ const effectiveLang = lang || (dense ? 'dense' : zh ? 'zh' : null);
+
if (!topic) {
console.log('\nAvailable docs:\n');
- for (const [name, desc] of Object.entries(TOPICS)) {
- console.log(` ${name.padEnd(14)} ${desc}`);
+ for (const [name, docPath] of Object.entries(topics)) {
+ try {
+ const mod = await import(pathToFileURL(docPath).href);
+ console.log(` ${name.padEnd(14)} ${mod.docs.description}`);
+ } catch {
+ console.log(` ${name}`);
+ }
}
- console.log('\nUsage: npx xds docs <topic>\n');
+ console.log('\nUsage: npx xds docs <topic>');
+ console.log(' npx xds docs <topic> <section>\n');
return;
}
- const normalized = topic.toLowerCase().replace(/\.md$/, '');
+ const normalized = topic.toLowerCase();
+
+ if (!topics[normalized]) {
+ // Fallback: try legacy .md file
+ const mdPath = path.join(DOCS_DIR, `${normalized}.md`);
+ if (fs.existsSync(mdPath)) {
+ console.log(fs.readFileSync(mdPath, 'utf-8'));
+ return;
+ }
- if (!TOPICS[normalized]) {
console.error(`Error: Unknown topic "${topic}".`);
- console.error(
- `Available topics: ${Object.keys(TOPICS).join(', ')}`,
- );
+ console.error(`Available topics: ${Object.keys(topics).join(', ')}`);
process.exit(1);
}
- const docPath = path.join(DOCS_DIR, `${normalized}.md`);
+ const docs = await loadReferenceDocs(topics[normalized], {lang: effectiveLang});
- if (!fs.existsSync(docPath)) {
- console.error(`Error: Doc file not found at ${docPath}`);
- process.exit(1);
+ if (section) {
+ const normalizedSection = section.toLowerCase();
+ const match = docs.sections.find(
+ s => s.title.toLowerCase().includes(normalizedSection),
+ );
+ if (!match) {
+ console.error(`Error: Section "${section}" not found in "${topic}".`);
+ console.error(
+ `Available sections: ${docs.sections.map(s => s.title).join(', ')}`,
+ );
+ process.exit(1);
+ }
+ console.log(formatSection(match, detail));
+ return;
}
- const content = fs.readFileSync(docPath, 'utf-8');
- console.log(content);
+ console.log(formatReferenceFull(docs, detail));
});
}
diff --git a/packages/core/src/docs-types.ts b/packages/core/src/docs-types.ts
index e16f4abdb7..f3caf73488 100644
--- a/packages/core/src/docs-types.ts
+++ b/packages/core/src/docs-types.ts
@@ -242,3 +242,91 @@ export interface TranslationDoc {
propDescriptions?: Record<string, string>;
}>;
}
+
+// =============================================================================
+// Reference Documentation Types
+// =============================================================================
+
+/**
+ * A content block within a reference doc section.
+ * Ordered array of these makes up a section's content.
+ * New block types can be added without breaking existing docs.
+ *
+ * @example
+ * ```
+ * { type: 'prose', text: 'Spacing tokens control gap and padding...' }
+ * { type: 'code', lang: 'tsx', code: 'padding: spacingVars[...]' }
+ * { type: 'table', headers: ['Token', 'Value'], rows: [['--spacing-4', '16px']] }
+ * { type: 'list', style: 'do', items: ['Use semantic tokens'] }
+ * ```
+ */
+export type ContentBlock =
+ | {type: 'prose'; text: string}
+ | {type: 'code'; lang: string; code: string; label?: string}
+ | {type: 'table'; headers: string[]; rows: string[][]}
+ | {
+ type: 'list';
+ style: 'ordered' | 'unordered' | 'do' | 'dont';
+ items: string[];
+ };
+
+/**
+ * A section within a reference doc. Sections are the primary
+ * organizational unit — each becomes an h2 in full output,
+ * and can be individually retrieved via `xds docs <topic> <section>`.
+ */
+export interface ReferenceSection {
+ /** Section title, e.g. "Spacing Tokens", "Light/Dark Mode" */
+ title: string;
+ /** Ordered content blocks. Mix prose, code, tables, and lists freely. */
+ content: ContentBlock[];
+}
+
+/**
+ * A reference documentation file (.doc.mjs).
+ *
+ * Reference docs cover topics like design tokens, principles, theming,
+ * patterns, accessibility, and migration guides. Unlike ComponentDoc,
+ * they aren't tied to a specific component — just drop a .doc.mjs file
+ * in the docs/ directory and it shows up in `xds docs`.
+ *
+ * Every reference .doc.mjs must export a single `docs` constant:
+ *
+ * /** @type {import('../../core/src/docs-types').ReferenceDoc} *\/
+ * export const docs = { ... };
+ */
+export interface ReferenceDoc {
+ /** URL-safe identifier, used as the CLI topic name. e.g. 'tokens', 'principles' */
+ name: string;
+ /** Human-readable title. e.g. 'XDS Design Tokens' */
+ title: string;
+ /** One-line summary shown in topic listings. */
+ description: string;
+ /** Ordered sections that make up the doc. */
+ sections: ReferenceSection[];
+}
+
+/**
+ * Translation/compression overlay for reference documentation.
+ *
+ * Swaps prose text and list items. Code blocks and table data
+ * are NOT translated — they stay as-is from the base doc.
+ *
+ * Used by `docsZh` (Chinese) and `docsDense` (compressed format).
+ */
+export interface ReferenceTranslationDoc {
+ /** Translated/compressed description. */
+ description: string;
+ /** Section overrides. Array indices must match base doc sections. */
+ sections: {
+ /** Translated section title. */
+ title: string;
+ /** Content block overrides. Only prose and list blocks need entries.
+ * Use null for blocks that don't change (code, table). */
+ content: (
+ | {type: 'prose'; text: string}
+ | {type: 'list'; items: string[]}
+ | null
+ )[];
+ }[];
+}