Skip to content

Commit 18540af

Browse files
theletterfclaude
andcommitted
Expand nav to current page on direct URL load
Walk up the DOM from the matched link and check each ancestor collapsible checkbox so the sidebar reveals the active page location when navigating directly to a URL. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
1 parent b7172c6 commit 18540af

File tree

1 file changed

+24
-2
lines changed

1 file changed

+24
-2
lines changed

src/Elastic.Documentation.Site/Assets/pages-nav-v2.ts

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,8 +42,6 @@ function initAccordion(nav: HTMLElement) {
4242

4343
/**
4444
* Mark the current page's nav link with the "current" CSS class.
45-
* Unlike the V1 nav, we do NOT auto-expand parent sections —
46-
* progressive disclosure keeps all sections collapsed until the user opens them.
4745
*/
4846
function markCurrentPage(nav: HTMLElement) {
4947
// Remove stale current markers
@@ -55,11 +53,35 @@ function markCurrentPage(nav: HTMLElement) {
5553
)
5654
}
5755

56+
/**
57+
* Expand all ancestor collapsible sections that contain the current page link,
58+
* so that navigating directly to a URL reveals its location in the sidebar.
59+
*/
60+
function expandToCurrentPage(nav: HTMLElement) {
61+
const pathname = window.location.pathname.replace(/\/$/, '')
62+
const link = nav.querySelector<HTMLElement>(
63+
`a[href="${pathname}"], a[href="${pathname}/"]`
64+
)
65+
if (!link) return
66+
67+
let el: Element | null = link.parentElement
68+
while (el && el !== nav) {
69+
if (el.matches('li')) {
70+
const cb = el.querySelector<HTMLInputElement>(
71+
':scope > .peer input[type=checkbox]'
72+
)
73+
if (cb) cb.checked = true
74+
}
75+
el = el.parentElement
76+
}
77+
}
78+
5879
/**
5980
* Initialize all V2 nav behaviours on the given sidebar element.
6081
* Call this on every htmx:load when [data-nav-v2] is present.
6182
*/
6283
export function initNavV2(nav: HTMLElement) {
6384
initAccordion(nav)
6485
markCurrentPage(nav)
86+
expandToCurrentPage(nav)
6587
}

0 commit comments

Comments
 (0)