pr_01m47d15m3e54sn21z27rpy5n9/apps/docs/src/route-data.ts
| 1 | import { defineRouteMiddleware } from '@astrojs/starlight/route-data'; |
| 2 | |
| 3 | import { tabFor } from './tabs'; |
| 4 | |
| 5 | type Entry = { type: string; href?: string; entries?: Entry[] }; |
| 6 | |
| 7 | /** The slug of a group's first page on this site, such as `reference/api`. */ |
| 8 | function firstSlug(entries: Entry[]): string | undefined { |
| 9 | for (const entry of entries) { |
| 10 | if (entry.type === 'group') { |
| 11 | const slug = firstSlug(entry.entries ?? []); |
| 12 | if (slug !== undefined) return slug; |
| 13 | } else if (entry.href?.startsWith('/') && !entry.href.startsWith('//')) { |
| 14 | return entry.href.replace(/^\/|\/$/g, ''); |
| 15 | } |
| 16 | } |
| 17 | return undefined; |
| 18 | } |
| 19 | |
| 20 | /** |
| 21 | * Each page's sidebar holds only its tab's groups: those whose pages |
| 22 | * belong to the same tab. Groups are told apart by their pages, not their |
| 23 | * labels, since a guide group and an API group can share a name. |
| 24 | */ |
| 25 | export const onRequest = defineRouteMiddleware((context) => { |
| 26 | const route = context.locals.starlightRoute; |
| 27 | const tab = tabFor(route.id); |
| 28 | route.sidebar = route.sidebar.filter((entry) => { |
| 29 | if (entry.type !== 'group') return false; |
| 30 | const slug = firstSlug(entry.entries as Entry[]); |
| 31 | return slug !== undefined && tabFor(slug) === tab; |
| 32 | }); |
| 33 | }); |