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_.jsonso the autogenerated sidebar handles rendering with zero changes tosidebars.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/Childpath 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-indexlanding 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, orMDXComponentsregistration (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 as | Notes |
|---|---|---|---|
| ✅ | ❌ | Leaf | Existing pattern. Folder is a doc page with tabs. |
| ❌ | ✅ | Parent | Sidebar category. No own page. Routes to first child. |
| ❌ | ❌ | Ignored | Empty container — skipped. |
| ✅ | ✅ | Warning + treated as leaf | Ambiguous; 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
| Field | Required | Convention |
|---|---|---|
label | yes | Display name with proper casing (e.g., Input, Bulk action). Without it, Docusaurus falls back to the folder name. |
position | yes | Numeric sidebar order, mirroring sidebar_position in leaf frontmatter. |
link.type | yes | Always "doc" (parent routes to first child). |
link.id | yes | Full 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. |
collapsed | no | Default true. Docusaurus auto-expands the section containing the active page, so true keeps inactive families tidy. |
collapsible | no | Omit (default true). |
className | no | Omit 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
| File | Type of change |
|---|---|
plugins/doc-tabs-plugin.js | Recursive walker, new manifest keying, new validation, new redirect emission |
src/components/AutoDocTabs/index.tsx | webpackInclude regex update for nested paths |
src/theme/DocItem/Layout/index.tsx | Slug derivation handles full sub-path |
docusaurus.config.ts | Register @docusaurus/plugin-client-redirects reading the plugin's redirect output |
sidebars.ts | No 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 nestedredirects— array of{ from, to }entries derived fromcategories(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:
- Parse Path. Split on
/. 1 segment → flat creation (existing flow). 2+ segments → nested creation; last = leaf, rest = parent path. - (nested only) Resolve parent folder
docs/<dir>/<parent-kebab>/:- Doesn't exist → ask: "Create new '[Parent]' parent category? (Y/n)". On Y, create
_category_.jsonwithlink.idpointing to this child. - Exists with
_category_.json→ continue. - Exists with
index.md→ ERROR. Suggest/migrate-component-doc.
- Doesn't exist → ask: "Create new '[Parent]' parent category? (Y/n)". On Y, create
- Create leaf folder
docs/<dir>/<parent-kebab>/<child-kebab>/with the standard scaffold (index.md + 5 tab files). - Run Figma scan + Storybook prompt as today.
- Update
_category_.jsononly if this is the first child created andlink.idis missing. - 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:
- Parse second arg. No slash → target is
<parent>/<source-name>. Has slash → target is the literal path. - Validate:
- Source folder exists at
docs/<dir>/<flat>/and containsindex.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.
- Source folder exists at
- Move with git history preserved:
git mv docs/<dir>/<flat> docs/<dir>/<target-path>. - Create or update parent
_category_.json:- If parent doesn't exist → create with
link.idpointing to migrated child. - If parent exists → leave
_category_.jsonalone (don't change first child).
- If parent doesn't exist → create with
- Append redirect:
/docs/<dir>/<flat>→/docs/<dir>/<target-path>to the redirects manifest the plugin reads. - Grep the docs tree for hardcoded references and auto-replace with confirmation:
- Markdown links:
](/docs/<dir>/<flat>) RelatedComponentsarrays:link: "/docs/<dir>/<flat>"
- Markdown links:
- 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
- Parent-URL redirects (per
_category_.json) — emitted by the plugin from thecategoriesarray during the walk. Format:{ from: `/docs/${docTypeRoot}/${category.slug}`, to: `/docs/${category.link.id}` } - Migration redirects (from old flat URLs to new nested URLs) — written by
/migrate-component-docto 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:
- A folder with both
_category_.jsonandindex.md— treated as leaf, ambiguity warning. - A
_category_.jsonwhoselink.type === 'doc'andlink.iddoesn't resolve to a known leaf in the manifest. - A
_category_.jsonwhoselink.idpoints outside the parent's subtree. - 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/:
scanDocTabsreturns expected manifest for a fixture mixing flat and nested folders- Detects ambiguous folder (both
index.mdand_category_.json) - Detects empty parent (no leaf descendants)
- Generates correct redirect entries from
_category_.jsonfiles - 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)
-
ComponentPageTOCworks 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)
- Update
doc-tabs-plugin.js: recursion, manifest keying, validation, redirect emission. - Update
AutoDocTabs/index.tsx: regex change. - Update
DocItem/Layout/index.tsx: slug derivation. - Install and wire
@docusaurus/plugin-client-redirectsindocusaurus.config.ts. - Add unit tests + integration smoke test.
- 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
- Update
.claude/commands/generate-component-doc.md(path syntax + parent detection). - Update
.claude/commands/add-content-tab.md(path syntax). - Update
.claude/commands/generate-pattern-doc.md(path syntax + parent detection). - 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:
- Run
/generate-component-doc Input/InputTextto create the parent + first child. - Add additional children (Input/InputNumber, Input/InputDate, Input/TextArea) as
/generate-component-doc Input/InputNumberetc. - 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:
- Run
/migrate-component-doc datepicker Input. - Review the diff (file moves + reference updates).
- Verify build passes with no warnings and the old URL redirects to the new one.
- 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-redirectswiring. 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 revertthe 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
- Notion: Structural Changes: Expandable sidebar item
- Existing spec:
docs/superpowers/specs/2026-04-05-pattern-page-infrastructure-design.md(related infrastructure) - Existing spec:
docs/superpowers/specs/2026-04-05-add-content-tab-design.md(related skill design) - Docusaurus docs:
_category_.jsonand autogenerated sidebar - Docusaurus docs:
@docusaurus/plugin-client-redirects