An open source design system that's fully customizable and agent ready
TypeScript
fix(cli): component resolution for sub-components and showcase priority (#1916)
Cindy Zhange2d946c4b5ff
diff --git a/packages/cli/README.md b/packages/cli/README.mdindex 0fd8d0d883..b86744aa16 100644--- a/packages/cli/README.md+++ b/packages/cli/README.md@@ -11,18 +11,18 @@ npx xds template --list## Commands-| Command | Description |-|---------|-------------|-| `init` | Initialize XDS in your project — installs packages, sets up theming, adds AI agent docs |-| `component` | List components or print detailed docs, props, usage examples, and source |-| `docs` | Print reference documentation (tokens, theme, color, typography, spacing, etc.) |-| `template` | Inject page or block templates into your project |-| `hook` | List hooks and print hook documentation |-| `swizzle` | Copy component source into your project for deep customization |-| `upgrade` | Run codemods to migrate between XDS versions |-| `theme build` | Compile a defineTheme file to production CSS and JS |-| `discover` | Discover external XDS packages and components |-| `gap-report` | Report a gap when a component doesn't meet your needs |+| Command | Description |+| ------------- | --------------------------------------------------------------------------------------- |+| `init` | Initialize XDS in your project — installs packages, sets up theming, adds AI agent docs |+| `component` | List components or print detailed docs, props, usage examples, and source |+| `docs` | Print reference documentation (tokens, theme, color, typography, spacing, etc.) |+| `template` | Inject page or block templates into your project |+| `hook` | List hooks and print hook documentation |+| `swizzle` | Copy component source into your project for deep customization |+| `upgrade` | Run codemods to migrate between XDS versions |+| `theme build` | Compile a defineTheme file to production CSS and JS |+| `discover` | Discover external XDS packages and components |+| `gap-report` | Report a gap when a component doesn't meet your needs |### Global options@@ -110,35 +110,37 @@ detail.data.name; // already narrowedEvery response has a `type` string that uniquely identifies it:-| Command | Type | Response |-|---------|------|----------|-| `xds --json component [--list]` | `component.list` | `ComponentListResponse` |-| `xds --json component --detail brief` | `component.brief` | `ComponentBriefResponse` |-| `xds --json component <name>` | `component.detail` | `ComponentDetailResponse` |-| `xds --json component <name> --props` | `component.detail.props` | `ComponentDetailPropsResponse` |-| `xds --json component <name> --source` | `component.detail.source` | `ComponentDetailSourceResponse` |-| `xds --json discover` | `discover.list` | `DiscoverListResponse` |-| `xds --json discover @scope/name` | `discover.detail` | `DiscoverDetailResponse` |-| `xds --json discover @scope/name/Comp` | `discover.detail.doc` | `DiscoverDetailDocResponse` |-| `xds --json discover <search>` | `discover.search` | `DiscoverSearchResponse` |-| `xds --json docs` | `docs.list` | `DocsListResponse` |-| `xds --json docs <topic>` | `docs.detail` | `DocsDetailResponse` |-| `xds --json docs <topic> <section>` | `docs.detail.section` | `DocsDetailSectionResponse` |-| `xds --json template [--list]` | `template.list` | `TemplateListResponse` |-| `xds --json template <name>` | `template.show` | `TemplateShowResponse` |-| `xds --json template <name> --skeleton` | `template.skeleton` | `TemplateSkeletonResponse` |-| `xds --json template <name> [path]` | `template.copy` | `TemplateCopyResponse` |-| `xds --json hook [--list]` | `hook.list` | `HookListResponse` |-| `xds --json hook <name>` | `hook.detail` | `HookDetailResponse` |-| `xds --json swizzle [--list]` | `swizzle.list` | `SwizzleListResponse` |-| `xds --json swizzle <component>` | `swizzle.copy` | `SwizzleCopyResponse` |-| `xds --json theme build <file>` | `theme.build` | `ThemeBuildResponse` |-| `xds --json upgrade --list` | `upgrade.list` | `UpgradeListResponse` |-| `xds --json upgrade [--apply]` | `upgrade.run` | `UpgradeRunResponse` |-| `xds --json gap-report --list-categories` | `gap-report.categories` | `GapReportCategoriesResponse` |-| `xds --json gap-report --component X ...` | `gap-report.file` | `GapReportFileResponse` |-| any error | — | `CLIError` |-| unsupported command | — | `CLIUnsupportedError` |+| Command | Type | Response |+| ----------------------------------------- | --------------------------- | --------------------------------- |+| `xds --json component [--list]` | `component.list` | `ComponentListResponse` |+| `xds --json component --detail brief` | `component.brief` | `ComponentBriefResponse` |+| `xds --json component <name>` | `component.detail` | `ComponentDetailResponse` |+| `xds --json component <name> --props` | `component.detail.props` | `ComponentDetailPropsResponse` |+| `xds --json component <name> --source` | `component.detail.source` | `ComponentDetailSourceResponse` |+| `xds --json component <name> --showcase` | `component.detail.showcase` | `ComponentDetailShowcaseResponse` |+| `xds --json component <name> --blocks` | `component.detail.blocks` | `ComponentDetailBlocksResponse` |+| `xds --json discover` | `discover.list` | `DiscoverListResponse` |+| `xds --json discover @scope/name` | `discover.detail` | `DiscoverDetailResponse` |+| `xds --json discover @scope/name/Comp` | `discover.detail.doc` | `DiscoverDetailDocResponse` |+| `xds --json discover <search>` | `discover.search` | `DiscoverSearchResponse` |+| `xds --json docs` | `docs.list` | `DocsListResponse` |+| `xds --json docs <topic>` | `docs.detail` | `DocsDetailResponse` |+| `xds --json docs <topic> <section>` | `docs.detail.section` | `DocsDetailSectionResponse` |+| `xds --json template [--list]` | `template.list` | `TemplateListResponse` |+| `xds --json template <name>` | `template.show` | `TemplateShowResponse` |+| `xds --json template <name> --skeleton` | `template.skeleton` | `TemplateSkeletonResponse` |+| `xds --json template <name> [path]` | `template.copy` | `TemplateCopyResponse` |+| `xds --json hook [--list]` | `hook.list` | `HookListResponse` |+| `xds --json hook <name>` | `hook.detail` | `HookDetailResponse` |+| `xds --json swizzle [--list]` | `swizzle.list` | `SwizzleListResponse` |+| `xds --json swizzle <component>` | `swizzle.copy` | `SwizzleCopyResponse` |+| `xds --json theme build <file>` | `theme.build` | `ThemeBuildResponse` |+| `xds --json upgrade --list` | `upgrade.list` | `UpgradeListResponse` |+| `xds --json upgrade [--apply]` | `upgrade.run` | `UpgradeRunResponse` |+| `xds --json gap-report --list-categories` | `gap-report.categories` | `GapReportCategoriesResponse` |+| `xds --json gap-report --component X ...` | `gap-report.file` | `GapReportFileResponse` |+| any error | — | `CLIError` |+| unsupported command | — | `CLIUnsupportedError` |## Configuration@@ -147,7 +149,7 @@ The CLI reads from an optional `xds.config.mjs` in your project root:```javascriptexport default {templates: {- get: async (id) => fetchTemplateFromAPI(id),+ get: async id => fetchTemplateFromAPI(id),},gapReport: {url: 'https://your-api.com/gaps',diff --git a/packages/cli/src/api/component.mjs b/packages/cli/src/api/component.mjsindex 22794e6fd6..d2a8ea9a49 100644--- a/packages/cli/src/api/component.mjs+++ b/packages/cli/src/api/component.mjs@@ -18,7 +18,7 @@ import {import {loadDocs} from '../lib/component-loader.mjs';import {searchComponents} from '../lib/string-utils.mjs';import {XDSError} from './error.mjs';-import {findShowcase} from './template.mjs';+import {findShowcase, findRelatedBlocks} from './template.mjs';/*** @param {string} [name]@@ -29,6 +29,7 @@ import {findShowcase} from './template.mjs';* @param {boolean} [options.props]* @param {boolean} [options.source]* @param {boolean} [options.showcase]+ * @param {boolean} [options.blocks]* @param {'full'|'compact'|'brief'} [options.detail]* @param {string} [options.lang]* @param {boolean} [options.zh]@@ -43,6 +44,7 @@ export async function component(name, options = {}) {props = false,source = false,showcase = false,+ blocks = false,detail = 'full',lang = null,zh = false,@@ -200,6 +202,71 @@ export async function component(name, options = {}) {const docs = await loadDocs(readmePath, {zh, dense, lang});+ // ── Blocks mode ──────────────────────────────────────────────+ if (blocks) {+ const allBlocks = await findRelatedBlocks(dirName);+ const toEntry = (b) => ({+ name: b.dirName,+ displayName: b.name,+ description: b.description,+ isShowcase: b.isShowcase ?? false,+ category: b.category,+ });++ // Examples: blocks in the component's own directory, or+ // componentsUsed match for sub-components without a directory.+ const ownDir = allBlocks.filter(b => b.category.split('/').pop() === dirName);+ const examples = ownDir.length > 0+ ? ownDir+ : allBlocks.filter(b => b.componentsUsed?.some(c => c === dirName));+ const exampleSet = new Set(examples.map(b => b.dirName));++ // Showcase: the single hero example from the examples list.+ const showcaseBlock = examples.find(b => b.isShowcase) || null;++ // Related: everything else that uses this component but isn't+ // primarily about it (e.g. a Dialog block that has a Button).+ const related = allBlocks.filter(b => !exampleSet.has(b.dirName));++ return {+ type: 'component.detail.blocks',+ data: {+ component: dirName,+ showcase: showcaseBlock ? toEntry(showcaseBlock) : null,+ examples: examples.filter(b => b !== showcaseBlock).map(toEntry),+ related: related.map(toEntry),+ },+ };+ }++ // ── Sub-component scoping ────────────────────────────────────+ // If the user asked for "Code" but the doc is for "CodeBlock" (parent),+ // scope the response to just the matching sub-component.+ const requestedXDS = `XDS${dirName}`;+ const isParentDoc = docs.name && docs.name.toLowerCase() !== dirName.toLowerCase();+ const matchingComponent = isParentDoc && docs.components+ ? docs.components.find(c => c.name === requestedXDS || c.name === dirName)+ : null;++ if (matchingComponent) {+ const scoped = {+ name: dirName,+ description: matchingComponent.description,+ props: matchingComponent.props,+ // Keep parent context for reference+ components: [matchingComponent],+ parentDoc: docs.name,+ import: resolveImportPath(coreDir, dirName),+ };+ if (docs.usage) scoped.usage = docs.usage;+ if (docs.theming) scoped.theming = docs.theming;++ if (props) {+ return {type: 'component.detail.props', data: matchingComponent.props || []};+ }+ return {type: 'component.detail', data: scoped};+ }+if (props) {const p = docs.props || (docs.components ? docs.components.flatMap(c => c.props || []) : []);return {type: 'component.detail.props', data: p};diff --git a/packages/cli/src/api/template.mjs b/packages/cli/src/api/template.mjsindex 193c65d89d..abb3f35f7b 100644--- a/packages/cli/src/api/template.mjs+++ b/packages/cli/src/api/template.mjs@@ -111,23 +111,29 @@ export async function findRelatedBlocks(componentName) {export async function findShowcase(componentName) {const blocks = await discoverBlocks();const lc = componentName.toLowerCase();- // Match by directory name (category is "components/Badge" → ends with "/Badge"),- // by componentsUsed, or by exact display name.- const match = blocks.find(b => {- if (!b.isShowcase) return false;+ const showcases = blocks.filter(b => b.isShowcase);++ const toResult = (b) => ({+ name: b.name,+ aspectRatio: b.aspectRatio,+ filePath: b.filePath,+ docPath: b.docPath,+ });++ // Priority 1: own directory (components/Badge/ for "Badge")+ const dirMatch = showcases.find(b => {const catDir = b.category.split('/').pop()?.toLowerCase();- if (catDir === lc) return true;- if (b.componentsUsed.some(c => c.toLowerCase() === lc)) return true;- if (b.name.toLowerCase() === lc) return true;- return false;+ return catDir === lc;});- if (!match) return null;- return {- name: match.name,- aspectRatio: match.aspectRatio,- filePath: match.filePath,- docPath: match.docPath,- };+ if (dirMatch) return toResult(dirMatch);++ // Priority 2: componentsUsed in any directory (ClickableCard in Card/)+ const usedMatch = showcases.find(b =>+ b.componentsUsed.some(c => c.toLowerCase() === lc),+ );+ if (usedMatch) return toResult(usedMatch);++ return null;}const UBIQUITOUS = new Set([diff --git a/packages/cli/src/commands/component-resolution.test.mjs b/packages/cli/src/commands/component-resolution.test.mjsnew file mode 100644index 0000000000..2a518e9855--- /dev/null+++ b/packages/cli/src/commands/component-resolution.test.mjs@@ -0,0 +1,172 @@+import {describe, it, expect} from 'vitest';+import {component} from '../api/component.mjs';+import {findShowcase, findRelatedBlocks} from '../api/template.mjs';++const CWD = {cwd: '.'};++// ─── Bug: sub-component doc resolution ──────────────────────────+// When asking for a sub-component (Code, HStack, Heading, SideNavItem),+// the API should scope the response to that specific sub-component,+// not return the entire parent doc.++describe('component() sub-component scoping', () => {+ it('component("Code") returns Code, not CodeBlock', async () => {+ const result = await component('Code', CWD);+ // Should be scoped to the Code sub-component+ expect(result.data.name).not.toBe('CodeBlock');+ // The response should contain Code's props, not CodeBlock's+ const props = result.data.props || result.data.components?.flatMap(c => c.props || []);+ const propNames = props?.map(p => p.name) || [];+ // Code has 'children', CodeBlock has 'code' + 'language'+ expect(propNames).toContain('children');+ expect(propNames).not.toContain('language');+ });++ it('component("HStack") returns HStack, not Stack', async () => {+ const result = await component('HStack', CWD);+ expect(result.data.name).not.toBe('Stack');+ });++ it('component("Heading") returns Heading, not Text', async () => {+ const result = await component('Heading', CWD);+ expect(result.data.name).not.toBe('Text');+ });++ it('component("SideNavItem") returns SideNavItem, not SideNav', async () => {+ const result = await component('SideNavItem', CWD);+ expect(result.data.name).not.toBe('SideNav');+ });++ it('component("GridSpan") returns GridSpan, not Grid', async () => {+ const result = await component('GridSpan', CWD);+ expect(result.data.name).not.toBe('Grid');+ });++ it('component("Tab") returns Tab, not TabList', async () => {+ const result = await component('Tab', CWD);+ expect(result.data.name).not.toBe('TabList');+ });++ // Non-regression: asking for the parent still returns the full doc+ it('component("CodeBlock") still returns full CodeBlock doc', async () => {+ const result = await component('CodeBlock', CWD);+ expect(result.data.name).toBe('CodeBlock');+ expect(result.data.components.length).toBeGreaterThan(1);+ });++ it('component("Stack") still returns full Stack doc', async () => {+ const result = await component('Stack', CWD);+ expect(result.data.name).toBe('Stack');+ });++ it('component("SideNav") still returns full SideNav doc', async () => {+ const result = await component('SideNav', CWD);+ expect(result.data.name).toBe('SideNav');+ });+});++// ─── Bug: findShowcase priority ─────────────────────────────────+// findShowcase should prioritize exact directory matches over+// componentsUsed matches from sibling directories.++describe('findShowcase() priority', () => {+ it('Badge resolves to Badge dir, not a sibling that uses Badge', async () => {+ const result = await findShowcase('Badge');+ expect(result).not.toBeNull();+ expect(result.filePath).toMatch(/\/Badge\//);+ });++ it('Avatar resolves to Avatar dir, not AvatarStatusDot', async () => {+ const result = await findShowcase('Avatar');+ expect(result).not.toBeNull();+ expect(result.filePath).toMatch(/\/Avatar\//);+ expect(result.filePath).not.toMatch(/AvatarStatusDot/);+ });++ it('ClickableCard resolves via componentsUsed in Card/', async () => {+ const result = await findShowcase('ClickableCard');+ expect(result).not.toBeNull();+ expect(result.name).toBe('ClickableCard');+ expect(result.filePath).toMatch(/\/Card\//);+ });++ it('SelectableCard resolves via componentsUsed in Card/', async () => {+ const result = await findShowcase('SelectableCard');+ expect(result).not.toBeNull();+ expect(result.name).toBe('SelectableCard');+ });++ it('Stack resolves to Stack dir despite componentsUsed elsewhere', async () => {+ const result = await findShowcase('Stack');+ expect(result).not.toBeNull();+ expect(result.filePath).toMatch(/\/Stack\//);+ });++ it('returns null for nonexistent component', async () => {+ const result = await findShowcase('NonExistentWidget');+ expect(result).toBeNull();+ });+});++// ─── Feature: component() → blocks (showcase, examples, related) ─+// The blocks API returns three separate lists so consumers can use+// the showcase hero, component-specific examples, and broader related+// blocks independently.++describe('component() blocks integration', () => {+ it('returns showcase, examples, and related as separate lists', async () => {+ const result = await component('Card', {...CWD, blocks: true});+ expect(result.type).toBe('component.detail.blocks');+ expect(result.data.component).toBe('Card');+ expect(result.data).toHaveProperty('showcase');+ expect(Array.isArray(result.data.examples)).toBe(true);+ expect(Array.isArray(result.data.related)).toBe(true);+ });++ it('showcase is the hero block for the component', async () => {+ const result = await component('Card', {...CWD, blocks: true});+ expect(result.data.showcase).not.toBeNull();+ expect(result.data.showcase.isShowcase).toBe(true);+ expect(result.data.showcase).toHaveProperty('name');+ expect(result.data.showcase).toHaveProperty('description');+ });++ it('examples are component-specific blocks excluding the showcase', async () => {+ const result = await component('Button', {...CWD, blocks: true});+ expect(result.data.showcase).not.toBeNull();+ expect(result.data.examples.length).toBeGreaterThan(0);+ // Showcase should not appear in examples+ const exampleNames = result.data.examples.map(b => b.name);+ expect(exampleNames).not.toContain(result.data.showcase.name);+ // Examples should be about Button, not random blocks that use Button+ for (const ex of result.data.examples) {+ expect(ex.category).toMatch(/Button/);+ }+ });++ it('related blocks use the component but are not primarily about it', async () => {+ const result = await component('Button', {...CWD, blocks: true});+ // Button is used in many blocks (dialogs, toolbars, etc.)+ expect(result.data.related.length).toBeGreaterThan(0);+ // Related should not overlap with examples or showcase+ const exampleNames = new Set(result.data.examples.map(b => b.name));+ for (const r of result.data.related) {+ expect(exampleNames.has(r.name)).toBe(false);+ expect(r.name).not.toBe(result.data.showcase?.name);+ }+ });++ it('sub-component blocks resolve via componentsUsed', async () => {+ const result = await component('ClickableCard', {...CWD, blocks: true});+ expect(result.data.component).toBe('ClickableCard');+ expect(result.data.showcase).not.toBeNull();+ expect(result.data.showcase.name).toMatch(/ClickableCard/);+ });++ it('component with no blocks returns null showcase and empty arrays', async () => {+ const result = await component('Theme', {...CWD, blocks: true});+ expect(result.data.showcase).toBeNull();+ expect(result.data.examples).toEqual([]);+ expect(result.data.related).toEqual([]);+ });+});diff --git a/packages/cli/src/commands/component/index.mjs b/packages/cli/src/commands/component/index.mjsindex 627358c31d..1f92c6dd5a 100644--- a/packages/cli/src/commands/component/index.mjs+++ b/packages/cli/src/commands/component/index.mjs@@ -34,6 +34,7 @@ export function registerComponent(program) {.option('--props', 'Print only the props table').option('--source', 'Print component source code').option('--showcase', 'Print showcase source code')+ .option('--blocks', 'List example blocks: showcase, examples, and related').action(async (name, options) => {const run = getRunPrefix();const zh = program.opts().zh || false;@@ -59,6 +60,7 @@ export function registerComponent(program) {props: options.props,source: options.source,showcase: options.showcase,+ blocks: options.blocks,detail,lang, zh, dense,});@@ -156,6 +158,32 @@ export function registerComponent(program) {console.log(result.data.source);break;}++ case 'component.detail.blocks': {+ const {showcase, examples, related} = result.data;+ if (showcase) {+ console.log(`\nShowcase: ${showcase.displayName}`);+ if (showcase.description) console.log(` ${showcase.description}`);+ }+ if (examples.length > 0) {+ console.log('\nExamples:\n');+ for (const b of examples) {+ console.log(` ${b.name}`);+ if (b.description) console.log(` ${b.description}`);+ }+ }+ if (related.length > 0) {+ console.log(`\nRelated: ${related.length} blocks that use ${result.data.component}\n`);+ for (const b of related) {+ console.log(` ${b.name}`);+ }+ }+ if (!showcase && examples.length === 0 && related.length === 0) {+ console.log(`\nNo blocks found for ${result.data.component}`);+ }+ console.log('');+ break;+ }}});}diff --git a/packages/cli/src/types/component.d.ts b/packages/cli/src/types/component.d.tsindex 6c271479fb..fb661fc35b 100644--- a/packages/cli/src/types/component.d.ts+++ b/packages/cli/src/types/component.d.ts@@ -11,6 +11,7 @@* xds --json component Button --props -> component.detail.props* xds --json component Button --source -> component.detail.source* xds --json component Button --showcase -> component.detail.showcase+ * xds --json component Button --blocks -> component.detail.blocks* (not found) -> CLIError*/@@ -57,3 +58,22 @@ export interface ComponentDetailShowcaseResponse {type: 'component.detail.showcase';data: {component: string; aspectRatio: number; source: string};}++/** xds --json component <name> --blocks */+export interface ComponentDetailBlocksResponse {+ type: 'component.detail.blocks';+ data: {+ component: string;+ showcase: BlockEntry | null;+ examples: BlockEntry[];+ related: BlockEntry[];+ };+}++export interface BlockEntry {+ name: string;+ displayName: string;+ description: string;+ isShowcase: boolean;+ category: string;+}