Skip to main content

Expandable Sidebar Nesting Design

Overview​

Support nested sidebar items so a component family (e.g., Input → Input text, Input number, Input date, Text area) renders as an expandable category in the sidebar with one parent and N children. The same mechanism applies generically to any folder-based doc dir the doc-tabs-plugin already scans (components, patterns, foundations, and any future top-level dir).

The parent slot is a pure category — no own page. Clicking the parent label routes to the first child by default. Children are full leaf components with the existing tab structure.

Goals​

  • Any folder-based doc dir can contain nested parent → child structures of arbitrary depth (2 levels expected in practice)
  • Detection of "parent" vs "leaf" is fully filesystem-driven; no global registry, no manual list
  • Parent declaration uses Docusaurus' native _category_.json so the autogenerated sidebar handles rendering with zero changes to sidebars.ts
  • Bare parent URLs (e.g., /docs/components/input) redirect to the first child
  • Existing flat components migrate cleanly; old URLs redirect to nested URLs forever
  • Designers' authoring workflow continues to "just work" via updated slash commands using a single Parent/Child path syntax

Non-Goals​

  • Renaming during migration is supported but treated as the rare case (same-name nesting is the default)
  • No support for category descriptions or generated-index landing pages on parents (parents are pure routing categories)
  • No automatic detection of "this should be a family" — designers explicitly opt in via _category_.json
  • No changes to the ComponentPageTOC, ComponentDocTabs, or MDXComponents registration (rendering of leaves is unchanged)
  • No support for foundation/pattern-only nesting that doesn't follow the same convention (the rules are uniform across doc types)

Section 1: Filesystem Layout & Detection Rule​

Layout​

