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.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
import { slug } from 'github-slugger';
import { splitSitePath } from '../config/locales.mjs';
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 the English docs page id, removing the deployment base path and any locale: a
* translation mirrors its English file's name and directory, so English data drives every locale's sidebar. The site
* root itself maps to 'index', the id `generateDocsId` gives the root `index.mdx` (only a trailing `/index` drops).
* @param {string} baseUrl
* @returns {(href: string) => string}
*/
export const makeHrefToId = (baseUrl) => (href) => {
const path = splitSitePath(href, baseUrl)?.path;
if (path === undefined) return trimSlashes(href);
return path === '/' ? 'index' : trimSlashes(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
*/
export const sortAndRelabel = (entries, fileNames, hrefToId) => {
/** @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) => {
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);
sortAndRelabel(entry.entries, fileNames, hrefToId);
}
};
/**
* The UI string key of a sidebar group's label: the label's slug, which is also the last segment of the URL path of
* the directory a group is generated from, e.g. `sidebar.group.image-generation`.
* @param {string} label the English label
*/
export const sidebarGroupKey = (label) => `sidebar.group.${slug(label)}`;
/**
* Translates the labels of groups at every depth, directory-derived ones included. A label without a UI string stays.
* @param {SidebarEntry[]} entries
* @param {{ (key: string): string, exists: (key: string) => boolean }} t
*/
export const translateGroupLabels = (entries, t) => {
for (const entry of entries) {
if (entry.type !== 'group') continue;
const key = sidebarGroupKey(entry.label);
if (t.exists(key)) entry.label = t(key);
translateGroupLabels(entry.entries, t);
}
};
/**
* @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
*/
export const addCrossListings = (sidebar, crossListings, directories, hrefToId) => {
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]: '' } });
}
};
/**
* 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),
};
};
/**
* The labels of the groups enclosing the current page's link, outermost first, and the link itself, for a breadcrumb.
* `undefined` when the current page is not in the sidebar.
* @param {SidebarEntry[]} entries
* @returns {{ groups: string[], link: SidebarLink } | undefined}
*/
export const findCurrentTrail = (entries) => {
for (const entry of entries) {
if (entry.type === 'link') {
if (entry.isCurrent) return { groups: [], link: entry };
continue;
}
const trail = findCurrentTrail(entry.entries);
if (trail) return { groups: [entry.label, ...trail.groups], link: trail.link };
}
return undefined;
};
/**
* The docs directory, as a URL path, that a sidebar section was generated from: the deepest directory holding all of
* its pages. Cross-listed copies belong to other directories and are ignored. `undefined` for a section without pages.
* @param {Extract<SidebarEntry, { type: 'group' }>} group
* @param {Map<string, string>} directories page id -> file directory
* @param {(href: string) => string} hrefToId
*/
export const sectionDirectory = (group, directories, hrefToId) => {
const paths = flattenLinks(group.entries)
.filter((link) => !(CROSS_LISTED_ATTR in link.attrs))
.map((link) => directories.get(hrefToId(link.href)))
.filter((directory) => directory !== undefined)
.map((directory) => directory.split('/'));
if (paths.length === 0) return undefined;
const [first, ...rest] = paths;
let length = first.length;
for (const path of rest) {
while (length > 0 && path.slice(0, length).join('/') !== first.slice(0, length).join('/')) length--;
}
return first.slice(0, length).join('/');
};