Skip to content

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

TypeScript

fix(docsite): render the component anatomy table (#4847)

AK78e8e1ce7788
diff --git a/apps/docsite/src/__tests__/anatomy-helpers.test.ts b/apps/docsite/src/__tests__/anatomy-helpers.test.ts
new file mode 100644
index 0000000000..3ef2492322
--- /dev/null
+++ b/apps/docsite/src/__tests__/anatomy-helpers.test.ts
@@ -0,0 +1,44 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {describe, expect, it} from 'vitest';
+import {anatomyDescription} from '../components/component-detail/anatomyHelpers';
+
+describe('anatomy description', () => {
+ it('marks a required element with a bold lead-in on its description', () => {
+ expect(
+ anatomyDescription({
+ name: 'Avatar children',
+ required: true,
+ description: 'Avatar elements that form the overlapping row.',
+ }),
+ ).toBe('**Required:** Avatar elements that form the overlapping row.');
+ });
+
+ it('leaves an optional element description untouched', () => {
+ expect(
+ anatomyDescription({
+ name: 'Overflow indicator',
+ required: false,
+ description: 'A "+N" circle at the end showing hidden count.',
+ }),
+ ).toBe('A "+N" circle at the end showing hidden count.');
+ });
+
+ it('emits the lead-in alone when a required element has no description', () => {
+ expect(
+ anatomyDescription({name: 'Photo', required: true, description: ''}),
+ ).toBe('**Required:**');
+ });
+
+ it('keeps the lead-in adjacent to descriptions authored across lines', () => {
+ // Doc files write descriptions as wrapped template literals, so the raw
+ // string can lead with a newline and indentation.
+ expect(
+ anatomyDescription({
+ name: 'Status dot',
+ required: true,
+ description: '\n A small indicator in the bottom-right corner.\n',
+ }),
+ ).toBe('**Required:** A small indicator in the bottom-right corner.');
+ });
+});
diff --git a/apps/docsite/src/__tests__/component-detail-wiring.test.ts b/apps/docsite/src/__tests__/component-detail-wiring.test.ts
new file mode 100644
index 0000000000..58113ff8ce
--- /dev/null
+++ b/apps/docsite/src/__tests__/component-detail-wiring.test.ts
@@ -0,0 +1,115 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Wiring tests for the component detail page.
+ *
+ * The `component-detail/` directory holds the internal building blocks of a
+ * single page. Unlike `app/`, it contains no Next.js route entry points and no
+ * script-consumed modules, so every module in it must be reachable from an
+ * import — a renderer that nothing imports is dead code, and the data it was
+ * written to display silently never reaches the page.
+ *
+ * Run: pnpm -F @astryxdesign/docsite test
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {fileURLToPath} from 'node:url';
+import {describe, it, expect} from 'vitest';
+import {components} from '../generated/componentRegistry';
+
+const SRC_DIR = path.resolve(
+ path.dirname(fileURLToPath(import.meta.url)),
+ '..',
+);
+const DETAIL_DIR = path.join(SRC_DIR, 'components/component-detail');
+const EXTENSIONS = ['.ts', '.tsx'];
+
+function walk(dir: string, out: string[] = []): string[] {
+ for (const entry of fs.readdirSync(dir, {withFileTypes: true})) {
+ const full = path.join(dir, entry.name);
+ if (entry.isDirectory()) {
+ walk(full, out);
+ } else if (EXTENSIONS.includes(path.extname(entry.name))) {
+ out.push(full);
+ }
+ }
+ return out;
+}
+
+/**
+ * Resolve a relative import specifier the way the bundler does, so a match is
+ * an actual module reference rather than a name that happens to appear in the
+ * source. Package specifiers are skipped — `@astryxdesign/core/Section` must
+ * not count as an import of a local `Section.tsx`.
+ */
+function resolveRelative(fromFile: string, specifier: string): string | null {
+ if (!specifier.startsWith('.')) {
+ return null;
+ }
+ const base = path.resolve(path.dirname(fromFile), specifier);
+ const candidates = [
+ base,
+ ...EXTENSIONS.map(ext => base + ext),
+ ...EXTENSIONS.map(ext => path.join(base, `index${ext}`)),
+ ];
+ for (const candidate of candidates) {
+ if (fs.existsSync(candidate) && fs.statSync(candidate).isFile()) {
+ return candidate;
+ }
+ }
+ return null;
+}
+
+const SPECIFIER_RE = /(?:from\s*|import\(\s*|require\(\s*)['"]([^'"]+)['"]/g;
+
+function collectImportedFiles(files: string[]): Set<string> {
+ const imported = new Set<string>();
+ for (const file of files) {
+ const source = fs.readFileSync(file, 'utf8');
+ for (const match of source.matchAll(SPECIFIER_RE)) {
+ const resolved = resolveRelative(file, match[1]);
+ if (resolved !== null) {
+ imported.add(resolved);
+ }
+ }
+ }
+ return imported;
+}
+
+describe('component detail wiring', () => {
+ it('imports every module in component-detail/ from somewhere', () => {
+ const detailModules = walk(DETAIL_DIR).filter(
+ file => !file.includes('.test.'),
+ );
+ // Guard against a vacuous pass if the directory is ever moved or renamed.
+ expect(detailModules.length).toBeGreaterThan(5);
+
+ const imported = collectImportedFiles(walk(SRC_DIR));
+ const orphans = detailModules
+ .filter(file => !imported.has(file))
+ .map(file => path.relative(SRC_DIR, file))
+ .sort();
+
+ expect(orphans).toEqual([]);
+ });
+
+ it('carries anatomy data for components that author it', () => {
+ const withAnatomy = Object.values(components)
+ .flat()
+ .filter(entry => (entry.usage?.anatomy?.length ?? 0) > 0);
+
+ // The renderer is only worth wiring if the generated registry actually
+ // carries the data; this fails if generate-data.mjs ever drops `anatomy`
+ // from the `usage` block it passes through.
+ expect(withAnatomy.length).toBeGreaterThan(0);
+
+ for (const entry of withAnatomy) {
+ for (const element of entry.usage!.anatomy!) {
+ expect(typeof element.name).toBe('string');
+ expect(element.name.length).toBeGreaterThan(0);
+ expect(typeof element.description).toBe('string');
+ }
+ }
+ });
+});
diff --git a/apps/docsite/src/components/component-detail/Anatomy.tsx b/apps/docsite/src/components/component-detail/Anatomy.tsx
index 9715967bbf..28902ca65e 100644
--- a/apps/docsite/src/components/component-detail/Anatomy.tsx
+++ b/apps/docsite/src/components/component-detail/Anatomy.tsx
@@ -6,9 +6,10 @@ import {Heading} from '@astryxdesign/core/Text';
import {VStack} from '@astryxdesign/core/Layout';
import {Section} from '@astryxdesign/core/Section';
import {Table, pixel} from '@astryxdesign/core/Table';
-import {Badge} from '@astryxdesign/core/Badge';
+import {Card} from '@astryxdesign/core/Card';
import type {AnatomyElement} from '../../generated/componentRegistry';
import {MarkdownText} from '../MarkdownText';
+import {anatomyDescription} from './anatomyHelpers';
interface AnatomyProps {
elements: AnatomyElement[];
@@ -21,44 +22,40 @@ export function Anatomy({elements}: AnatomyProps) {
const data = elements.map(el => ({
name: el.name as unknown,
- required: el.required as unknown,
- description: el.description as unknown,
+ description: anatomyDescription(el) as unknown,
})) as Record<string, unknown>[];
return (
<Section>
- <VStack gap={2}>
- <Heading level={3}>Anatomy</Heading>
- <Table
- data={data}
- columns={[
- {
- key: 'name',
- header: 'Element',
- width: pixel(140),
- },
- {
- key: 'required',
- header: '',
- width: pixel(80),
- renderCell: (item: Record<string, unknown>) =>
- item.required === true ? (
- <Badge label="required" variant="info" />
- ) : null,
- },
- {
- key: 'description',
- header: 'Description',
- renderCell: (item: Record<string, unknown>) => (
- <MarkdownText type="body">
- {item.description as string}
- </MarkdownText>
- ),
- },
- ]}
- density="spacious"
- dividers="rows"
- />
+ <VStack gap={4}>
+ <Heading level={2} type="display-3">
+ Anatomy
+ </Heading>
+ {/* Carded like the other tables on this page (BestPracticesBlock, the
+ /docs TableBlock) rather than sitting bare on the page background. */}
+ <Card variant="default">
+ <Table
+ data={data}
+ columns={[
+ {
+ key: 'name',
+ header: 'Element',
+ width: pixel(140),
+ },
+ {
+ key: 'description',
+ header: 'Description',
+ renderCell: (item: Record<string, unknown>) => (
+ <MarkdownText type="body">
+ {item.description as string}
+ </MarkdownText>
+ ),
+ },
+ ]}
+ density="spacious"
+ dividers="rows"
+ />
+ </Card>
</VStack>
</Section>
);
diff --git a/apps/docsite/src/components/component-detail/ComponentDetailClient.tsx b/apps/docsite/src/components/component-detail/ComponentDetailClient.tsx
index e8609ce571..ffb4004403 100644
--- a/apps/docsite/src/components/component-detail/ComponentDetailClient.tsx
+++ b/apps/docsite/src/components/component-detail/ComponentDetailClient.tsx
@@ -15,6 +15,7 @@ import {CodeExampleBlock} from '../CodeExampleBlock';
import {TabList, Tab} from '@astryxdesign/core/TabList';
import {ShowcasePreview} from './ShowcasePreview';
import {ComponentPreviewTheme} from './ComponentPreviewTheme';
+import {Anatomy} from './Anatomy';
import {BestPractices} from './BestPractices';
import {Theming} from './Theming';
import {HookSignature} from './HookSignature';
@@ -107,6 +108,12 @@ function OverviewContent({
hasCopyButton
/>
+ {/* Anatomy before best practices, matching the CLI's section order
+ in clients/cli/lib/component-format.mjs. */}
+ {comp.usage.anatomy && comp.usage.anatomy.length > 0 && (
+ <Anatomy elements={comp.usage.anatomy} />
+ )}
+
{comp.usage.bestPractices && comp.usage.bestPractices.length > 0 && (
<BestPractices practices={comp.usage.bestPractices} />
)}
diff --git a/apps/docsite/src/components/component-detail/anatomyHelpers.ts b/apps/docsite/src/components/component-detail/anatomyHelpers.ts
new file mode 100644
index 0000000000..67c76a80af
--- /dev/null
+++ b/apps/docsite/src/components/component-detail/anatomyHelpers.ts
@@ -0,0 +1,34 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file anatomyHelpers.ts
+ * @input A component's `usage.anatomy` elements (name, required, description).
+ * @output Pure helpers that shape anatomy data for the component-detail Anatomy
+ * section — currently folding the `required` flag into the description as a
+ * bold lead-in.
+ * @position Consumed by Anatomy.tsx; kept separate so the logic is unit-testable
+ * without rendering React.
+ *
+ * The lead-in mirrors how the CLI marks its guidance rows (`**Do:**` /
+ * `**Don't:**` in packages/cli/clients/cli/lib/component-format.mjs), so a
+ * required part reads the same way in both surfaces.
+ */
+
+import type {AnatomyElement} from '../../generated/componentRegistry';
+
+const REQUIRED_LEAD_IN = '**Required:**';
+
+/**
+ * The description to render for one anatomy element. Required elements get a
+ * bold `Required:` lead-in rather than a separate badge column, keeping the flag
+ * inline with the prose it qualifies.
+ */
+export function anatomyDescription(element: AnatomyElement): string {
+ const description = element.description.trim();
+
+ if (!element.required) {
+ return description;
+ }
+
+ return description ? `${REQUIRED_LEAD_IN} ${description}` : REQUIRED_LEAD_IN;
+}