Skip to content

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

TypeScript

feat(docsite): nest docs pages under a parent page in the sidebar (#9786)

nynexman4464b75cbf56d714
diff --git a/apps/docsite/scripts/docs-pages.mjs b/apps/docsite/scripts/docs-pages.mjs
index 40488798ea..42ba58759f 100644
--- a/apps/docsite/scripts/docs-pages.mjs
+++ b/apps/docsite/scripts/docs-pages.mjs
@@ -11,8 +11,9 @@
* @input A docs reader with the CLI docs API's shape
* (`docs(topic, section, options)` from `@astryxdesign/cli/api`) and the
* flat topics the site already built.
- * @output Doc pages ({topic, title, description, category, sections}) and
- * redirects from each guide's own slug to its section on the full page.
+ * @output Doc pages ({topic, title, description, category, sections, and
+ * the sidebar `parent` of a page shown under another}) and redirects from
+ * each guide's own slug to its section on the full page.
* @position Used by generate-data.mjs; tested on its own with a fake reader.
*/
@@ -35,6 +36,28 @@ export const GUIDE_PAGE_NAMESPACES = new Set(['cli']);
*/
export const GUIDE_NAMESPACE_PAGES = new Map();
+/**
+ * Nested namespaces that have a page of their own instead of a part of their
+ * root namespace's page, by root. The root page leaves each one out, and each
+ * one is a full page at its route's slug, with `parent` set to the root page's
+ * slug so the sidebar shows it under that page.
+ * @type {Map<string, string[]>}
+ */
+export const NESTED_NAMESPACE_PAGES = new Map();
+
+/**
+ * Pages the sidebar shows under another page, child slug to parent slug. The
+ * child keeps its URL and moves into its parent's sidebar group. A nested
+ * namespace's page (NESTED_NAMESPACE_PAGES) has its root page as parent with
+ * no entry here.
+ * @type {Map<string, string>}
+ */
+export const SIDEBAR_PARENTS = new Map([
+ ['cli-experimental-icon-sets', 'icons'],
+ ['cli-experimental-icon-set-files', 'icons'],
+ ['styling', 'styling-overview'],
+]);
+
/**
* Older slugs of a root namespace's page, which redirect to it: global mode
* was `cli/global`, and before that the `cli/install-once` guide; the
@@ -285,6 +308,66 @@ export async function namespacePage(readDocs, route, options = {}) {
};
}
+/**
+ * The pages of a root namespace: its own page without its nested namespaces
+ * that have a page of their own, and one page for each of those, marked with
+ * the root page as its `parent`. A namespace with no guide below it has no
+ * page.
+ * @param {(topic?: string, section?: string, options?: object) => Promise<any>} readDocs
+ * @param {string} root
+ * @param {{aliases?: string[], nested?: string[]}} [options] older slugs of
+ * the root page, and the nested namespaces with a page of their own
+ * (NESTED_NAMESPACE_PAGES by default)
+ * @returns {Promise<{root: {page: object, redirects: Record<string, string>} | null, nested: Array<{page: object, redirects: Record<string, string>}>}>}
+ */
+export async function rootNamespacePages(readDocs, root, options = {}) {
+ const {
+ aliases = [],
+ nested: nestedRoutes = NESTED_NAMESPACE_PAGES.get(root) ?? [],
+ } = options;
+ const rootPage = await namespacePage(readDocs, root, {
+ aliases,
+ except: nestedRoutes,
+ });
+ const nested = [];
+ for (const route of nestedRoutes) {
+ const page = await namespacePage(readDocs, route, {slug: routeSlug(route)});
+ if (!page) continue;
+ if (rootPage) page.page.parent = rootPage.page.topic;
+ nested.push(page);
+ }
+ return {root: rootPage, nested};
+}
+
+/**
+ * Set the sidebar `parent` of each page that SIDEBAR_PARENTS names. Nesting is
+ * one level deep, so a parent cannot have a parent of its own.
+ * @param {Array<{topic: string, parent?: string}>} pages
+ * @param {Map<string, string>} [parents]
+ * @throws when an entry names a page that does not exist, or nests deeper
+ * than one level
+ */
+export function applySidebarParents(pages, parents = SIDEBAR_PARENTS) {
+ const bySlug = new Map(pages.map(page => [page.topic, page]));
+ for (const [child, parent] of parents) {
+ const page = bySlug.get(child);
+ if (!page || !bySlug.has(parent) || child === parent) {
+ throw new Error(
+ `docs: sidebar parent "${child}" -> "${parent}" needs two different pages.`,
+ );
+ }
+ page.parent = parent;
+ }
+ for (const page of pages) {
+ if (page.parent && bySlug.get(page.parent)?.parent) {
+ throw new Error(
+ `docs: "${page.topic}" is under "${page.parent}", which is itself under another page.`,
+ );
+ }
+ }
+ return pages;
+}
+
/**
* Apply MERGED_TOPICS and DATA_ONLY_TOPICS to the flat topics: a merged
* topic's sections move onto its host page and its slug redirects there; a
diff --git a/apps/docsite/scripts/generate-data.mjs b/apps/docsite/scripts/generate-data.mjs
index 7efec30c25..03fd380135 100644
--- a/apps/docsite/scripts/generate-data.mjs
+++ b/apps/docsite/scripts/generate-data.mjs
@@ -35,9 +35,11 @@ import {
GUIDE_NAMESPACE_PAGES,
GUIDE_PAGE_NAMESPACES,
ROOT_PAGE_ALIASES,
+ applySidebarParents,
movedGuideRedirects,
mergeFlatTopics,
namespacePage,
+ rootNamespacePages,
routeSlug,
sectionAnchors,
withCliCommands,
@@ -1854,9 +1856,11 @@ export const templateMetadataCount = ${templateMetadata.length};
* The docsite pages of the CLI's docs tree, read through the CLI's public docs
* API. Every root namespace is one full page at its own slug (docs-pages.mjs),
* so splitting a flat topic into a namespace keeps its URL, sidebar spot and
- * text; the guides under it redirect to their sections on that page. A root
- * namespace in GUIDE_PAGE_NAMESPACES shows the pages GUIDE_NAMESPACE_PAGES
- * lists, the same way one level down, and its other guides keep a page each.
+ * text; the guides under it redirect to their sections on that page. A nested
+ * namespace in NESTED_NAMESPACE_PAGES is a page of its own instead, under its
+ * root's page in the sidebar. A root namespace in GUIDE_PAGE_NAMESPACES shows
+ * the pages GUIDE_NAMESPACE_PAGES lists, the same way one level down, and its
+ * other guides keep a page each.
*/
async function docsTreePages() {
const pages = [];
@@ -1882,9 +1886,13 @@ async function docsTreePages() {
continue;
}
routes.push(...(await treeRoutes(root)));
- const full = await namespacePage(readDocs, root, {
+ const {root: full, nested} = await rootNamespacePages(readDocs, root, {
aliases: ROOT_PAGE_ALIASES.get(root) ?? [],
});
+ for (const page of nested) {
+ pages.push(page.page);
+ Object.assign(redirects, page.redirects);
+ }
if (!full) continue;
pages.push(full.page);
Object.assign(
@@ -2022,6 +2030,7 @@ async function generateDocsRegistry() {
}
docTopics.push(page);
}
+ applySidebarParents(docTopics);
const docsTreeRoutes = [...new Set(tree.routes)].sort();
const docRedirects = Object.fromEntries(
Object.entries({...merged.redirects, ...tree.redirects}).sort(([a], [b]) =>
@@ -2095,6 +2104,8 @@ export interface DocTopic {
description: string;
/** Navigation category: 'guide' | 'foundations' | null */
category: string | null;
+ /** Slug of the page the sidebar shows this page under, if any */
+ parent?: string;
/** Full doc sections with content blocks */
sections: DocSection[];
}
diff --git a/apps/docsite/src/__tests__/docs-nav.test.ts b/apps/docsite/src/__tests__/docs-nav.test.ts
index 394da70d69..828f93f31c 100644
--- a/apps/docsite/src/__tests__/docs-nav.test.ts
+++ b/apps/docsite/src/__tests__/docs-nav.test.ts
@@ -45,7 +45,12 @@ describe('docs nav model', () => {
})),
);
expect(nav.docTopics).toEqual(
- docTopics.map(({topic, title, category}) => ({topic, title, category})),
+ docTopics.map(({topic, title, category, parent}) => ({
+ topic,
+ title,
+ category,
+ parent,
+ })),
);
});
diff --git a/apps/docsite/src/__tests__/docs-pages.test.ts b/apps/docsite/src/__tests__/docs-pages.test.ts
index ea2f60359c..2c5e06188d 100644
--- a/apps/docsite/src/__tests__/docs-pages.test.ts
+++ b/apps/docsite/src/__tests__/docs-pages.test.ts
@@ -2,14 +2,21 @@
import {describe, expect, it} from 'vitest';
import {
+ SIDEBAR_PARENTS,
+ applySidebarParents,
mergeFlatTopics,
namespaceCategory,
namespacePage,
+ rootNamespacePages,
sectionAnchors,
withCliCommands,
} from '../../scripts/docs-pages.mjs';
import {buildOutline} from '../components/docs/docOutline';
-import {docTopics, type DocSection} from '../generated/docsRegistry';
+import {
+ docRedirects,
+ docTopics,
+ type DocSection,
+} from '../generated/docsRegistry';
const section = (title: string, text = `${title} text.`) => ({
title,
@@ -203,6 +210,158 @@ describe('a page for part of a namespace', () => {
});
});
+describe('a nested namespace with a page of its own', () => {
+ const guideNode = (route: string, title: string) => ({
+ route,
+ kind: 'generic',
+ title,
+ sections: [section(title)],
+ });
+ const extras = {
+ route: 'kit/extras',
+ kind: 'namespace',
+ title: 'Extras',
+ summary: 'Extra parts for the kit.',
+ content: [{type: 'prose', text: 'Extras fit every kit.'}],
+ slots: [
+ {
+ name: 'guides',
+ children: [guideNode('kit/extras/fit', 'Fit an extra')],
+ },
+ ],
+ };
+ const reader = async (
+ route?: string,
+ _section?: string,
+ options: {depth?: number | 'all'} = {},
+ ) => {
+ if (route === 'kit' && options.depth === 'all') {
+ return {
+ type: 'docs.node',
+ data: {
+ route: 'kit',
+ kind: 'namespace',
+ title: 'Kit',
+ summary: 'Build the kit.',
+ content: [],
+ slots: [
+ {
+ name: 'guides',
+ children: [guideNode('kit/start', 'Start'), extras],
+ },
+ ],
+ },
+ };
+ }
+ if (route === 'kit/extras' && options.depth === 'all') {
+ return {type: 'docs.node', data: extras};
+ }
+ return {type: 'docs.detail', data: {category: 'guide', sections: []}};
+ };
+ const pages = () =>
+ rootNamespacePages(reader, 'kit', {nested: ['kit/extras']});
+
+ it('leaves the nested namespace off its root page', async () => {
+ const {root} = await pages();
+ const page = root?.page as {
+ topic: string;
+ sections: Array<{title: string}>;
+ };
+ expect(page.topic).toBe('kit');
+ expect(page.sections.map(s => s.title)).toEqual(['Start']);
+ expect(root?.redirects).toEqual({'kit-start': '/docs/kit#start'});
+ });
+
+ it('gives it a full page at its slug, under its root page', async () => {
+ const {nested} = await pages();
+ expect(nested).toHaveLength(1);
+ const [extrasPage] = nested;
+ expect(extrasPage.page).toMatchObject({
+ topic: 'kit-extras',
+ title: 'Extras',
+ description: 'Extra parts for the kit.',
+ category: 'guide',
+ parent: 'kit',
+ });
+ const page = extrasPage.page as {sections: Array<{title: string}>};
+ expect(page.sections.map(s => s.title)).toEqual([
+ 'Overview',
+ 'Fit an extra',
+ ]);
+ expect(extrasPage.redirects).toEqual({
+ 'kit-extras-fit': '/docs/kit-extras#fit-an-extra',
+ });
+ });
+
+ it('keeps a root namespace with no nested page to one page', async () => {
+ const {root, nested} = await rootNamespacePages(
+ splitReader([
+ {
+ route: 'widgets/basics',
+ title: 'Basics',
+ category: 'foundations',
+ sections: widgetsBefore.sections,
+ },
+ ]),
+ 'widgets',
+ );
+ expect(root?.page).toEqual(widgetsBefore);
+ expect(nested).toEqual([]);
+ });
+});
+
+describe('sidebar parents', () => {
+ const pageAt = (topic: string, parent?: string) => ({
+ topic,
+ ...(parent ? {parent} : {}),
+ });
+
+ it('puts each named page under its parent and leaves the rest alone', () => {
+ const pages = applySidebarParents(
+ [pageAt('icons'), pageAt('icon-files'), pageAt('kit-extras', 'kit')],
+ new Map([['icon-files', 'icons']]),
+ );
+ expect(pages).toEqual([
+ pageAt('icons'),
+ pageAt('icon-files', 'icons'),
+ pageAt('kit-extras', 'kit'),
+ ]);
+ });
+
+ it('fails the build on a missing page, a page under itself, or a second level', () => {
+ expect(() =>
+ applySidebarParents([pageAt('icons')], new Map([['gone', 'icons']])),
+ ).toThrow(/gone/);
+ expect(() =>
+ applySidebarParents([pageAt('icons')], new Map([['icons', 'gone']])),
+ ).toThrow(/gone/);
+ expect(() =>
+ applySidebarParents([pageAt('icons')], new Map([['icons', 'icons']])),
+ ).toThrow(/two different pages/);
+ expect(() =>
+ applySidebarParents(
+ [pageAt('a'), pageAt('b', 'a'), pageAt('c')],
+ new Map([['c', 'b']]),
+ ),
+ ).toThrow(/itself under another page/);
+ });
+
+ it('places the site pages it names, at unchanged URLs', () => {
+ for (const [child, parent] of SIDEBAR_PARENTS) {
+ expect(docTopics.find(topic => topic.topic === child)?.parent).toBe(
+ parent,
+ );
+ expect(docTopics.some(topic => topic.topic === parent)).toBe(true);
+ expect(docRedirects).not.toHaveProperty(child);
+ }
+ expect(SIDEBAR_PARENTS.get('cli-experimental-icon-sets')).toBe('icons');
+ expect(SIDEBAR_PARENTS.get('cli-experimental-icon-set-files')).toBe(
+ 'icons',
+ );
+ expect(SIDEBAR_PARENTS.get('styling')).toBe('styling-overview');
+ });
+});
+
describe('namespaceCategory', () => {
it('prefers the namespace, then foundations only when every guide is', () => {
expect(namespaceCategory('guide', ['foundations'])).toBe('guide');
diff --git a/apps/docsite/src/__tests__/docs-sidebar-data.test.ts b/apps/docsite/src/__tests__/docs-sidebar-data.test.ts
new file mode 100644
index 0000000000..0fbe356803
--- /dev/null
+++ b/apps/docsite/src/__tests__/docs-sidebar-data.test.ts
@@ -0,0 +1,97 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file The Guide and Foundations groups of the docs sidebar: each page in its
+ * group's order, with a page that names a parent nested under that parent's
+ * item, in the parent's group.
+ */
+
+import {describe, expect, it} from 'vitest';
+import {
+ docsSidebarGroups,
+ type DocsSidebarItem,
+} from '../components/docsSidebarData';
+import {docTopics, type DocTopic} from '../generated/docsRegistry';
+
+const page = (
+ topic: string,
+ title: string,
+ extra: Partial<DocTopic> = {},
+): DocTopic => ({
+ topic,
+ title,
+ description: '',
+ category: 'guide',
+ sections: [],
+ ...extra,
+});
+
+const shape = (items: DocsSidebarItem[]) =>
+ items.map(({page: p, children}) => [p.topic, children.map(c => c.topic)]);
+
+describe('docs sidebar groups', () => {
+ it('nests a page under its parent and keeps the rest flat, in group order', () => {
+ const groups = docsSidebarGroups([
+ page('migration', 'Migration'),
+ page('kit-extras', 'Extras', {parent: 'kit'}),
+ page('kit', 'Kit'),
+ page('getting-started', 'Getting Started'),
+ page('color', 'Color', {category: 'foundations'}),
+ page('tokens', 'Tokens', {category: 'foundations'}),
+ ]);
+ expect(shape(groups.guide)).toEqual([
+ ['kit', ['kit-extras']],
+ ['migration', []],
+ ]);
+ expect(shape(groups.foundations)).toEqual([
+ ['tokens', []],
+ ['color', []],
+ ]);
+ });
+
+ it("moves a page into its parent's group", () => {
+ const groups = docsSidebarGroups([
+ page('icon-files', 'Icon files', {parent: 'icons'}),
+ page('layout', 'Layout'),
+ page('icons', 'Icons', {category: 'foundations'}),
+ ]);
+ expect(shape(groups.guide)).toEqual([['layout', []]]);
+ expect(shape(groups.foundations)).toEqual([['icons', ['icon-files']]]);
+ });
+
+ it('keeps a page at the top of its own group when its parent is not in the sidebar, or is nested', () => {
+ const groups = docsSidebarGroups([
+ page('orphan', 'Orphan', {parent: 'missing'}),
+ page('start', 'Start', {parent: 'getting-started'}),
+ page('getting-started', 'Getting Started'),
+ page('a', 'A'),
+ page('b', 'B', {parent: 'a'}),
+ page('c', 'C', {parent: 'b'}),
+ ]);
+ expect(shape(groups.guide)).toEqual([
+ ['a', ['b']],
+ ['c', []],
+ ['orphan', []],
+ ['start', []],
+ ]);
+ });
+
+ it('shows the site pages under their parents', () => {
+ const groups = docsSidebarGroups(docTopics);
+ const childrenOf = (items: DocsSidebarItem[], topic: string) =>
+ items
+ .find(({page: p}) => p.topic === topic)
+ ?.children.map(c => [c.topic, c.title]);
+ expect(childrenOf(groups.foundations, 'icons')).toEqual([
+ ['cli-experimental-icon-set-files', 'Icon set files'],
+ ['cli-experimental-icon-sets', 'Icon sets'],
+ ]);
+ expect(childrenOf(groups.guide, 'styling-overview')).toEqual([
+ ['styling', 'Styling components'],
+ ]);
+ const topLevel = groups.guide.map(({page: p}) => p.topic);
+ expect(topLevel).not.toContain('styling');
+ expect(topLevel).not.toContain('cli-experimental-icon-set-files');
+ expect(topLevel).not.toContain('cli-experimental-icon-sets');
+ });
+});
diff --git a/apps/docsite/src/__tests__/docs-sidebar-items.test.tsx b/apps/docsite/src/__tests__/docs-sidebar-items.test.tsx
new file mode 100644
index 0000000000..1e05069803
--- /dev/null
+++ b/apps/docsite/src/__tests__/docs-sidebar-items.test.tsx
@@ -0,0 +1,81 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+// @vitest-environment jsdom
+
+/**
+ * @file A parent page's sidebar entry opens when the reader reaches one of its
+ * pages without the sidebar remounting, as a link or site search does, and
+ * the reader can still collapse it there.
+ */
+
+import '@testing-library/jest-dom/vitest';
+import {cleanup, fireEvent, render, screen} from '@testing-library/react';
+import {afterEach, describe, expect, it} from 'vitest';
+import {DocsSidebarItems} from '../components/DocsSidebarItems';
+import type {DocsSidebarItem} from '../components/docsSidebarData';
+import type {DocTopic} from '../generated/docsRegistry';
+
+const page = (topic: string, title: string): DocTopic => ({
+ topic,
+ title,
+ description: '',
+ category: 'guide',
+ sections: [],
+});
+
+const items: DocsSidebarItem[] = [
+ {
+ page: page('styling-overview', 'Styling overview'),
+ children: [
+ page('styling', 'Styling components'),
+ page('styling-themes', 'Styling themes'),
+ ],
+ },
+];
+
+const childName = 'Styling components';
+const parentToggle = () =>
+ screen.getByRole('button', {name: /^(Collapse|Expand) Styling overview$/});
+
+afterEach(cleanup);
+
+describe('docs sidebar items', () => {
+ it('opens the parent entry and marks the child current after a move from the parent page', () => {
+ const {rerender} = render(
+ <DocsSidebarItems items={items} pathname="/docs/styling-overview" />,
+ );
+ expect(screen.queryByRole('link', {name: childName})).toBeNull();
+
+ rerender(<DocsSidebarItems items={items} pathname="/docs/styling" />);
+ expect(screen.getByRole('link', {name: childName})).toHaveAttribute(
+ 'aria-current',
+ 'page',
+ );
+ });
+
+ it('collapses the parent entry on a child page when the reader presses its toggle', () => {
+ render(<DocsSidebarItems items={items} pathname="/docs/styling" />);
+ expect(parentToggle()).toHaveAttribute('aria-expanded', 'true');
+
+ fireEvent.click(parentToggle());
+ expect(parentToggle()).toHaveAttribute('aria-expanded', 'false');
+ expect(screen.queryByRole('link', {name: childName})).toBeNull();
+ });
+
+ it('opens the collapsed parent entry again on a move to another of its pages', () => {
+ const {rerender} = render(
+ <DocsSidebarItems items={items} pathname="/docs/styling" />,
+ );
+ fireEvent.click(parentToggle());
+ expect(parentToggle()).toHaveAttribute('aria-expanded', 'false');
+
+ rerender(
+ <DocsSidebarItems items={items} pathname="/docs/styling-themes" />,
+ );
+ expect(parentToggle()).toHaveAttribute('aria-expanded', 'true');
+ expect(screen.getByRole('link', {name: 'Styling themes'})).toHaveAttribute(
+ 'aria-current',
+ 'page',
+ );
+ });
+});
diff --git a/apps/docsite/src/__tests__/route-resolution.test.ts b/apps/docsite/src/__tests__/route-resolution.test.ts
index 00e320d698..e3d2e3ba61 100644
--- a/apps/docsite/src/__tests__/route-resolution.test.ts
+++ b/apps/docsite/src/__tests__/route-resolution.test.ts
@@ -9,6 +9,7 @@ import {
import {packages} from '../generated/packageRegistry';
import {linkifyCode} from '../components/codeLinkifiers';
import {buildOutline} from '../components/docs/docOutline';
+import {docsSidebarGroups} from '../components/docsSidebarData';
/**
* Every topic page the site had before the CLI's docs were split into
@@ -95,8 +96,11 @@ describe('route resolution', () => {
// `use-integrations` is the guide for apps that install one;
// `cli-experimental-render-pages` is the experimental render guide;
// `calendars` is the calendar systems page.
- const sidebarGuides = docTopics
- .filter(d => d.category === 'guide' && d.topic !== 'getting-started')
+ // `styling` shows under `styling-overview`, and
+ // `cli-experimental-icon-sets` and `cli-experimental-icon-set-files`
+ // under Icons in Foundations.
+ const sidebarGuides = docsSidebarGroups(docTopics)
+ .guide.flatMap(({page, children}) => [page, ...children])
.map(d => d.topic)
.sort();
expect(sidebarGuides).toEqual(
@@ -105,8 +109,6 @@ describe('route resolution', () => {
'browser-support',
'calendars',
'cli-component-lookups',
- 'cli-experimental-icon-set-files',
- 'cli-experimental-icon-sets',
'cli-experimental-render-pages',
'cli-host-entry',
'global',
diff --git a/apps/docsite/src/components/DocsShell.tsx b/apps/docsite/src/components/DocsShell.tsx
index 09ffcade59..148ac894e9 100644
--- a/apps/docsite/src/components/DocsShell.tsx
+++ b/apps/docsite/src/components/DocsShell.tsx
@@ -25,8 +25,9 @@ import type {
DocsNavEntry,
DocsNavItem,
DocsNavPackage,
- DocsNavTopic,
} from './docsNav';
+import {docsSidebarGroups} from './docsSidebarData';
+import {DocsSidebarItems} from './DocsSidebarItems';
interface DocsShellProps {
children: React.ReactNode;
@@ -51,17 +52,6 @@ function CanaryCategoryMarker() {
);
}
-/** Foundations: tokens first, then alphabetical */
-const foundationsSort = (a: DocsNavTopic, b: DocsNavTopic) => {
- if (a.topic === 'tokens') {
- return -1;
- }
- if (b.topic === 'tokens') {
- return 1;
- }
- return a.title.localeCompare(b.title);
-};
-
// ── Shell ──────────────────────────────────────────────────────────────
export function DocsShell({children, nav}: DocsShellProps) {
@@ -106,14 +96,9 @@ export function DocsShell({children, nav}: DocsShellProps) {
const libraryPackages = packages.filter(p => !isTheme(p) && !p.canaryOnly);
const canaryPackages = packages.filter(p => !isTheme(p) && p.canaryOnly);
- // Classify doc topics by category (from data). Getting Started is promoted
- // to a top-level nav item, so it is excluded from the Guide section.
- const guideTopics = docTopics
- .filter(d => d.category === 'guide' && d.topic !== 'getting-started')
- .sort((a, b) => a.title.localeCompare(b.title));
- const foundationTopics = docTopics
- .filter(d => d.category === 'foundations')
- .sort(foundationsSort);
+ // Classify doc topics by category (from data).
+ const {guide: guideItems, foundations: foundationItems} =
+ docsSidebarGroups(docTopics);
// True for the /components index AND every /components/[name] detail page.
// On these routes we hide every non-Components section so the sidebar is
@@ -196,14 +181,7 @@ export function DocsShell({children, nav}: DocsShellProps) {
<SideNavItem
label="Guide"
collapsible={{defaultIsCollapsed: false}}>
- {guideTopics.map(d => (
- <SideNavItem
- key={d.topic}
- label={d.title}
- href={`/docs/${d.topic}`}
- isSelected={pathname === `/docs/${d.topic}`}
- />
- ))}
+ <DocsSidebarItems items={guideItems} pathname={pathname} />
</SideNavItem>
</SideNavSection>
@@ -212,14 +190,10 @@ export function DocsShell({children, nav}: DocsShellProps) {
<SideNavItem
label="Foundations"
collapsible={{defaultIsCollapsed: false}}>
- {foundationTopics.map(d => (
- <SideNavItem
- key={d.topic}
- label={d.title}
- href={`/docs/${d.topic}`}
- isSelected={pathname === `/docs/${d.topic}`}
- />
- ))}
+ <DocsSidebarItems
+ items={foundationItems}
+ pathname={pathname}
+ />
</SideNavItem>
</SideNavSection>
diff --git a/apps/docsite/src/components/DocsSidebarItems.tsx b/apps/docsite/src/components/DocsSidebarItems.tsx
new file mode 100644
index 0000000000..d59328f1d6
--- /dev/null
+++ b/apps/docsite/src/components/DocsSidebarItems.tsx
@@ -0,0 +1,98 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file DocsSidebarItems.tsx
+ * @input The items of one docs sidebar group and the current path
+ * @output One sidebar entry per page, with a parent's pages nested under it
+ * @position Rendered by DocsShell in the Guide and Foundations groups
+ */
+
+import {useState} from 'react';
+import {SideNavItem} from '@astryxdesign/core/SideNav';
+import type {DocsNavTopic} from './docsNav';
+import type {DocsSidebarItem} from './docsSidebarData';
+
+interface DocsSidebarItemsProps {
+ items: DocsSidebarItem[];
+ pathname: string;
+}
+
+const hrefOf = (page: DocsNavTopic) => `/docs/${page.topic}`;
+
+function DocsPageEntry({
+ page,
+ pathname,
+}: {
+ page: DocsNavTopic;
+ pathname: string;
+}) {
+ return (
+ <SideNavItem
+ label={page.title}
+ href={hrefOf(page)}
+ isSelected={pathname === hrefOf(page)}
+ />
+ );
+}
+
+/**
+ * The shell stays mounted across in-site navigation, so a mount-time default
+ * alone would leave the parent closed when a link or search moves the reader
+ * to one of its pages. Each move to a child page opens the parent again; a
+ * collapse on that page stays until the next move.
+ */
+function DocsParentEntry({
+ item: {page, children},
+ pathname,
+}: {
+ item: DocsSidebarItem;
+ pathname: string;
+}) {
+ const hasCurrentChild = children.some(child => pathname === hrefOf(child));
+ const [isCollapsed, setIsCollapsed] = useState(!hasCurrentChild);
+ const [lastPathname, setLastPathname] = useState(pathname);
+ if (pathname !== lastPathname) {
+ setLastPathname(pathname);
+ if (hasCurrentChild) {
+ setIsCollapsed(false);
+ }
+ }
+ return (
+ <SideNavItem
+ label={page.title}
+ href={hrefOf(page)}
+ isSelected={pathname === hrefOf(page)}
+ collapsible={{
+ isCollapsed,
+ onCollapsedChange: setIsCollapsed,
+ }}>
+ {children.map(child => (
+ <DocsPageEntry key={child.topic} page={child} pathname={pathname} />
+ ))}
+ </SideNavItem>
+ );
+}
+
+export function DocsSidebarItems({items, pathname}: DocsSidebarItemsProps) {
+ return (
+ <>
+ {items.map(item =>
+ item.children.length === 0 ? (
+ <DocsPageEntry
+ key={item.page.topic}
+ page={item.page}
+ pathname={pathname}
+ />
+ ) : (
+ <DocsParentEntry
+ key={item.page.topic}
+ item={item}
+ pathname={pathname}
+ />
+ ),
+ )}
+ </>
+ );
+}
diff --git a/apps/docsite/src/components/docsNav.ts b/apps/docsite/src/components/docsNav.ts
index 56923de3c9..628cc49e15 100644
--- a/apps/docsite/src/components/docsNav.ts
+++ b/apps/docsite/src/components/docsNav.ts
@@ -23,7 +23,10 @@ export type DocsNavPackage = Pick<
'name' | 'displayName' | 'canaryOnly'
>;
-export type DocsNavTopic = Pick<DocTopic, 'topic' | 'title' | 'category'>;
+export type DocsNavTopic = Pick<
+ DocTopic,
+ 'topic' | 'title' | 'category' | 'parent'
+>;
export type DocsNavEntry = Pick<
ComponentSidebarEntry,
@@ -92,10 +95,11 @@ export function getDocsNav(): DocsNav {
displayName,
canaryOnly,
})),
- docTopics: docTopics.map(({topic, title, category}) => ({
+ docTopics: docTopics.map(({topic, title, category, parent}) => ({
topic,
title,
category,
+ parent,
})),
componentItems: componentItems.map(toNavItem),
utilities: utilities.map(toNavEntry),
diff --git a/apps/docsite/src/components/docsSidebarData.ts b/apps/docsite/src/components/docsSidebarData.ts
new file mode 100644
index 0000000000..e531e5a924
--- /dev/null
+++ b/apps/docsite/src/components/docsSidebarData.ts
@@ -0,0 +1,87 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file docsSidebarData.ts
+ * @input The docs registry's pages
+ * @output The Guide and Foundations sidebar groups: each page in its group's
+ * order, with the pages that name it as `parent` nested under it
+ * @position Read by DocsShell; tested on its own
+ */
+
+import type {DocsNavTopic} from './docsNav';
+
+export interface DocsSidebarItem {
+ page: DocsNavTopic;
+ children: DocsNavTopic[];
+}
+
+export interface DocsSidebarGroups {
+ guide: DocsSidebarItem[];
+ foundations: DocsSidebarItem[];
+}
+
+type Group = keyof DocsSidebarGroups;
+
+/**
+ * Getting Started has its own item at the top of the sidebar, so the Guide
+ * group leaves it out.
+ */
+function groupOf(page: DocsNavTopic): Group | null {
+ if (page.category === 'foundations') {
+ return 'foundations';
+ }
+ if (page.category === 'guide' && page.topic !== 'getting-started') {
+ return 'guide';
+ }
+ return null;
+}
+
+const byTitle = (a: DocsNavTopic, b: DocsNavTopic) =>
+ a.title.localeCompare(b.title);
+
+/** Foundations: tokens first, then by title. */
+const foundationsOrder = (a: DocsNavTopic, b: DocsNavTopic) => {
+ if (a.topic === 'tokens') {
+ return -1;
+ }
+ if (b.topic === 'tokens') {
+ return 1;
+ }
+ return byTitle(a, b);
+};
+
+/**
+ * A page sits under its parent in the parent's group, whatever its own group.
+ * Nesting is one level deep: a page whose parent is not in the sidebar, or is
+ * itself nested, stays at the top of its own group.
+ */
+export function docsSidebarGroups(
+ docTopics: DocsNavTopic[],
+): DocsSidebarGroups {
+ const shown = docTopics.filter(page => groupOf(page) !== null);
+ const bySlug = new Map(shown.map(page => [page.topic, page]));
+ const inSidebar = (slug?: string) =>
+ slug != null ? bySlug.get(slug) : undefined;
+ const parentOf = (page: DocsNavTopic) => {
+ const parent = inSidebar(page.parent);
+ if (!parent || parent === page || inSidebar(parent.parent)) {
+ return null;
+ }
+ return parent;
+ };
+ const items = (
+ group: Group,
+ order: (a: DocsNavTopic, b: DocsNavTopic) => number,
+ ): DocsSidebarItem[] =>
+ shown
+ .filter(page => groupOf(page) === group && !parentOf(page))
+ .sort(order)
+ .map(page => ({
+ page,
+ children: shown.filter(child => parentOf(child) === page).sort(byTitle),
+ }));
+ return {
+ guide: items('guide', byTitle),
+ foundations: items('foundations', foundationsOrder),
+ };
+}
diff --git a/docs/specs/AST-046-docs-tree/spec.md b/docs/specs/AST-046-docs-tree/spec.md
index 32308fe928..38cf2cd148 100644
--- a/docs/specs/AST-046-docs-tree/spec.md
+++ b/docs/specs/AST-046-docs-tree/spec.md
@@ -277,11 +277,19 @@ and references from other packages are an open question (OQ2).
the namespace open only in `astryx docs`. A topic that becomes a namespace (FR13) therefore keeps its
address, its sidebar group, and its text. The slug of each guide and nested
namespace below it (its route with `/` as `-`) MUST be a temporary redirect
- to where its text starts on the page. A root namespace whose slug is a
+ to where its text starts on the page. The docsite MAY give a nested
+ namespace that it names a page of its own instead: one page at that
+ namespace's slug, with its own content and every guide below it, which the
+ root page leaves out. Its sidebar entry MUST sit under the root page's
+ entry, and the slug of each guide below it MUST redirect into it. A root
+ namespace whose slug is a
package's page (`cli` is the CLI package's page) keeps one page per guide,
at the guide's slug, and has no namespace page. A namespace page's sidebar
group MUST be the namespace's own `category`; without one, `foundations`
- when every guide below it is a foundations doc, and `guide` otherwise. A
+ when every guide below it is a foundations doc, and `guide` otherwise. The
+ docsite MAY name a sidebar parent page for any page: the page keeps its
+ slug and its `category`, and its sidebar entry sits under the parent's
+ entry, in the parent's group. Sidebar nesting is one level deep. A
namespace with no guide below it, such as a generated topic level (FR12), has
no page. The docsite build MUST fail when a slug is both a page and a
redirect, or both a flat topic and a namespace page.
@@ -328,18 +336,18 @@ Phase 1 changes these surfaces:
## Verification
-| Contract | Verification | Representative states | Mutation or failure expectation |
-| ------------- | ----------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| FR1, FR3, FR4 | Tree builder fixture tests | three authored levels; adoption with and without `groupBy`; reversed input order; order and title sort | A route that ignores the parent, a folder that implies a parent, or a tree that depends on input order |
-| FR2 | Tree builder failure fixtures | no slot; unknown slot; a slot that refuses the kind; another package's parent; not a reference; two adopters; a cycle | A failed placement that falls back to adoption, or a failure without a diagnostic |
-| FR5, FR6, FR7 | `docs()` dispatcher tests and CLI runs | `cli`, `cli/api`, one function, the placed guide and its sections, the old name, a typo route; a section on a namespace that one guide, no guide, and two guides hold; the topic list read with and without a depth, and a guide one integration replaces | A namespace that inlines grandchildren, a lost section read, a section read that picks one of two guides, a wrong error code, a listed doc attributed to the package whose route it took, or an experimental doc listed unmarked |
-| FR8 | Doctor tests | this repo; a fixture tree with a broken placement | A broken tree or an unplaced CLI doc that passes |
-| FR9 | Real-tree tests and the route inventory | every command, function, schema, and enum doc; every exported API function | A CLI typed doc without its route, or a route inventory row the tree contradicts |
-| FR10 | Search tests and CLI runs | a guide section; a typed doc by its own name; an error code; a topic hit; no core installed | A section hit whose command reads the whole topic, or a docs-only search that needs core |
-| FR11 | Integration tree tests; guide route target tests | a namespace and two placed guides from a package whose provider id differs from its name; a broken link; a claim on the `cli` route; a flat topic that replaces or extends a CLI guide by its route, with `before` and `after` | A node named by the package name, a broken link that passes either doctor, an integration that takes a CLI route, a replaced guide or added section that names the wrong package, or a section out of place |
-| FR12 | `docs()` tests, the graph walk, and search tests | the level and its children in list order; a topic's Up, Previous, and Next; a flat topic hit's parent; an integration's flat topic | A flat topic without a home, a topic whose name changes, or a level that lists a placed guide |
-| FR13 | Split tests over the topic before and after, the graph walk, and search tests | each old section key read through the namespace; a link and a token reference to the old topic; a `--dense` read; the topic list and a search for one section | A dropped, merged, or copied section; a changed title or `id`; a reference left on the old identity; a name listed twice; a section found twice |
-| FR14 | Docsite page-generation and route-resolution tests | a split namespace; a nested namespace; a package-page namespace; a namespace with a `category`, and one whose guides are all foundations docs; a generated topic level | An old address that stops resolving or lands in another sidebar group, a permanent guide redirect, a guide page on a non-package namespace, or a slug that is both a page and a redirect |
+| Contract | Verification | Representative states | Mutation or failure expectation |
+| ------------- | ----------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| FR1, FR3, FR4 | Tree builder fixture tests | three authored levels; adoption with and without `groupBy`; reversed input order; order and title sort | A route that ignores the parent, a folder that implies a parent, or a tree that depends on input order |
+| FR2 | Tree builder failure fixtures | no slot; unknown slot; a slot that refuses the kind; another package's parent; not a reference; two adopters; a cycle | A failed placement that falls back to adoption, or a failure without a diagnostic |
+| FR5, FR6, FR7 | `docs()` dispatcher tests and CLI runs | `cli`, `cli/api`, one function, the placed guide and its sections, the old name, a typo route; a section on a namespace that one guide, no guide, and two guides hold; the topic list read with and without a depth, and a guide one integration replaces | A namespace that inlines grandchildren, a lost section read, a section read that picks one of two guides, a wrong error code, a listed doc attributed to the package whose route it took, or an experimental doc listed unmarked |
+| FR8 | Doctor tests | this repo; a fixture tree with a broken placement | A broken tree or an unplaced CLI doc that passes |
+| FR9 | Real-tree tests and the route inventory | every command, function, schema, and enum doc; every exported API function | A CLI typed doc without its route, or a route inventory row the tree contradicts |
+| FR10 | Search tests and CLI runs | a guide section; a typed doc by its own name; an error code; a topic hit; no core installed | A section hit whose command reads the whole topic, or a docs-only search that needs core |
+| FR11 | Integration tree tests; guide route target tests | a namespace and two placed guides from a package whose provider id differs from its name; a broken link; a claim on the `cli` route; a flat topic that replaces or extends a CLI guide by its route, with `before` and `after` | A node named by the package name, a broken link that passes either doctor, an integration that takes a CLI route, a replaced guide or added section that names the wrong package, or a section out of place |
+| FR12 | `docs()` tests, the graph walk, and search tests | the level and its children in list order; a topic's Up, Previous, and Next; a flat topic hit's parent; an integration's flat topic | A flat topic without a home, a topic whose name changes, or a level that lists a placed guide |
+| FR13 | Split tests over the topic before and after, the graph walk, and search tests | each old section key read through the namespace; a link and a token reference to the old topic; a `--dense` read; the topic list and a search for one section | A dropped, merged, or copied section; a changed title or `id`; a reference left on the old identity; a name listed twice; a section found twice |
+| FR14 | Docsite page-generation and route-resolution tests | a split namespace; a nested namespace; a nested namespace with its own page; a page with a named sidebar parent in another group; a package-page namespace; a namespace with a `category`, and one whose guides are all foundations docs; a generated topic level | An old address that stops resolving or lands in a sidebar group other than its own or its named parent's, a permanent guide redirect, a guide page on a non-package namespace, a nested page its root page also holds, or a slug that is both a page and a redirect |
## Decision log