Leaf component (today's pattern, unchanged):

docs/components/avatar/
├── index.md ← frontmatter: component_page: true
├── overview.md
├── design.md
├── code.md
├── accessibility.md
├── content.md ← optional
└── status.md

Parent + nested children (new):

docs/components/input/
├── _category_.json ← declares parent
├── input-text/ ← child = full leaf component structure
│ ├── index.md
│ ├── overview.md
│ └── ...
├── input-number/
├── input-date/
└── text-area/

Detection rule​

Per folder, the plugin checks two files:

Has index.md?Has _category_.json?Treated asNotes
✅❌LeafExisting pattern. Folder is a doc page with tabs.
❌✅ParentSidebar category. No own page. Routes to first child.
❌❌IgnoredEmpty container — skipped.
✅✅Warning + treated as leafAmbiguous; build warning emitted.

Filesystem is the single source of truth. No flags, no central list.

Applies to​

Every directory in DOC_DIRS in plugins/doc-tabs-plugin.js. The detection rule and recursion logic are doc-type-agnostic.


Section 2: _category_.json Schema and Behavior​

Canonical example​

docs/components/input/_category_.json:

{
"label": "Input",
"position": 5,
"link": {
"type": "doc",
"id": "components/input/input-text"
},
"collapsed": true
}

Field rules​

FieldRequiredConvention
labelyesDisplay name with proper casing (e.g., Input, Bulk action). Without it, Docusaurus falls back to the folder name.
positionyesNumeric sidebar order, mirroring sidebar_position in leaf frontmatter.
link.typeyesAlways "doc" (parent routes to first child).
link.idyesFull doc ID of the first child. Format: <doc-dir>/<...kebab-segments> — drop docs/ prefix, drop .md, drop trailing /index, use forward slashes, no leading slash. Example: components/input/input-text.
collapsednoDefault true. Docusaurus auto-expands the section containing the active page, so true keeps inactive families tidy.
collapsiblenoOmit (default true).
classNamenoOmit unless a visual marker is later added for parents.

Doc ID derivation​

For a child at docs/components/input/input-text/index.md, the doc ID is components/input/input-text.

URL behavior​

  • Sidebar click on parent label → navigates to /docs/<link.id> (handled natively by Docusaurus).
  • Direct visit to bare parent URL (e.g., /docs/components/input/) → 404 by default. Resolved by the redirect strategy in Section 5.

Section 3: Plugin and Layout Runtime Changes​

Files affected​

FileType of change
plugins/doc-tabs-plugin.jsRecursive walker, new manifest keying, new validation, new redirect emission
src/components/AutoDocTabs/index.tsxwebpackInclude regex update for nested paths
src/theme/DocItem/Layout/index.tsxSlug derivation handles full sub-path
docusaurus.config.tsRegister @docusaurus/plugin-client-redirects reading the plugin's redirect output
sidebars.tsNo change — Docusaurus' autogenerated sidebar handles _category_.json natively

3.1 Recursive walker​

scanDocTabs replaces its single-level for loop with a recursive walker. Pseudocode:

function walk(currentDir, relativeSlug, dir, type, manifest, categories, warnings) {
const indexFile = path.join(currentDir, 'index.md');
const categoryFile = path.join(currentDir, '_category_.json');
const hasIndex = fs.existsSync(indexFile);
const hasCategory = fs.existsSync(categoryFile);

if (hasIndex && hasCategory) {
warnings.push(`${currentDir}: both index.md and _category_.json present — treating as leaf`);
}

if (hasIndex) {
const tabs = TAB_NAMES.filter(t => fs.existsSync(path.join(currentDir, `${t}.md`)));
if (tabs.length > 0) {
manifest[relativeSlug] = { tabs, path: `docs/${dir}/${relativeSlug}`, type };
}
return;
}

if (hasCategory) {
const category = JSON.parse(fs.readFileSync(categoryFile, 'utf8'));
categories.push({ slug: relativeSlug, dir, type, category, path: currentDir });

const children = fs.readdirSync(currentDir, { withFileTypes: true });
for (const child of children) {
if (!child.isDirectory()) continue;
walk(
path.join(currentDir, child.name),
`${relativeSlug}/${child.name}`,
dir,
type,
manifest,
categories,
warnings
);
}
return;
}

// No marker — folder skipped.
}

The top-level scan iterates each {dir, type} in DOC_DIRS. For each direct subfolder of docs/<dir>/, it invokes walk(<subfolderPath>, <subfolderName>, dir, type, manifest, categories, warnings). The doc-type root itself is never passed to walk (it never carries a _category_.json or index.md). relativeSlug starts as the immediate child folder name and grows by one segment per recursion level.

3.2 Manifest keying​

Today: manifest['avatar'], manifest['datepicker']. After: manifest['avatar'], manifest['input/input-text'], manifest['input/input-number'].

Keys are slug paths — same value used as the dynamic-import path suffix in AutoDocTabs.

3.3 AutoDocTabs regex update​

Current webpackInclude (in createComponentLazyTab):

/* webpackInclude: /docs\/components\/[^/]+\/(overview|design|code|accessibility|content|status)\.md$/ */

Updated:

/* webpackInclude: /docs\/components\/(?:[^/]+\/)+(overview|design|code|accessibility|content|status)\.md$/ */

The (?:[^/]+\/)+ group permits any number of path segments. Same change applied to the pattern and foundation variants (createPatternLazyTab, createFoundationLazyTab).

The template-string itself (`@site/docs/components/${slug}/${tab}.md`) does not change — slug may now contain a slash.

3.4 Slug derivation in layout​

Current logic (DocItem/Layout/index.tsx):

const idParts = metadata.id?.split('/') ?? [];
const lastPart = idParts[idParts.length - 1];
const slug = lastPart === 'index' ? (idParts[idParts.length - 2] ?? '') : lastPart ?? '';

Replace with:

const parts = metadata.id?.split('/') ?? [];
const withoutDocType = parts.slice(1);
const withoutIndex = withoutDocType[withoutDocType.length - 1] === 'index'
? withoutDocType.slice(0, -1)
: withoutDocType;
const slug = withoutIndex.join('/');

Result: "avatar" for flat leaves; "input/input-text" for nested. The hasAutoTabs = isComponentPage && !!pluginData?.manifest?.[slug]?.tabs?.length lookup works unchanged because keys now also contain slashes.

3.5 Plugin output (globalData)​

setGlobalData({ manifest, redirects }) where:

  • manifest — same shape as today, with slash-bearing keys for nested
  • redirects — array of { from, to } entries derived from categories (see Section 5)

AutoDocTabs consumes only manifest (unchanged consumption shape).


Section 4: Slash Command Updates​

All three commands accept the same Parent/Child path syntax. One mental model.

4.1 /generate-component-doc <Path> [FigmaURL]​

Skill file: .claude/commands/generate-component-doc.md

Path forms accepted:

  • Avatar — flat (existing behavior)
  • Input/InputText — nested

Updated logic:

  1. Parse Path. Split on /. 1 segment → flat creation (existing flow). 2+ segments → nested creation; last = leaf, rest = parent path.
  2. (nested only) Resolve parent folder docs/<dir>/<parent-kebab>/:
    • Doesn't exist → ask: "Create new '[Parent]' parent category? (Y/n)". On Y, create _category_.json with link.id pointing to this child.
    • Exists with _category_.json → continue.
    • Exists with index.md → ERROR. Suggest /migrate-component-doc.
  3. Create leaf folder docs/<dir>/<parent-kebab>/<child-kebab>/ with the standard scaffold (index.md + 5 tab files).
  4. Run Figma scan + Storybook prompt as today.
  5. Update _category_.json only if this is the first child created and link.id is missing.
  6. Print summary: files created, folder path, sidebar position, next steps.

Bug fix folded in: the existing skill checks docs/components/<kebab>.md (single-file convention). Update to check folder + index.md to match the current folder-based pattern.

4.2 /migrate-component-doc <flat> <parent-or-target> (new)​

Skill file: .claude/commands/migrate-component-doc.md (new file, modeled on generate-component-doc.md)

Two forms:

/migrate-component-doc datepicker Input
→ docs/components/datepicker/ → docs/components/input/datepicker/

/migrate-component-doc datepicker Input/input-date
→ docs/components/datepicker/ → docs/components/input/input-date/

Logic:

  1. Parse second arg. No slash → target is <parent>/<source-name>. Has slash → target is the literal path.
  2. Validate:
    • Source folder exists at docs/<dir>/<flat>/ and contains index.md.
    • Source has no nested children (it's a leaf, not already a parent).
    • Target path doesn't already exist.
    • Parent folder either doesn't exist (will be created) or already has _category_.json.
  3. Move with git history preserved: git mv docs/<dir>/<flat> docs/<dir>/<target-path>.
  4. Create or update parent _category_.json:
    • If parent doesn't exist → create with link.id pointing to migrated child.
    • If parent exists → leave _category_.json alone (don't change first child).
  5. Append redirect: /docs/<dir>/<flat> → /docs/<dir>/<target-path> to the redirects manifest the plugin reads.
  6. Grep the docs tree for hardcoded references and auto-replace with confirmation:
    • Markdown links: ](/docs/<dir>/<flat>)
    • RelatedComponents arrays: link: "/docs/<dir>/<flat>"
  7. Print summary: files moved, references updated (file:line list), redirect added.

4.3 /add-content-tab <Path> (existing, needs update)​

Skill file: .claude/commands/add-content-tab.md

Accept the same Path syntax:

  • alert → docs/components/alert/
  • Input/InputText → docs/components/input/input-text/

Resolution path becomes docs/<dir>/<...kebab-parts>/index.md. Template choice and file write are unchanged. Error message updated to mention nested paths.

4.4 Other doc-creation commands​

Same nesting updates apply to /generate-pattern-doc (file: .claude/commands/generate-pattern-doc.md) for consistency. If a /generate-foundation-doc is added later, follow the same pattern.


Section 5: URL & Redirect Strategy​

Two redirect sources​

  1. Parent-URL redirects (per _category_.json) — emitted by the plugin from the categories array during the walk. Format:
    { from: `/docs/${docTypeRoot}/${category.slug}`, to: `/docs/${category.link.id}` }
  2. Migration redirects (from old flat URLs to new nested URLs) — written by /migrate-component-doc to a persistent manifest file (e.g., docs/.redirects.json) the plugin reads at build time and merges with the plugin-emitted redirects.

Plugin client-redirects integration​

In docusaurus.config.ts:

plugins: [
// existing plugins
'./plugins/doc-tabs-plugin',
[
'@docusaurus/plugin-client-redirects',
{
createRedirects: () => {
// pull both sources: plugin globalData + persistent manifest
const fromPlugin = require('./.docusaurus/doc-tabs-plugin/redirects.json');
const fromManifest = require('./docs/.redirects.json');
return [...fromPlugin, ...fromManifest];
},
},
],
],

The exact wiring depends on whether globalData is reachable at config-evaluation time. If not, the plugin writes a sibling JSON file to .docusaurus/ during contentLoaded, and createRedirects reads from disk.

Lifecycle​

  • Adding a _category_.json → plugin emits a parent-URL redirect on next build.
  • Running /migrate-component-doc → appends to the persistent migration manifest.
  • Removing a parent (rare) → designer manually prunes from the manifest.

Section 6: Validation & Errors​

The plugin emits build-time warnings (not failures) for:

  1. A folder with both _category_.json and index.md — treated as leaf, ambiguity warning.
  2. A _category_.json whose link.type === 'doc' and link.id doesn't resolve to a known leaf in the manifest.
  3. A _category_.json whose link.id points outside the parent's subtree.
  4. A parent folder with zero leaf descendants (empty parent).

Warnings appear in the dev server log and in npm run build output. They do not block local development but indicate problems that should be fixed before merging.


Section 7: Testing Strategy​

Unit tests (Jest)​

In plugins/__tests__/doc-tabs-plugin.test.js (new file), with fixtures under plugins/__tests__/fixtures/:

  • scanDocTabs returns expected manifest for a fixture mixing flat and nested folders
  • Detects ambiguous folder (both index.md and _category_.json)
  • Detects empty parent (no leaf descendants)
  • Generates correct redirect entries from _category_.json files
  • Manifest keys are correct slash-paths
  • Recursion handles depth ≥ 3 without crashing

Integration / smoke test​

A scripted build against a fixture (or a flag in CI) that:

  • Runs npm run build
  • Verifies all child URLs resolve to 200
  • Verifies parent URL redirects to first child URL
  • Verifies no broken-link warnings in build output

Manual verification checklist​

Before merging:

  • Sidebar renders nested family with parent collapsible
  • Clicking parent label routes to first child
  • Active child highlights correctly
  • Tabs render on a nested child page (Overview, Design, Code, Accessibility, Status, Content if present)
  • ComponentPageTOC works on a nested child
  • Bare parent URL redirects in production build
  • Migrated flat URL (e.g., /docs/components/datepicker) redirects to nested location

Section 8: Rollout & Migration Plan​

Phase 1 — Infrastructure (no content changes)​

  1. Update doc-tabs-plugin.js: recursion, manifest keying, validation, redirect emission.
  2. Update AutoDocTabs/index.tsx: regex change.
  3. Update DocItem/Layout/index.tsx: slug derivation.
  4. Install and wire @docusaurus/plugin-client-redirects in docusaurus.config.ts.
  5. Add unit tests + integration smoke test.
  6. Verify all existing flat components still render unchanged (regression check).

Ship Phase 1 alone — no nested families exist yet, so the only visible change is the new redirects plugin running with zero entries.

Phase 2 — Slash command updates​

  1. Update .claude/commands/generate-component-doc.md (path syntax + parent detection).
  2. Update .claude/commands/add-content-tab.md (path syntax).
  3. Update .claude/commands/generate-pattern-doc.md (path syntax + parent detection).
  4. Add .claude/commands/migrate-component-doc.md (new).

Ship Phase 2 alone — designers can now create nested families but no flat components have been migrated yet.

Phase 3 — First family creation​

Pick one family (Input is the canonical case from the Notion brief) and create it:

  1. Run /generate-component-doc Input/InputText to create the parent + first child.
  2. Add additional children (Input/InputNumber, Input/InputDate, Input/TextArea) as /generate-component-doc Input/InputNumber etc.
  3. Verify sidebar renders correctly, parent URL redirects, child pages render.

Phase 4 — Migration (optional, per family)​

For each existing flat component that should join a family:

  1. Run /migrate-component-doc datepicker Input.
  2. Review the diff (file moves + reference updates).
  3. Verify build passes with no warnings and the old URL redirects to the new one.
  4. Commit and merge.

Migration is opt-in per component. Components that don't fit a family stay flat indefinitely.

Rollback​

  • Phase 1: revert the three runtime files; remove the @docusaurus/plugin-client-redirects wiring. No content was changed.
  • Phase 2: revert the four skill files. Designers fall back to the previous (flat-only) authoring flow.
  • Phase 3: delete the family's parent folder (docs/components/input/). All content was new.
  • Phase 4: git revert the migration commit. The redirect entry can stay (harmless if both URLs point to the same content — but the URLs will diverge again on revert, so prune the redirect manifest entry too).

Open Questions​

None at design close. All structural and behavioral decisions are settled. Implementation-level details (exact regex shape, exact redirect file format, test fixture layout) are deferred to the implementation plan.

References​