An open source design system that's fully customizable and agent ready
TypeScript
fix(docsite): keep one full page per topic when the CLI splits its docs (#7199)
Joeyc4df65c164f0
diff --git a/apps/docsite/next.config.mjs b/apps/docsite/next.config.mjsindex a4d0f839ed..68dd42ab18 100644--- a/apps/docsite/next.config.mjs+++ b/apps/docsite/next.config.mjs@@ -9,7 +9,7 @@* @position Next.js configuration for the existing Vercel docsite deployment.*/-import {readFileSync, readdirSync} from 'node:fs';+import {existsSync, readFileSync, readdirSync} from 'node:fs';import {resolve} from 'node:path';const playgroundCookieCompatibility = readFileSync(@@ -20,6 +20,17 @@ const playgroundCookieCompatibility = readFileSync('utf8',);+// Slugs that are not pages of their own (generate-data.mjs): a guide under a+// docs-tree namespace opens at its section on the namespace's full page, and+// a flat topic merged into another page opens there.+const docRedirectsPath = resolve(+ import.meta.dirname,+ 'src/generated/docRedirects.json',+);+const docRedirects = existsSync(docRedirectsPath)+ ? JSON.parse(readFileSync(docRedirectsPath, 'utf8'))+ : {};+const stagesStaticApps =process.env.VERCEL_ENV === 'preview' ||process.env.VERCEL_ENV === 'production';@@ -68,6 +79,12 @@ const nextConfig = {destination: '/docs/cli-integrations-docs-add-a-topic',permanent: true,},+ // Temporary: a later site version may give these guides pages again.+ ...Object.entries(docRedirects).map(([slug, destination]) => ({+ source: `/docs/${slug}`,+ destination,+ permanent: false,+ })),];},// The playground preview evaluates user-authored code, so it is the onediff --git a/apps/docsite/scripts/docs-pages.mjs b/apps/docsite/scripts/docs-pages.mjsnew file mode 100644index 0000000000..61b1b765c7--- /dev/null+++ b/apps/docsite/scripts/docs-pages.mjs@@ -0,0 +1,208 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file docs-pages.mjs+ *+ * How the CLI's docs become docsite pages. The CLI splits a long topic into a+ * docs-tree namespace of short guides, so an agent can read one guide at a+ * time. A human reader keeps one full page per topic, at the same URL and in+ * the same sidebar spot, whatever the split.+ *+ * @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.+ * @position Used by generate-data.mjs; tested on its own with a fake reader.+ */++/**+ * Root namespaces that keep one page per guide instead of one full page.+ * `cli` is the CLI's own reference: /docs/cli is the @astryxdesign/cli package+ * page, and each integration guide under it already has its own page and+ * sidebar entry.+ */+export const GUIDE_PAGE_NAMESPACES = new Set(['cli']);++/**+ * Flat topics whose full text the site shows on another topic's page. The+ * theme split (before namespaces) left `theme` as a short overview and moved+ * its text to two flat topics, so the theme page shows those two in order in+ * place of the overview's pointers to them.+ */+export const MERGED_TOPICS = new Map([+ ['theme', ['use-a-theme', 'author-a-theme']],+]);++/**+ * Flat topics that are data for other docs, not pages: `token-tables` is what+ * token references read, and the tokens page already shows every table.+ */+export const DATA_ONLY_TOPICS = new Map([['token-tables', 'tokens']]);++/**+ * Anchor ids of a page's sections, the way ReferenceDocView's outline builds+ * them: the slug of each title, numbered on repeats, with heading blocks+ * taking their own ids in between.+ * @param {Array<{title: string, content?: Array<{type?: string, text?: string}>}>} sections+ * @returns {string[]}+ */+export function sectionAnchors(sections) {+ const seen = new Map();+ const unique = (value, fallback) => {+ const base =+ value+ .toLowerCase()+ .trim()+ .replace(/[^a-z0-9]+/g, '-')+ .replace(/^-+|-+$/g, '') || fallback;+ const count = seen.get(base) ?? 0;+ seen.set(base, count + 1);+ return count === 0 ? base : `${base}-${count + 1}`;+ };+ return sections.map(section => {+ const id = unique(section.title, 'section');+ for (const block of section.content ?? []) {+ if (block?.type === 'heading' && block.text) {+ unique(`${section.title} ${block.text}`, `${id}-heading`);+ }+ }+ return id;+ });+}++/** A docs-tree route as a site slug: `layout/scaffold` is `layout-scaffold`. */+export const routeSlug = route => route.replaceAll('/', '-');++/**+ * The docsite renders token tables itself, so a resolved token reference is+ * not copied into the registry.+ * @param {any[]} sections+ */+export function withoutResolvedTokens(sections) {+ return sections.map(section => ({+ ...section,+ content: (section.content ?? []).map(block => {+ if (block?.type !== 'token-ref') return block;+ const {resolved: _resolved, ...authored} = block;+ return authored;+ }),+ }));+}++/**+ * The sidebar group of a namespace page: the namespace's own category when it+ * declares one, otherwise `foundations` when every guide under it is a+ * foundations doc, otherwise `guide`.+ * @param {string | null | undefined} own+ * @param {Array<string | null | undefined>} guideCategories+ */+export function namespaceCategory(own, guideCategories) {+ if (own) return own;+ return guideCategories.length > 0 &&+ guideCategories.every(category => category === 'foundations')+ ? 'foundations'+ : 'guide';+}++/**+ * One full page for a root namespace: every guide under it, compiled in tree+ * order, as `astryx docs <route> --depth all --detail full` reads it. Each+ * guide and nested namespace keeps its slug as a redirect to where its text+ * starts on the page. Typed docs (commands, API docs) open only in+ * `astryx docs` and add nothing to the page.+ *+ * A namespace with no guide placed under it (the tree's Unorganized level,+ * whose children are flat topics with pages of their own) has no page.+ * @param {(topic?: string, section?: string, options?: object) => Promise<any>} readDocs+ * @param {string} route+ * @returns {Promise<{page: object, redirects: Record<string, string>} | null>}+ */+export async function namespacePage(readDocs, route) {+ const read = await readDocs(route, undefined, {depth: 'all', detail: 'full'});+ if (read?.type !== 'docs.node' || read.data.kind !== 'namespace') return null;+ const node = read.data;+ const sections = [];+ /** @type {Array<[string, number]>} slug and index of its first section */+ const starts = [];+ const guideCategories = [];+ if (node.content?.length > 0) {+ sections.push({title: 'Overview', content: node.content});+ }+ const walk = async slots => {+ for (const slot of slots ?? []) {+ for (const child of slot.children) {+ if (!child.route.startsWith(`${route}/`)) continue;+ if (child.kind === 'generic') {+ const detail = await readDocs(child.route);+ guideCategories.push(detail?.data?.category ?? null);+ starts.push([routeSlug(child.route), sections.length]);+ sections.push(...withoutResolvedTokens(child.sections ?? []));+ } else if (child.kind === 'namespace') {+ starts.push([routeSlug(child.route), sections.length]);+ if (child.content?.length > 0) {+ sections.push({title: child.title, content: child.content});+ }+ await walk(child.slots);+ }+ }+ }+ };+ await walk(node.slots);+ if (guideCategories.length === 0) return null;++ const anchors = sectionAnchors(sections);+ const href = `/docs/${route}`;+ const redirects = {};+ for (const [slug, index] of starts) {+ redirects[slug] =+ index < sections.length ? `${href}#${anchors[index]}` : href;+ }+ return {+ page: {+ topic: route,+ title: node.title || route,+ description: node.summary || '',+ category: namespaceCategory(node.category, guideCategories),+ sections,+ },+ redirects,+ };+}++/**+ * 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+ * data-only topic has no page. A host or part that is missing is skipped, so+ * the rule holds before and after the split that created it.+ * @param {Array<{topic: string, sections: any[]}>} topics+ * @returns {{topics: any[], redirects: Record<string, string>}}+ */+export function mergeFlatTopics(topics) {+ const bySlug = new Map(topics.map(topic => [topic.topic, topic]));+ const redirects = {};+ const dropped = new Set();+ for (const [host, parts] of MERGED_TOPICS) {+ const page = bySlug.get(host);+ const present = parts.filter(part => bySlug.has(part));+ if (!page || present.length === 0) continue;+ const sections = [];+ const starts = [];+ for (const part of present) {+ starts.push([part, sections.length]);+ sections.push(...bySlug.get(part).sections);+ dropped.add(part);+ }+ page.sections = sections;+ const anchors = sectionAnchors(sections);+ for (const [part, index] of starts) {+ redirects[part] = `/docs/${host}#${anchors[index]}`;+ }+ }+ for (const [topic, host] of DATA_ONLY_TOPICS) {+ if (!bySlug.has(topic)) continue;+ dropped.add(topic);+ redirects[topic] = `/docs/${host}`;+ }+ return {topics: topics.filter(topic => !dropped.has(topic.topic)), redirects};+}diff --git a/apps/docsite/scripts/generate-data.mjs b/apps/docsite/scripts/generate-data.mjsindex 1f198ae49b..e5e5d55ab6 100644--- a/apps/docsite/scripts/generate-data.mjs+++ b/apps/docsite/scripts/generate-data.mjs@@ -25,6 +25,13 @@ import {execFileSync} from 'node:child_process';import {createRequire} from 'node:module';import {fileURLToPath, pathToFileURL} from 'node:url';import {resolveContentRoot} from './resolve-content-root.mjs';+import {+ GUIDE_PAGE_NAMESPACES,+ mergeFlatTopics,+ namespacePage,+ routeSlug,+ withoutResolvedTokens,+} from './docs-pages.mjs';import {docs as readDocs,template as queryTemplates,@@ -1681,17 +1688,31 @@ export const templateMetadataCount = ${templateMetadata.length};// ── 5. Docs Registry ──────────────────────────────────────────────────/**- * Every guide in the CLI's docs tree, read through the CLI's public docs API:- * walk down from each top-level namespace and read each guide by its route.- * @returns {Promise<Array<{topic: string, title: string, description: string, category: string | null, sections: unknown[]}>>}+ * 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. Root+ * namespaces in GUIDE_PAGE_NAMESPACES keep one page per guide instead.*/-async function docsTreeGuides() {- const guides = [];- // Every route the tree has. The site has a page only for a guide; a- // reference to any other route still opens it in `astryx docs`.+async function docsTreePages() {+ const pages = [];+ const redirects = {};+ // Every route the tree has. A reference to a route without a page of its+ // own (a command or API doc) still opens it in `astryx docs`.const routes = [];const list = await readDocs();- const pending = (list.meta?.namespaces ?? []).map(entry => entry.topic);+ const pending = [];+ for (const {topic: root} of list.meta?.namespaces ?? []) {+ if (GUIDE_PAGE_NAMESPACES.has(root)) {+ pending.push(root);+ continue;+ }+ routes.push(...(await treeRoutes(root)));+ const full = await namespacePage(readDocs, root);+ if (!full) continue;+ pages.push(full.page);+ Object.assign(redirects, full.redirects);+ }while (pending.length > 0) {const route = pending.shift();routes.push(route);@@ -1703,11 +1724,9 @@ async function docsTreeGuides() {if (child.kind === 'namespace') {pending.push(child.route);} else if (child.kind === 'generic' && child.route.includes('/')) {- // A flat topic in the Unorganized level keeps its own name, and the- // flat registry above already has its page.const doc = (await readDocs(child.route)).data;- guides.push({- topic: child.route.replaceAll('/', '-'),+ pages.push({+ topic: routeSlug(child.route),title: doc.title || child.title,description: doc.description || '',category: doc.category || null,@@ -1717,7 +1736,27 @@ async function docsTreeGuides() {}}}- return {guides, routes};+ return {pages, redirects, routes};+}++/**+ * Every route at or below a docs-tree node.+ * @param {string} route+ * @returns {Promise<string[]>}+ */+async function treeRoutes(route) {+ const read = await readDocs(route, undefined, {depth: 'all'});+ const routes = [route];+ const walk = slots => {+ for (const slot of slots ?? []) {+ for (const child of slot.children) {+ routes.push(child.route);+ walk(child.slots);+ }+ }+ };+ if (read.type === 'docs.node') walk(read.data.slots);+ return routes;}async function generateDocsRegistry() {@@ -1727,8 +1766,9 @@ async function generateDocsRegistry() {if (!fs.existsSync(DOCS_DIR)) {writeRegistry('docsRegistry.ts',- `// Auto-generated — no docs found\nexport const docTopics = [];\nexport const docsCount = 0;\nexport const docsTreeRoutes = [];\n`,+ `// Auto-generated — no docs found\nexport const docTopics = [];\nexport const docsCount = 0;\nexport const docsTreeRoutes = [];\nexport const docRedirects = {};\n`,);+ fs.writeFileSync(path.join(OUT_DIR, 'docRedirects.json'), '{}\n');return {docTopics: [], docsCount: 0};}@@ -1767,14 +1807,7 @@ async function generateDocsRegistry() {// the read runs from the CLI package. The docsite renders token tables// itself, so a resolved token reference is not copied into the registry.const read = await readDocs(topic, undefined, {cwd: CLI_ROOT});- sections = read.data.sections.map(section => ({- ...section,- content: section.content.map(block => {- if (block?.type !== 'token-ref') return block;- const {resolved: _resolved, ...authored} = block;- return authored;- }),- }));+ sections = withoutResolvedTokens(read.data.sections);}docTopics.push({@@ -1786,15 +1819,36 @@ async function generateDocsRegistry() {});}+ // Flat topics shown on another topic's page, or kept only as data.+ const merged = mergeFlatTopics(docTopics);+ docTopics.splice(0, docTopics.length, ...merged.topics);+// Guides the CLI's docs tree places (spec:AST-046) are not topic files: the- // CLI reads them only by route. Until the site renders the tree itself, each- // keeps a flat page whose slug is its route with "/" as "-", so+ // CLI reads them only by route. A root namespace is one full page at its+ // slug (a former flat topic keeps its URL), and each guide under it+ // redirects to its section there. Guides under GUIDE_PAGE_NAMESPACES keep a+ // flat page whose slug is the route with "/" as "-", so// `cli/integrations/quick-start` is /docs/cli-integrations-quick-start.- const tree = await docsTreeGuides();- for (const guide of tree.guides) {- docTopics.push(guide);+ const tree = await docsTreePages();+ for (const page of tree.pages) {+ if (docTopics.some(topic => topic.topic === page.topic)) {+ throw new Error(+ `docs: "${page.topic}" is both a flat topic and a docs-tree page. Remove the flat topic file when its namespace replaces it.`,+ );+ }+ docTopics.push(page);}const docsTreeRoutes = [...new Set(tree.routes)].sort();+ const docRedirects = Object.fromEntries(+ Object.entries({...merged.redirects, ...tree.redirects}).sort(([a], [b]) =>+ a.localeCompare(b),+ ),+ );+ for (const slug of Object.keys(docRedirects)) {+ if (docTopics.some(topic => topic.topic === slug)) {+ throw new Error(`docs: "${slug}" is both a page and a redirect.`);+ }+ }docTopics.sort((a, b) => a.topic.localeCompare(b.topic));@@ -1843,11 +1897,20 @@ export const docTopics: DocTopic[] = ${JSON.stringify(docTopics, null, 2)};export const docsCount = ${docTopics.length};-/** Every route of the CLI's docs tree. A guide has a page here; any other- * route (a namespace, a command or API doc) opens only in \`astryx docs\`. */+/** Every route of the CLI's docs tree. A route with no page or redirect here+ * (a command or API doc) opens only in \`astryx docs\`. */export const docsTreeRoutes: string[] = ${JSON.stringify(docsTreeRoutes, null, 2)};++/** Slugs that are not pages of their own, each to where its text is shown: a+ * guide under a namespace page, or a flat topic merged into another page.+ * next.config.mjs serves them as redirects. */+export const docRedirects: Record<string, string> = ${JSON.stringify(docRedirects, null, 2)};`;writeRegistry('docsRegistry.ts', content);+ fs.writeFileSync(+ path.join(OUT_DIR, 'docRedirects.json'),+ `${JSON.stringify(docRedirects, null, 2)}\n`,+ );return {docTopics, docsCount: docTopics.length};}diff --git a/apps/docsite/src/__tests__/docs-pages.test.ts b/apps/docsite/src/__tests__/docs-pages.test.tsnew file mode 100644index 0000000000..e4030be1eb--- /dev/null+++ b/apps/docsite/src/__tests__/docs-pages.test.ts@@ -0,0 +1,202 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {describe, expect, it} from 'vitest';+import {+ mergeFlatTopics,+ namespaceCategory,+ namespacePage,+ sectionAnchors,+} from '../../scripts/docs-pages.mjs';+import {buildOutline} from '../components/docs/docOutline';+import type {DocSection} from '../generated/docsRegistry';++const section = (title: string, text = `${title} text.`) => ({+ title,+ content: [{type: 'prose', text}],+});++/** The flat topic as the site had it before the split. */+const widgetsBefore = {+ topic: 'widgets',+ title: 'Widgets',+ description: 'Pick and place widgets.',+ category: 'foundations',+ sections: [+ section('Overview'),+ section('Sizes'),+ section('Best Practices'),+ section('Theming'),+ ],+};++type Guide = {route: string; title: string; category: string | null};++/**+ * A docs reader shaped like the CLI docs API after `widgets` became a root+ * namespace of two guides: `docs(route)` reads one guide, and+ * `docs(route, undefined, {depth: 'all', detail: 'full'})` reads the+ * namespace with every guide's compiled sections.+ */+function splitReader(+ guides: Array<Guide & {sections: ReturnType<typeof section>[]}>,+) {+ return async (+ route?: string,+ _section?: string,+ options: {depth?: number | 'all'} = {},+ ) => {+ const guide = guides.find(g => g.route === route);+ if (guide) {+ return {+ type: 'docs.detail',+ data: {+ title: guide.title,+ category: guide.category,+ sections: guide.sections,+ },+ };+ }+ if (route === 'widgets' && options.depth === 'all') {+ return {+ type: 'docs.node',+ data: {+ route: 'widgets',+ kind: 'namespace',+ title: 'Widgets',+ summary: 'Pick and place widgets.',+ content: [],+ slots: [+ {+ name: 'guides',+ title: 'Guides',+ children: guides.map(g => ({+ route: g.route,+ kind: 'generic',+ title: g.title,+ sections: g.sections,+ })),+ },+ ],+ },+ };+ }+ throw new Error(`unexpected read ${route}`);+ };+}++describe('a flat topic split into a docs-tree namespace', () => {+ const guides = [+ {+ route: 'widgets/basics',+ title: 'Basics',+ category: 'foundations',+ sections: widgetsBefore.sections.slice(0, 2),+ },+ {+ route: 'widgets/advanced',+ title: 'Advanced',+ category: 'foundations',+ sections: widgetsBefore.sections.slice(2),+ },+ ];++ it('keeps one page at the old slug, in the same group, with the same sections', async () => {+ const result = await namespacePage(splitReader(guides), 'widgets');+ expect(result?.page).toEqual(widgetsBefore);+ });++ it('sends each guide slug to its section on that page', async () => {+ const result = await namespacePage(splitReader(guides), 'widgets');+ expect(result?.redirects).toEqual({+ 'widgets-basics': '/docs/widgets#overview',+ 'widgets-advanced': '/docs/widgets#best-practices',+ });+ });++ it('has no page for a level whose children are not placed under it', async () => {+ const read = async () => ({+ type: 'docs.node',+ data: {+ route: 'unorganized',+ kind: 'namespace',+ title: 'Unorganized',+ content: [],+ slots: [+ {+ name: 'topics',+ children: [{route: 'color', kind: 'generic', sections: []}],+ },+ ],+ },+ });+ expect(await namespacePage(read, 'unorganized')).toBeNull();+ });+});++describe('namespaceCategory', () => {+ it('prefers the namespace, then foundations only when every guide is', () => {+ expect(namespaceCategory('guide', ['foundations'])).toBe('guide');+ expect(namespaceCategory(null, ['foundations', 'foundations'])).toBe(+ 'foundations',+ );+ expect(namespaceCategory(null, ['foundations', 'guide'])).toBe('guide');+ expect(namespaceCategory(null, [null])).toBe('guide');+ });+});++describe('mergeFlatTopics', () => {+ const flat = (topic: string, titles: string[]) => ({+ topic,+ title: topic,+ description: '',+ category: 'guide',+ sections: titles.map(t => section(t)),+ });++ it('shows the theme split on one theme page', () => {+ const {topics, redirects} = mergeFlatTopics([+ flat('theme', ['Wrap your app in a theme']),+ flat('use-a-theme', ['Wrap your app in a theme', 'Dark mode']),+ flat('author-a-theme', ['Custom themes']),+ flat('color', ['Overview']),+ ]);+ expect(topics.map(t => t.topic)).toEqual(['theme', 'color']);+ expect(topics[0].sections.map((s: {title: string}) => s.title)).toEqual([+ 'Wrap your app in a theme',+ 'Dark mode',+ 'Custom themes',+ ]);+ expect(redirects).toEqual({+ 'use-a-theme': '/docs/theme#wrap-your-app-in-a-theme',+ 'author-a-theme': '/docs/theme#custom-themes',+ });+ });++ it('leaves the topics alone before the split', () => {+ const before = [flat('theme', ['Dark mode']), flat('tokens', ['Color'])];+ expect(mergeFlatTopics(before)).toEqual({topics: before, redirects: {}});+ });++ it('keeps token data off the site', () => {+ const {topics, redirects} = mergeFlatTopics([flat('token-tables', ['A'])]);+ expect(topics).toEqual([]);+ expect(redirects).toEqual({'token-tables': '/docs/tokens'});+ });+});++describe('sectionAnchors', () => {+ it('matches the page outline, repeats and heading blocks included', () => {+ const sections = [+ {+ title: 'Overview',+ content: [{type: 'heading', text: 'Overview'}],+ },+ section('Overview'),+ section('Best Practices'),+ section('Best practices'),+ ];+ expect(sectionAnchors(sections)).toEqual(+ buildOutline(sections as DocSection[]).sectionIds,+ );+ });+});diff --git a/apps/docsite/src/__tests__/route-resolution.test.ts b/apps/docsite/src/__tests__/route-resolution.test.tsnew file mode 100644index 0000000000..fca9d025c1--- /dev/null+++ b/apps/docsite/src/__tests__/route-resolution.test.ts@@ -0,0 +1,130 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {describe, expect, it} from 'vitest';+import {+ docRedirects,+ docTopics,+ docsTreeRoutes,+} from '../generated/docsRegistry';+import {packages} from '../generated/packageRegistry';+import {linkifyCode} from '../components/codeLinkifiers';+import {buildOutline} from '../components/docs/docOutline';++/**+ * Every topic page the site had before the CLI's docs were split into+ * docs-tree namespaces, with its sidebar group. A split changes how agents+ * read a topic, never where a reader finds it: each slug keeps one page in the+ * same group. Guides under the `cli` namespace keep their own pages and are+ * not listed here.+ */+const PAGES_BEFORE_THE_SPLITS: Record<string, 'guide' | 'foundations'> = {+ authoring: 'guide',+ 'browser-support': 'guide',+ color: 'foundations',+ elevation: 'foundations',+ 'getting-started': 'guide',+ icons: 'foundations',+ illustrations: 'foundations',+ internationalization: 'guide',+ layout: 'guide',+ migration: 'guide',+ motion: 'foundations',+ principles: 'guide',+ shape: 'foundations',+ spacing: 'foundations',+ styling: 'guide',+ 'styling-libraries': 'guide',+ theme: 'guide',+ tokens: 'foundations',+ typography: 'foundations',+ 'working-with-ai': 'guide',+};++const pageBySlug = new Map(docTopics.map(topic => [topic.topic, topic]));++describe('route resolution', () => {+ it.each(Object.entries(PAGES_BEFORE_THE_SPLITS))(+ '/docs/%s still has a page in the %s group',+ (slug, category) => {+ const page = pageBySlug.get(slug);+ expect(page, `/docs/${slug} lost its page`).toBeDefined();+ expect(page?.category).toBe(category);+ expect(page?.sections.length).toBeGreaterThan(0);+ },+ );++ it('keeps the layout page whole, with its old section anchors', () => {+ const layout = pageBySlug.get('layout');+ const ids = buildOutline(layout?.sections ?? []).sectionIds;+ for (const anchor of [+ 'scaffold',+ 'shell',+ 'navigation',+ 'structure',+ 'headers-and-footers',+ 'side-panels',+ 'spacing',+ 'breakpoints',+ 'responsive-contract',+ ]) {+ expect(ids).toContain(anchor);+ }+ });++ it('shows the full theme text on the theme page', () => {+ const titles = pageBySlug.get('theme')?.sections.map(s => s.title) ?? [];+ for (const title of [+ 'Wrap your app in a theme',+ 'Available Themes',+ 'Custom themes',+ 'defineTheme',+ 'Dark mode',+ 'useTheme Hook',+ ]) {+ expect(titles).toContain(title);+ }+ });++ it('keeps /docs/cli the CLI package page', () => {+ expect(pageBySlug.has('cli')).toBe(false);+ expect(packages.some(pkg => pkg.name === '@astryxdesign/cli')).toBe(true);+ });++ it('gives no doc page the slug of a package page', () => {+ const packageSlugs = packages.map(pkg =>+ pkg.name.replace('@astryxdesign/', ''),+ );+ for (const slug of packageSlugs) {+ expect(pageBySlug.has(slug), slug).toBe(false);+ }+ });++ it('redirects each folded slug to a section of a page, never a page of its own', () => {+ for (const [slug, href] of Object.entries(docRedirects)) {+ expect(pageBySlug.has(slug), `${slug} is a page and a redirect`).toBe(+ false,+ );+ const [, target, anchor] = /^\/docs\/([^#]+)(?:#(.+))?$/.exec(href) ?? [];+ const page = pageBySlug.get(target);+ expect(page, `${slug} -> ${href}`).toBeDefined();+ if (anchor) {+ expect(buildOutline(page?.sections ?? []).sectionIds).toContain(anchor);+ }+ }+ });++ it('opens a guide under a namespace page at its section', () => {+ if (docsTreeRoutes.includes('layout/side-panels')) {+ expect(linkifyCode('astryx docs layout/side-panels')).toBe(+ '/docs/layout#side-panels',+ );+ }+ expect(linkifyCode('astryx docs layout')).toBe('/docs/layout');+ });++ it('links every doc page from `astryx docs <slug>`', () => {+ for (const {topic} of docTopics) {+ expect(linkifyCode(`astryx docs ${topic}`)).toBe(`/docs/${topic}`);+ }+ });+});diff --git a/apps/docsite/src/components/codeLinkifiers.ts b/apps/docsite/src/components/codeLinkifiers.tsindex 70932ea9c7..90ca3c3f9c 100644--- a/apps/docsite/src/components/codeLinkifiers.ts+++ b/apps/docsite/src/components/codeLinkifiers.ts@@ -19,7 +19,7 @@* append it to LINKIFIERS.*/-import {docTopics} from '../generated/docsRegistry';+import {docRedirects, docTopics} from '../generated/docsRegistry';import {components} from '../generated/componentRegistry';/** Returns an href for a code span it recognizes, or null to pass. */@@ -46,10 +46,14 @@ const docTopic: CodeLinkifier = code => {if (topic == null) {return '/docs';}- // A docs-tree guide (`cli/integrations`) has a flat page named after its- // route, with "/" as "-", until the site renders the tree itself.+ // A docs-tree guide has a slug named after its route, with "/" as "-": its+ // own page (`cli/integrations/quick-start`), or a redirect to its section on+ // its namespace's page (`layout/scaffold` -> /docs/layout#scaffold).const slug = topic.replaceAll('/', '-');- return KNOWN_TOPICS.has(slug) ? `/docs/${slug}` : null;+ if (KNOWN_TOPICS.has(slug)) {+ return `/docs/${slug}`;+ }+ return docRedirects[slug] ?? null;};/** Every documented component and hook name; each has a /components page. */diff --git a/apps/docsite/src/components/docs/ReferenceDocView.tsx b/apps/docsite/src/components/docs/ReferenceDocView.tsxindex e719feb805..2c2ec768ab 100644--- a/apps/docsite/src/components/docs/ReferenceDocView.tsx+++ b/apps/docsite/src/components/docs/ReferenceDocView.tsx@@ -3,11 +3,11 @@'use client';import {VStack} from '@astryxdesign/core/Layout';-import type {OutlineItem} from '@astryxdesign/core/Outline';import {AnchorHeading} from './AnchorHeading';import {ContentBlockRenderer} from './ContentBlockRenderer';import {BestPracticesBlock} from './BestPracticesBlock';import {DocPageLayout} from './DocPageLayout';+import {buildOutline, normalizeHeadingLevel} from './docOutline';import type {DocSection} from '../../generated/docsRegistry';import type {ReactNode} from 'react';@@ -16,74 +16,6 @@ export type SectionOverrides = Record<(section: DocSection, id: string) => ReactNode>;-/** Slugify a section title into a stable, URL-safe anchor id. */-function slugify(value: string): string {- return value- .toLowerCase()- .trim()- .replace(/[^a-z0-9]+/g, '-')- .replace(/^-+|-+$/g, '');-}--function uniqueSlug(- value: string,- seen: Map<string, number>,- fallback: string,-): string {- const base = slugify(value) || fallback;- const count = seen.get(base) ?? 0;- seen.set(base, count + 1);- return count === 0 ? base : `${base}-${count + 1}`;-}--function normalizeHeadingLevel(level: number | undefined): 3 | 4 | 5 | 6 {- return level === 4 || level === 5 || level === 6 ? level : 3;-}--/**- * Build unique anchor ids for sections and nested heading blocks, deduping- * collisions so every outline link resolves to exactly one element.- */-function buildOutline(sections: DocSection[]): {- sectionIds: string[];- blockIds: Map<string, string>;- outline: OutlineItem[];-} {- const seen = new Map<string, number>();- const sectionIds: string[] = [];- const blockIds = new Map<string, string>();- const outline: OutlineItem[] = [];-- sections.forEach((section, sectionIndex) => {- const sectionId = uniqueSlug(section.title, seen, 'section');- sectionIds.push(sectionId);- outline.push({- id: sectionId,- label: section.title,- level: 2,- });-- section.content.forEach((block, blockIndex) => {- if (block.type !== 'heading' || !block.text) {- return;- }- const blockId = uniqueSlug(- `${section.title} ${block.text}`,- seen,- `${sectionId}-heading`,- );- blockIds.set(`${sectionIndex}:${blockIndex}`, blockId);- outline.push({- id: blockId,- label: block.text,- level: normalizeHeadingLevel(block.level),- });- });- });-- return {sectionIds, blockIds, outline};-}-function isGuidanceList(block: DocSection['content'][number] | undefined) {return (block?.type === 'list' && (block.style === 'do' || block.style === 'dont')diff --git a/apps/docsite/src/components/docs/docOutline.ts b/apps/docsite/src/components/docs/docOutline.tsnew file mode 100644index 0000000000..0f71038d85--- /dev/null+++ b/apps/docsite/src/components/docs/docOutline.ts@@ -0,0 +1,80 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Section anchors and the outline of a reference doc page. Kept apart+ * from ReferenceDocView so build scripts and tests can check anchors without+ * rendering. generate-data's docs-pages.mjs mirrors sectionIds for redirects.+ */++import type {OutlineItem} from '@astryxdesign/core/Outline';+import type {DocSection} from '../../generated/docsRegistry';++/** Slugify a section title into a stable, URL-safe anchor id. */+function slugify(value: string): string {+ return value+ .toLowerCase()+ .trim()+ .replace(/[^a-z0-9]+/g, '-')+ .replace(/^-+|-+$/g, '');+}++function uniqueSlug(+ value: string,+ seen: Map<string, number>,+ fallback: string,+): string {+ const base = slugify(value) || fallback;+ const count = seen.get(base) ?? 0;+ seen.set(base, count + 1);+ return count === 0 ? base : `${base}-${count + 1}`;+}++export function normalizeHeadingLevel(+ level: number | undefined,+): 3 | 4 | 5 | 6 {+ return level === 4 || level === 5 || level === 6 ? level : 3;+}++/**+ * Build unique anchor ids for sections and nested heading blocks, deduping+ * collisions so every outline link resolves to exactly one element.+ */+export function buildOutline(sections: DocSection[]): {+ sectionIds: string[];+ blockIds: Map<string, string>;+ outline: OutlineItem[];+} {+ const seen = new Map<string, number>();+ const sectionIds: string[] = [];+ const blockIds = new Map<string, string>();+ const outline: OutlineItem[] = [];++ sections.forEach((section, sectionIndex) => {+ const sectionId = uniqueSlug(section.title, seen, 'section');+ sectionIds.push(sectionId);+ outline.push({+ id: sectionId,+ label: section.title,+ level: 2,+ });++ section.content.forEach((block, blockIndex) => {+ if (block.type !== 'heading' || !block.text) {+ return;+ }+ const blockId = uniqueSlug(+ `${section.title} ${block.text}`,+ seen,+ `${sectionId}-heading`,+ );+ blockIds.set(`${sectionIndex}:${blockIndex}`, blockId);+ outline.push({+ id: blockId,+ label: block.text,+ level: normalizeHeadingLevel(block.level),+ });+ });+ });++ return {sectionIds, blockIds, outline};+}