Skip to content

Commit 5589f5e

Browse files
authored
preserve Azure and Snowflake sidebar context on detail pages (#475)
1 parent d5fd2a1 commit 5589f5e

File tree

1 file changed

+64
-1
lines changed

1 file changed

+64
-1
lines changed

src/routeData.ts

Lines changed: 64 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,70 @@
11
import { defineRouteMiddleware } from '@astrojs/starlight/route-data';
22

33
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+
}
568

669
const overviewItem = starlightRoute.toc?.items[0];
770
if (overviewItem) overviewItem.text = 'Back to top';

0 commit comments

Comments
 (0)