import type { StarlightRouteData } from "@astrojs/starlight/route-data"; import { AstroError } from "astro/errors"; type SidebarEntry = StarlightRouteData["sidebar"][number]; type SidebarGroup = Extract; export interface MultiSidebarGroup { /** Label of the top-level group backing this sidebar. */ label: string; /** Optional badge rendered next to the label in the switcher. */ badge: SidebarGroup["badge"]; /** Entries rendered when this sidebar is selected. */ entries: SidebarEntry[]; /** Whether this sidebar contains the page being rendered. */ isCurrent: boolean; /** DOM id of the switcher control for this sidebar. */ tabId: string; /** DOM id of the panel holding this sidebar's entries. */ panelId: string; } /** Recursively check whether a sidebar entry contains the page being rendered. */ function containsCurrentPage(entry: SidebarEntry): boolean { return entry.type === "link" ? entry.isCurrent : entry.entries.some(containsCurrentPage); } /** * Turn the route's sidebar into one switchable sidebar per top-level group. * * Unlike `@lorenzo_lewis/starlight-utils`, this runs while the `Sidebar` component renders instead * of in a route middleware, so it always sees the sidebar every other plugin has finished building. * That matters for `starlight-versions`, whose middleware narrows the sidebar to the current * version and cannot be ordered against a second sidebar-rewriting middleware. */ export function getMultiSidebarGroups(sidebar: StarlightRouteData["sidebar"]): MultiSidebarGroup[] { const groups = sidebar.map((entry, index) => { if (entry.type !== "group") { throw new AstroError( `\`${entry.label}\` cannot be used with multi-sidebar.`, "Each top-level `sidebar` item in the Starlight config must be a group or autogenerated when the " + "`multiSidebar` option of `starlight-theme-celestia` is enabled.\n" + "See https://starlight.astro.build/guides/sidebar/#groups and " + "https://starlight.astro.build/guides/sidebar/#autogenerated-groups for more details.", ); } return { label: entry.label, badge: entry.badge, entries: entry.entries, isCurrent: containsCurrentPage(entry), tabId: `celestia-sidebar-tab-${index}`, panelId: `celestia-sidebar-panel-${index}`, }; }); // Pages outside every sidebar, such as the site index, fall back to the first sidebar. const first = groups[0]; if (first && !groups.some((group) => group.isCurrent)) { first.isCurrent = true; } return groups; }