import { defineRouteMiddleware } from "@astrojs/starlight/route-data";
import type { StarlightRouteData } from "@astrojs/starlight/route-data";
// starlight always seeds the table of contents with a link back to the page
// title, so `toc` is truthy even on pages with no headings and the "on this
// page" overview renders empty. drop it in that case.
const PAGE_TITLE_ID = "_top";
type TocItem = NonNullable<StarlightRouteData["toc"]>["items"][number];
function hasSections(items: TocItem[]): boolean {
return items.some(
(item) => item.slug !== PAGE_TITLE_ID || hasSections(item.children),
);
}
export const onRequest = defineRouteMiddleware((context) => {
const route = context.locals.starlightRoute;
if (route.toc && !hasSections(route.toc.items)) {
route.toc = undefined;
}
});