|
1 | 1 | import { defineRouteMiddleware } from '@astrojs/starlight/route-data'; |
2 | 2 |
|
3 | 3 | export const onRequest = defineRouteMiddleware((context) => { |
4 | | - const { starlightRoute } = context.locals; |
| 4 | + const locals = context.locals as typeof context.locals & { |
| 5 | + starlightUtils?: { |
| 6 | + multiSidebar?: any[]; |
| 7 | + }; |
| 8 | + }; |
| 9 | + const { starlightRoute } = locals; |
| 10 | + |
| 11 | + const pathname = context.url.pathname.replace(/\/+$/, '') || '/'; |
| 12 | + const sidebarContextOverrides = [ |
| 13 | + { |
| 14 | + match: /^\/azure\/services\/[^/]+$/, |
| 15 | + sidebarLabel: 'Azure', |
| 16 | + currentLinkHref: '/azure/services/', |
| 17 | + }, |
| 18 | + { |
| 19 | + match: /^\/snowflake\/features\/[^/]+$/, |
| 20 | + sidebarLabel: 'Snowflake', |
| 21 | + currentLinkHref: '/snowflake/features/', |
| 22 | + }, |
| 23 | + ]; |
| 24 | + const sidebarContextOverride = sidebarContextOverrides.find(({ match }) => |
| 25 | + match.test(pathname) |
| 26 | + ); |
| 27 | + |
| 28 | + if (sidebarContextOverride) { |
| 29 | + const { sidebarLabel, currentLinkHref } = sidebarContextOverride; |
| 30 | + |
| 31 | + const markLinkCurrent = (entry: any): boolean => { |
| 32 | + if (entry.type === 'link' && entry.href === currentLinkHref) { |
| 33 | + entry.isCurrent = true; |
| 34 | + return true; |
| 35 | + } |
| 36 | + if (entry.type === 'group') { |
| 37 | + return entry.entries.some((nestedEntry: any) => markLinkCurrent(nestedEntry)); |
| 38 | + } |
| 39 | + return false; |
| 40 | + }; |
| 41 | + |
| 42 | + const resetGroupCurrentState = (entry: any) => { |
| 43 | + if (entry.type === 'link') { |
| 44 | + entry.isCurrent = false; |
| 45 | + return; |
| 46 | + } |
| 47 | + if (entry.type === 'group') { |
| 48 | + entry.entries.forEach((nestedEntry: any) => resetGroupCurrentState(nestedEntry)); |
| 49 | + } |
| 50 | + }; |
| 51 | + |
| 52 | + for (const entry of starlightRoute.sidebar) { |
| 53 | + if (entry.type !== 'group') continue; |
| 54 | + if (entry.label === sidebarLabel) { |
| 55 | + markLinkCurrent(entry); |
| 56 | + } else { |
| 57 | + resetGroupCurrentState(entry); |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + const multiSidebarData = locals.starlightUtils?.multiSidebar; |
| 62 | + if (Array.isArray(multiSidebarData)) { |
| 63 | + multiSidebarData.forEach((data: any) => { |
| 64 | + data.isCurrentSidebar = data.label?.label === sidebarLabel; |
| 65 | + }); |
| 66 | + } |
| 67 | + } |
5 | 68 |
|
6 | 69 | const overviewItem = starlightRoute.toc?.items[0]; |
7 | 70 | if (overviewItem) overviewItem.text = 'Back to top'; |
|
0 commit comments