Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

test(docs): unit-test sidebar ordering, cross-listing and pagination

Lincoln Stein49b57912a574
diff --git a/.github/workflows/deploy-docs.yml b/.github/workflows/deploy-docs.yml
index 58cce3ac25..88ace849ea 100644
--- a/.github/workflows/deploy-docs.yml
+++ b/.github/workflows/deploy-docs.yml
@@ -107,6 +107,10 @@ jobs:
working-directory: docs
# Checks
+ - name: test docs tooling
+ run: pnpm test
+ working-directory: docs
+
- name: verify generated docs data
run: pnpm run check-docs-data
working-directory: docs
diff --git a/docs/package.json b/docs/package.json
index 44966f4b57..1839a673f1 100644
--- a/docs/package.json
+++ b/docs/package.json
@@ -9,6 +9,7 @@
"check-docs-data": "pnpm run generate-docs-data && git diff --exit-code -- src/generated",
"check-deploy-output": "node ./scripts/verify-deploy-output.mjs",
"check-redirects": "node ./scripts/validate-redirect-targets.mjs",
+ "test": "node --test \"src/**/*.test.mjs\"",
"build": "astro build",
"preview": "astro preview",
"astro": "astro"
diff --git a/docs/src/lib/sidebar.mjs b/docs/src/lib/sidebar.mjs
new file mode 100644
index 0000000000..acb8383d3f
--- /dev/null
+++ b/docs/src/lib/sidebar.mjs
@@ -0,0 +1,192 @@
+import { generateDocsId, getSortPrefix, stripSortPrefix } from './sort-prefix.mjs';
+
+// Sidebar post-processing for the Starlight route middleware (`src/route-data.ts`): sort-prefix ordering,
+// cross-listing via `alsoListedIn` frontmatter, and prev/next links. Plain JavaScript so `node --test` can exercise
+// it without Astro.
+
+/**
+ * @typedef {import('@astrojs/starlight/route-data').StarlightRouteData} StarlightRouteData
+ * @typedef {StarlightRouteData['sidebar'][number]} SidebarEntry
+ * @typedef {Extract<SidebarEntry, { type: 'link' }>} SidebarLink
+ * @typedef {StarlightRouteData['entry']['data']['prev']} PrevNextConfig
+ * @typedef {{ id: string, directory: string }} CrossListing
+ */
+
+/** Marks the copy of a link that a page's `alsoListedIn` frontmatter adds; pagination skips these. */
+export const CROSS_LISTED_ATTR = 'data-cross-listed';
+
+/** @param {string} path */
+export const trimSlashes = (path) => path.replace(/^\/+|\/+$/g, '');
+
+/** @param {string} id */
+export const parentDirectory = (id) => id.slice(0, Math.max(id.lastIndexOf('/'), 0));
+
+/**
+ * Maps a sidebar link's href to a docs page id, removing the deployment base path.
+ * @param {string} baseUrl
+ * @returns {(href: string) => string}
+ */
+export const makeHrefToId = (baseUrl) => {
+ const basePath = trimSlashes(baseUrl);
+ return (href) => {
+ const path = trimSlashes(href);
+ return basePath && path.startsWith(`${basePath}/`) ? path.slice(basePath.length + 1) : path;
+ };
+};
+
+/**
+ * A docs file's directory as a URL path, e.g. `src/content/docs/Users Guide/03.Models/x.mdx` -> `users-guide/models`.
+ * @param {string | undefined} filePath
+ */
+export const fileDirectory = (filePath) => {
+ const relative = filePath?.split('content/docs/').pop() ?? '';
+ const directory = relative.slice(0, Math.max(relative.lastIndexOf('/'), 0));
+ // A placeholder file name, because generateDocsId drops a trailing extension-like segment.
+ return directory ? parentDirectory(generateDocsId({ entry: `${directory}/page.md`, data: {} })) : '';
+};
+
+/**
+ * The cross-listings declared by `alsoListedIn` frontmatter. Starlight leaves draft (in production) and hidden pages
+ * out of the sidebar, so they have no link to copy.
+ * @param {{ id: string, data: { alsoListedIn?: string[], draft?: boolean, sidebar?: { hidden?: boolean } } }[]} docs
+ * @param {boolean} isProduction
+ * @returns {CrossListing[]}
+ */
+export const selectCrossListings = (docs, isProduction) =>
+ docs
+ .filter((doc) => !doc.data.sidebar?.hidden && !(doc.data.draft && isProduction))
+ .flatMap((doc) =>
+ (doc.data.alsoListedIn ?? []).map((directory) => ({ id: doc.id, directory: trimSlashes(directory) }))
+ );
+
+/**
+ * Starlight orders autogenerated entries by frontmatter `sidebar.order`, then by id, and ids no longer carry the
+ * prefix. Reorder siblings generated from the same directory by prefix (unprefixed ones follow, in Starlight's order)
+ * and strip the prefix from directory labels. Other entries keep their positions.
+ * @param {SidebarEntry[]} entries
+ * @param {Map<string, string>} fileNames page id -> file name, which keeps the sorting prefix the id drops
+ * @param {(href: string) => string} hrefToId
+ * @returns {boolean} whether anything moved
+ */
+export const sortAndRelabel = (entries, fileNames, hrefToId) => {
+ let changed = false;
+ /** @param {SidebarEntry} entry */
+ const sortKey = (entry) =>
+ getSortPrefix(entry.type === 'group' ? entry.label : (fileNames.get(hrefToId(entry.href)) ?? '')) ??
+ Number.POSITIVE_INFINITY;
+
+ /** @type {Map<string, number[]>} */
+ const slotsByDirectory = new Map();
+ entries.forEach((entry, index) => {
+ const directory = 'autogenerate' in entry ? entry.autogenerate?.directory : undefined;
+ if (directory !== undefined) slotsByDirectory.set(directory, [...(slotsByDirectory.get(directory) ?? []), index]);
+ });
+ for (const slots of slotsByDirectory.values()) {
+ const sorted = slots.map((index) => entries[index]).sort((a, b) => sortKey(a) - sortKey(b));
+ slots.forEach((slot, i) => {
+ if (entries[slot] !== sorted[i]) changed = true;
+ entries[slot] = sorted[i];
+ });
+ }
+
+ for (const entry of entries) {
+ if (entry.type !== 'group') continue;
+ if ('autogenerate' in entry && entry.autogenerate) entry.label = stripSortPrefix(entry.label);
+ if (sortAndRelabel(entry.entries, fileNames, hrefToId)) changed = true;
+ }
+ return changed;
+};
+
+/**
+ * @param {SidebarEntry[]} entries
+ * @returns {SidebarLink[]}
+ */
+export const flattenLinks = (entries) =>
+ entries.flatMap((entry) => (entry.type === 'group' ? flattenLinks(entry.entries) : [entry]));
+
+/**
+ * The group autogenerated from a docs directory: the one whose own links are pages in that directory. A directory
+ * holding only subdirectories cannot be found this way.
+ * @param {SidebarEntry[]} entries
+ * @param {string} directory
+ * @param {Map<string, string>} directories page id -> file directory
+ * @param {(href: string) => string} hrefToId
+ * @returns {SidebarEntry[] | undefined}
+ */
+export const findDirectoryGroup = (entries, directory, directories, hrefToId) => {
+ if (entries.some((entry) => entry.type === 'link' && directories.get(hrefToId(entry.href)) === directory)) {
+ return entries;
+ }
+ for (const entry of entries) {
+ const found = entry.type === 'group' ? findDirectoryGroup(entry.entries, directory, directories, hrefToId) : undefined;
+ if (found) return found;
+ }
+ return undefined;
+};
+
+/**
+ * Autogenerated sidebars list each page once, under its own directory. Add a copy of each cross-listed page's link to
+ * the group of every directory its `alsoListedIn` frontmatter names, placed alphabetically by label among that group's
+ * links (so target directories should order their pages alphabetically). A misconfigured listing throws, failing the
+ * build.
+ * @param {SidebarEntry[]} sidebar
+ * @param {CrossListing[]} crossListings
+ * @param {Map<string, string>} directories page id -> file directory
+ * @param {(href: string) => string} hrefToId
+ * @returns {boolean} whether anything was added
+ */
+export const addCrossListings = (sidebar, crossListings, directories, hrefToId) => {
+ if (crossListings.length === 0) return false;
+ const linksById = new Map(flattenLinks(sidebar).map((link) => [hrefToId(link.href), link]));
+ for (const { id, directory } of crossListings) {
+ const link = linksById.get(id);
+ if (!link) throw new Error(`Cross-listed page "${id}" has no sidebar link.`);
+ if (directories.get(id) === directory) throw new Error(`Page "${id}" is cross-listed in its own directory.`);
+ const group = findDirectoryGroup(sidebar, directory, directories, hrefToId);
+ if (!group) {
+ throw new Error(`Page "${id}" is cross-listed in "${directory}", which has no sidebar group with pages.`);
+ }
+ // Before the first link that sorts after it, else before the group's first subgroup, else last.
+ const laterLink = group.findIndex(
+ (entry) => entry.type === 'link' && entry.label.localeCompare(link.label, 'en', { sensitivity: 'base' }) > 0
+ );
+ const firstGroup = group.findIndex((entry) => entry.type === 'group');
+ const index = laterLink !== -1 ? laterLink : firstGroup !== -1 ? firstGroup : group.length;
+ // The page's own link carries the current-page state, so the copy never does.
+ group.splice(index, 0, { ...link, isCurrent: false, attrs: { ...link.attrs, [CROSS_LISTED_ATTR]: '' } });
+ }
+ return true;
+};
+
+/**
+ * Mirrors Starlight's handling of the frontmatter `prev`/`next` options for a regenerated neighbour link.
+ * @param {SidebarLink | undefined} link
+ * @param {PrevNextConfig} config
+ * @returns {SidebarLink | undefined}
+ */
+export const applyPrevNextConfig = (link, config) => {
+ if (config === false) return undefined;
+ if (config === undefined || config === true) return link;
+ if (typeof config === 'string') return link && { ...link, label: config };
+ if (link) return { ...link, label: config.label ?? link.label, href: config.link ?? link.href, attrs: {} };
+ if (config.link && config.label) {
+ return { type: 'link', href: config.link, label: config.label, isCurrent: false, badge: undefined, attrs: {} };
+ }
+ return undefined;
+};
+
+/**
+ * Prev/next links for the current page in sidebar order, skipping cross-listed copies, or `null` when the current page
+ * is not in the sidebar (Starlight's own pagination then stands).
+ * @param {SidebarEntry[]} sidebar
+ * @param {{ prev?: PrevNextConfig, next?: PrevNextConfig }} data the page's frontmatter
+ */
+export const paginate = (sidebar, data) => {
+ const links = flattenLinks(sidebar).filter((link) => !(CROSS_LISTED_ATTR in link.attrs));
+ const current = links.findIndex((link) => link.isCurrent);
+ if (current === -1) return null;
+ return {
+ prev: applyPrevNextConfig(links[current - 1], data.prev),
+ next: applyPrevNextConfig(links[current + 1], data.next),
+ };
+};
diff --git a/docs/src/lib/sidebar.test.mjs b/docs/src/lib/sidebar.test.mjs
new file mode 100644
index 0000000000..11873e02eb
--- /dev/null
+++ b/docs/src/lib/sidebar.test.mjs
@@ -0,0 +1,221 @@
+import assert from 'node:assert/strict';
+import { describe, it } from 'node:test';
+
+import {
+ addCrossListings,
+ CROSS_LISTED_ATTR,
+ fileDirectory,
+ makeHrefToId,
+ paginate,
+ selectCrossListings,
+ sortAndRelabel,
+} from './sidebar.mjs';
+import { generateDocsId } from './sort-prefix.mjs';
+
+const hrefToId = makeHrefToId('/');
+
+/** @param {string} id */
+const link = (id, label = id.split('/').pop(), isCurrent = false) => ({
+ type: 'link',
+ href: `/${id}/`,
+ label,
+ isCurrent,
+ attrs: {},
+});
+
+/** @param {string} label @param {string} directory @param {object[]} entries */
+const group = (label, directory, entries) => ({ type: 'group', label, autogenerate: { directory }, entries });
+
+/** @param {object[]} entries */
+const labels = (entries) => entries.map((entry) => entry.label);
+
+describe('generateDocsId', () => {
+ it('strips sort prefixes from every path segment', () => {
+ assert.equal(
+ generateDocsId({ entry: 'Users Guide/04.Image Generation/01.introduction.mdx', data: {} }),
+ 'users-guide/image-generation/introduction'
+ );
+ });
+
+ it('prefers a frontmatter slug, but ignores an empty one', () => {
+ assert.equal(generateDocsId({ entry: '01.a.mdx', data: { slug: 'custom/path' } }), 'custom/path');
+ assert.equal(generateDocsId({ entry: '01.a.mdx', data: { slug: '' } }), 'a');
+ });
+});
+
+describe('sortAndRelabel', () => {
+ it('orders prefixed siblings by prefix, keeps unprefixed ones after them in order, and strips group labels', () => {
+ const fileNames = new Map([
+ ['guide/b', 'b.mdx'],
+ ['guide/intro', '01.intro.mdx'],
+ ['guide/a', 'a.mdx'],
+ ['guide/setup', '02.setup.mdx'],
+ ]);
+ const entries = [
+ { ...link('guide/b'), autogenerate: { directory: 'guide' } },
+ { ...link('guide/setup'), autogenerate: { directory: 'guide' } },
+ { ...link('guide/a'), autogenerate: { directory: 'guide' } },
+ { ...link('guide/intro'), autogenerate: { directory: 'guide' } },
+ ];
+ assert.equal(sortAndRelabel(entries, fileNames, hrefToId), true);
+ assert.deepEqual(labels(entries), ['intro', 'setup', 'b', 'a']);
+ });
+
+ it('sorts prefixed folders and recurses into them', () => {
+ const fileNames = new Map([
+ ['models/introduction', '01.introduction.mdx'],
+ ['models/zoo', 'zoo.mdx'],
+ ]);
+ const models = group('03.Models', 'Users Guide', [
+ { ...link('models/zoo'), autogenerate: { directory: 'models' } },
+ { ...link('models/introduction'), autogenerate: { directory: 'models' } },
+ ]);
+ const workbench = group('01.Workbench', 'Users Guide', []);
+ const entries = [models, workbench];
+ sortAndRelabel(entries, fileNames, hrefToId);
+ assert.deepEqual(labels(entries), ['Workbench', 'Models']);
+ assert.deepEqual(labels(models.entries), ['introduction', 'zoo']);
+ });
+
+ it('reports no change when the order is already right', () => {
+ const entries = [{ ...link('x/a'), autogenerate: { directory: 'x' } }];
+ assert.equal(sortAndRelabel(entries, new Map([['x/a', '01.a.mdx']]), hrefToId), false);
+ });
+});
+
+describe('fileDirectory', () => {
+ it('maps a file to its directory URL, independent of slugs and index pages', () => {
+ assert.equal(fileDirectory('src/content/docs/Users Guide/03.Models/Local Models/krea-2.mdx'), 'users-guide/models/local-models');
+ assert.equal(fileDirectory('src/content/docs/development/Documentation/index.mdx'), 'development/documentation');
+ assert.equal(fileDirectory('src/content/docs/index.mdx'), '');
+ });
+});
+
+describe('selectCrossListings', () => {
+ const docs = [
+ { id: 'video/wan', data: { alsoListedIn: ['/models/local/'] } },
+ { id: 'video/hidden', data: { alsoListedIn: ['models/local'], sidebar: { hidden: true } } },
+ { id: 'video/draft', data: { alsoListedIn: ['models/local'], draft: true } },
+ { id: 'video/plain', data: {} },
+ ];
+
+ it('normalizes directories and skips hidden pages', () => {
+ assert.deepEqual(selectCrossListings(docs, false), [
+ { id: 'video/wan', directory: 'models/local' },
+ { id: 'video/draft', directory: 'models/local' },
+ ]);
+ });
+
+ it('also skips drafts in production, where Starlight leaves them out of the sidebar', () => {
+ assert.deepEqual(selectCrossListings(docs, true), [{ id: 'video/wan', directory: 'models/local' }]);
+ });
+});
+
+describe('addCrossListings', () => {
+ const makeSidebar = () => [
+ group('Models', 'models', [
+ link('models/local/anima', 'Anima'),
+ link('models/local/sdxl', 'SDXL'),
+ group('Nested', 'models/local/nested', [link('models/local/nested/x', 'X')]),
+ ]),
+ group('Video', 'video', [link('video/ltx', 'LTX-2', true), link('video/wan', 'Wan 2.2')]),
+ ];
+ const directories = new Map([
+ ['models/local/anima', 'models/local'],
+ ['models/local/sdxl', 'models/local'],
+ ['models/local/nested/x', 'models/local/nested'],
+ ['video/ltx', 'video'],
+ ['video/wan', 'video'],
+ ]);
+
+ it('inserts copies alphabetically, before subgroups, without the current-page state', () => {
+ const sidebar = makeSidebar();
+ const listings = [
+ { id: 'video/wan', directory: 'models/local' },
+ { id: 'video/ltx', directory: 'models/local' },
+ ];
+ assert.equal(addCrossListings(sidebar, listings, directories, hrefToId), true);
+ const models = sidebar[0].entries;
+ assert.deepEqual(labels(models), ['Anima', 'LTX-2', 'SDXL', 'Wan 2.2', 'Nested']);
+ const ltxCopy = models[1];
+ assert.equal(ltxCopy.isCurrent, false);
+ assert.ok(CROSS_LISTED_ATTR in ltxCopy.attrs);
+ // The original keeps its state and gains no marker.
+ assert.equal(sidebar[1].entries[0].isCurrent, true);
+ assert.ok(!(CROSS_LISTED_ATTR in sidebar[1].entries[0].attrs));
+ });
+
+ it('matches the target group by file directory, not by URL', () => {
+ // A custom slug moves the page's URL out of its folder; the folder still decides its group.
+ const sidebar = [group('Docs', 'docs', [link('elsewhere/page', 'Page')]), group('Video', 'video', [link('video/wan', 'Wan')])];
+ const dirs = new Map([
+ ['elsewhere/page', 'docs/folder'],
+ ['video/wan', 'video'],
+ ]);
+ addCrossListings(sidebar, [{ id: 'video/wan', directory: 'docs/folder' }], dirs, hrefToId);
+ assert.deepEqual(labels(sidebar[0].entries), ['Page', 'Wan']);
+ });
+
+ it('does nothing without listings', () => {
+ assert.equal(addCrossListings(makeSidebar(), [], directories, hrefToId), false);
+ });
+
+ it('fails loudly on misconfiguration', () => {
+ assert.throws(
+ () => addCrossListings(makeSidebar(), [{ id: 'video/missing', directory: 'models/local' }], directories, hrefToId),
+ /has no sidebar link/
+ );
+ assert.throws(
+ () => addCrossListings(makeSidebar(), [{ id: 'video/wan', directory: 'video' }], directories, hrefToId),
+ /its own directory/
+ );
+ assert.throws(
+ () => addCrossListings(makeSidebar(), [{ id: 'video/wan', directory: 'models' }], directories, hrefToId),
+ /no sidebar group with pages/
+ );
+ });
+
+ it('honours a deployment base path', () => {
+ const baseHrefToId = makeHrefToId('/InvokeAI/');
+ const sidebar = [
+ group('Models', 'models', [{ ...link('models/local/sdxl', 'SDXL'), href: '/InvokeAI/models/local/sdxl/' }]),
+ group('Video', 'video', [{ ...link('video/wan', 'Wan'), href: '/InvokeAI/video/wan/' }]),
+ ];
+ addCrossListings(sidebar, [{ id: 'video/wan', directory: 'models/local' }], directories, baseHrefToId);
+ assert.deepEqual(labels(sidebar[0].entries), ['SDXL', 'Wan']);
+ });
+});
+
+describe('paginate', () => {
+ const sidebar = () => {
+ const entries = [
+ group('Models', 'models', [link('models/a', 'A'), link('models/b', 'B')]),
+ group('Video', 'video', [link('video/wan', 'Wan', true), link('video/ltx', 'LTX')]),
+ ];
+ // Cross-listed copies right before and after the current page, which pagination must step over.
+ const copy = (id, label) => ({ ...link(id, label), attrs: { [CROSS_LISTED_ATTR]: '' } });
+ entries[1].entries.splice(0, 0, copy('models/a', 'A'));
+ entries[1].entries.splice(2, 0, copy('models/b', 'B'));
+ return entries;
+ };
+
+ it('follows sidebar order and skips cross-listed copies', () => {
+ const { prev, next } = paginate(sidebar(), {});
+ assert.equal(prev.href, '/models/b/');
+ assert.ok(!(CROSS_LISTED_ATTR in prev.attrs));
+ assert.equal(next.label, 'LTX');
+ });
+
+ it('applies prev/next frontmatter', () => {
+ const { prev, next } = paginate(sidebar(), { prev: false, next: 'Onward' });
+ assert.equal(prev, undefined);
+ assert.equal(next.label, 'Onward');
+ assert.equal(next.href, '/video/ltx/');
+ const custom = paginate(sidebar(), { next: { link: '/elsewhere/', label: 'Elsewhere' } });
+ assert.equal(custom.next.href, '/elsewhere/');
+ });
+
+ it('returns null when the current page is not in the sidebar', () => {
+ assert.equal(paginate([group('Models', 'models', [link('models/a')])], {}), null);
+ });
+});
diff --git a/docs/src/route-data.ts b/docs/src/route-data.ts
index 0efa13ef67..9f6959c602 100644
--- a/docs/src/route-data.ts
+++ b/docs/src/route-data.ts
@@ -1,28 +1,16 @@
import { getCollection } from 'astro:content';
-import { defineRouteMiddleware, type StarlightRouteData } from '@astrojs/starlight/route-data';
+import { defineRouteMiddleware } from '@astrojs/starlight/route-data';
-import { generateDocsId, getSortPrefix, stripSortPrefix } from './lib/sort-prefix.mjs';
+import {
+ addCrossListings,
+ fileDirectory,
+ makeHrefToId,
+ paginate,
+ selectCrossListings,
+ sortAndRelabel,
+} from './lib/sidebar.mjs';
-type SidebarEntry = StarlightRouteData['sidebar'][number];
-type SidebarLink = Extract<SidebarEntry, { type: 'link' }>;
-type PrevNextConfig = StarlightRouteData['entry']['data']['prev'];
-
-const trimSlashes = (path: string) => path.replace(/^\/+|\/+$/g, '');
-const basePath = trimSlashes(import.meta.env.BASE_URL);
-const parentDirectory = (id: string) => id.slice(0, Math.max(id.lastIndexOf('/'), 0));
-
-type CrossListing = { id: string; directory: string };
-
-/** Marks the copy of a link that a page's `alsoListedIn` frontmatter adds; pagination skips these. */
-const CROSS_LISTED_ATTR = 'data-cross-listed';
-
-/** A docs file's directory as a URL path, e.g. `Users Guide/03.Models/x.mdx` -> `users-guide/models`. */
-const fileDirectory = (filePath: string | undefined) => {
- const relative = filePath?.split('content/docs/').pop() ?? '';
- const directory = relative.slice(0, Math.max(relative.lastIndexOf('/'), 0));
- // A placeholder file name, because generateDocsId drops a trailing extension-like segment.
- return directory ? parentDirectory(generateDocsId({ entry: `${directory}/page.md`, data: {} })) : '';
-};
+const hrefToId = makeHrefToId(import.meta.env.BASE_URL);
const getDocsIndex = async () => {
const docs = await getCollection('docs');
@@ -31,140 +19,22 @@ const getDocsIndex = async () => {
fileNames: new Map(docs.map((doc) => [doc.id, doc.filePath?.split('/').pop() ?? ''])),
/** Maps each docs page id to its file's directory, which a custom slug or an index page's id does not show. */
directories: new Map(docs.map((doc) => [doc.id, fileDirectory(doc.filePath)])),
- // Starlight leaves draft (in production) and hidden pages out of the sidebar, so there is nothing to copy.
- crossListings: docs
- .filter((doc) => !doc.data.sidebar.hidden && !(doc.data.draft && import.meta.env.PROD))
- .flatMap((doc): CrossListing[] =>
- (doc.data.alsoListedIn ?? []).map((directory) => ({
- id: doc.id,
- directory: trimSlashes(directory),
- }))
- ),
+ crossListings: selectCrossListings(docs, import.meta.env.PROD),
};
};
-const hrefToId = (href: string) => {
- const path = trimSlashes(href);
- return basePath && path.startsWith(`${basePath}/`) ? path.slice(basePath.length + 1) : path;
-};
-
-/**
- * Starlight orders autogenerated entries by frontmatter `sidebar.order`, then by id, and ids no longer carry
- * the prefix. Reorder siblings generated from the same directory by prefix (unprefixed ones follow, in
- * Starlight's order) and strip the prefix from directory labels. Other entries keep their positions.
- */
-const sortAndRelabel = (entries: SidebarEntry[], fileNames: Map<string, string>): boolean => {
- let changed = false;
- const sortKey = (entry: SidebarEntry) =>
- getSortPrefix(entry.type === 'group' ? entry.label : (fileNames.get(hrefToId(entry.href)) ?? '')) ??
- Number.POSITIVE_INFINITY;
-
- const slotsByDirectory = new Map<string, number[]>();
- entries.forEach((entry, index) => {
- const directory = 'autogenerate' in entry ? entry.autogenerate?.directory : undefined;
- if (directory !== undefined) slotsByDirectory.set(directory, [...(slotsByDirectory.get(directory) ?? []), index]);
- });
- for (const slots of slotsByDirectory.values()) {
- const sorted = slots.map((index) => entries[index]!).sort((a, b) => sortKey(a) - sortKey(b));
- slots.forEach((slot, i) => {
- if (entries[slot] !== sorted[i]) changed = true;
- entries[slot] = sorted[i]!;
- });
- }
-
- for (const entry of entries) {
- if (entry.type !== 'group') continue;
- if ('autogenerate' in entry && entry.autogenerate) entry.label = stripSortPrefix(entry.label);
- if (sortAndRelabel(entry.entries, fileNames)) changed = true;
- }
- return changed;
-};
-
-const flattenLinks = (entries: SidebarEntry[]): SidebarLink[] =>
- entries.flatMap((entry) => (entry.type === 'group' ? flattenLinks(entry.entries) : [entry]));
-
-/**
- * The group autogenerated from a docs directory: the one whose own links are pages in that directory. A directory
- * holding only subdirectories cannot be found this way.
- */
-const findDirectoryGroup = (
- entries: SidebarEntry[],
- directory: string,
- directories: Map<string, string>
-): SidebarEntry[] | undefined => {
- if (entries.some((entry) => entry.type === 'link' && directories.get(hrefToId(entry.href)) === directory)) {
- return entries;
- }
- for (const entry of entries) {
- const found = entry.type === 'group' ? findDirectoryGroup(entry.entries, directory, directories) : undefined;
- if (found) return found;
- }
- return undefined;
-};
-
-/**
- * Autogenerated sidebars list each page once, under its own directory. Add a copy of each cross-listed page's link
- * to the group of every directory its `alsoListedIn` frontmatter names, placed alphabetically by label among that
- * group's links (so target directories should order their pages alphabetically). A misconfigured listing fails the
- * build.
- */
-const addCrossListings = (
- sidebar: SidebarEntry[],
- crossListings: CrossListing[],
- directories: Map<string, string>
-): boolean => {
- if (crossListings.length === 0) return false;
- const linksById = new Map(flattenLinks(sidebar).map((link) => [hrefToId(link.href), link]));
- for (const { id, directory } of crossListings) {
- const link = linksById.get(id);
- if (!link) throw new Error(`Cross-listed page "${id}" has no sidebar link.`);
- if (directories.get(id) === directory) throw new Error(`Page "${id}" is cross-listed in its own directory.`);
- const group = findDirectoryGroup(sidebar, directory, directories);
- if (!group) {
- throw new Error(`Page "${id}" is cross-listed in "${directory}", which has no sidebar group with pages.`);
- }
- // Before the first link that sorts after it, else before the group's first subgroup, else last.
- const laterLink = group.findIndex(
- (entry) => entry.type === 'link' && entry.label.localeCompare(link.label, 'en', { sensitivity: 'base' }) > 0
- );
- const firstGroup = group.findIndex((entry) => entry.type === 'group');
- const index = laterLink !== -1 ? laterLink : firstGroup !== -1 ? firstGroup : group.length;
- // The page's own link carries the current-page state, so the copy never does.
- const copy: SidebarLink = {
- ...link,
- isCurrent: false,
- attrs: { ...link.attrs, [CROSS_LISTED_ATTR]: '' },
- };
- group.splice(index, 0, copy);
- }
- return true;
-};
-
-/** Mirrors Starlight's handling of the frontmatter `prev`/`next` options for a regenerated neighbour link. */
-const applyPrevNextConfig = (link: SidebarLink | undefined, config: PrevNextConfig): SidebarLink | undefined => {
- if (config === false) return undefined;
- if (config === undefined || config === true) return link;
- if (typeof config === 'string') return link && { ...link, label: config };
- if (link) return { ...link, label: config.label ?? link.label, href: config.link ?? link.href, attrs: {} };
- if (config.link && config.label) {
- return { type: 'link', href: config.link, label: config.label, isCurrent: false, badge: undefined, attrs: {} };
- }
- return undefined;
-};
-
export const onRequest = defineRouteMiddleware(async (context) => {
const route = context.locals.starlightRoute;
// Starlight hands each render its own copy of the sidebar.
+ const { sidebar } = route;
const { fileNames, directories, crossListings } = await getDocsIndex();
- const reordered = sortAndRelabel(route.sidebar, fileNames);
- const crossListed = addCrossListings(route.sidebar, crossListings, directories);
+ const reordered = sortAndRelabel(sidebar, fileNames, hrefToId);
+ const crossListed = addCrossListings(sidebar, crossListings, directories, hrefToId);
if (!reordered && !crossListed) return;
// Starlight derived prev/next links before the reorder. This site keeps the default `pagination: true`.
- const links = flattenLinks(route.sidebar).filter((link) => !(CROSS_LISTED_ATTR in link.attrs));
- const current = links.findIndex((link) => link.isCurrent);
- if (current === -1) return;
- const { data } = route.entry;
- route.pagination.prev = applyPrevNextConfig(links[current - 1], data.prev);
- route.pagination.next = applyPrevNextConfig(links[current + 1], data.next);
+ const pagination = paginate(sidebar, route.entry.data);
+ if (!pagination) return;
+ route.pagination.prev = pagination.prev;
+ route.pagination.next = pagination.next;
});