The best way to control Claude Code, Codex and more from any computer or phone

main
ts 79 lines 2.7 KB
Raw
1 /// <reference types="@astrojs/starlight/locals" />
2 import { defineRouteMiddleware } from "@astrojs/starlight/route-data";
3 import type { StarlightRouteData } from "@astrojs/starlight/route-data";
4 import { activeTab } from "./docs-tabs";
5
6 type SidebarItem = StarlightRouteData["sidebar"][number];
7 type SidebarLink = Extract<SidebarItem, { type: "link" }>;
8
9 /**
10 * The config sidebar in `astro.config.mjs` is one top-level group per docs
11 * tab (see `docs-tabs.ts`). This middleware swaps the whole-site sidebar for
12 * just the active tab's entries so the sidebar only ever navigates within
13 * the current tab, and recomputes prev/next pagination so it never walks
14 * across a tab boundary.
15 *
16 * Blog routes are skipped — starlight-blog owns their sidebar (re-bucketed
17 * by `blog-sidebar.ts`).
18 */
19 export const onRequest = defineRouteMiddleware(async (context, next) => {
20 await next();
21
22 const pathname = context.url.pathname;
23 if (pathname === "/blog" || pathname.startsWith("/blog/")) return;
24
25 // TODO: fix types
26 const { starlightRoute } = context.locals as Record<string, any>;
27 const tab = activeTab(pathname);
28 const group = starlightRoute.sidebar.find(
29 (item: any): item is Extract<SidebarItem, { type: "group" }> =>
30 item.type === "group" && item.label === tab.label,
31 );
32 if (!group) return;
33
34 starlightRoute.sidebar = group.entries;
35
36 const links = flattenLinks(group.entries);
37 const index = links.findIndex((link) => link.isCurrent);
38 const { prev, next: nextLink } = starlightRoute.entry.data;
39 starlightRoute.pagination = {
40 prev: override(prev, index > 0 ? links[index - 1] : undefined),
41 next: override(nextLink, index !== -1 ? links[index + 1] : undefined),
42 };
43 });
44
45 /**
46 * Apply a page's `prev` / `next` frontmatter to the sidebar-derived link, the
47 * same way Starlight's own pagination does: `false` removes the link, a
48 * string relabels it, and `{ link, label }` replaces it outright.
49 */
50 function override(
51 config: StarlightRouteData["entry"]["data"]["prev"],
52 link: SidebarLink | undefined,
53 ): SidebarLink | undefined {
54 if (config === undefined || config === true) return link;
55 if (config === false) return undefined;
56 if (typeof config === "string") {
57 return link ? { ...link, label: config } : undefined;
58 }
59 const href = config.link ?? link?.href;
60 const label = config.label ?? link?.label;
61 if (!href || !label) return link;
62 return {
63 type: "link",
64 label,
65 href,
66 isCurrent: false,
67 badge: undefined,
68 attrs: {},
69 };
70 }
71
72 function flattenLinks(items: SidebarItem[]): SidebarLink[] {
73 const links: SidebarLink[] = [];
74 for (const item of items) {
75 if (item.type === "link") links.push(item);
76 else links.push(...flattenLinks(item.entries));
77 }
78 return links;
79 }