Skip to content

Commit

Permalink
Setup all matching links .selected on page load and after a route call.
Browse files Browse the repository at this point in the history
Closes #158
  • Loading branch information
tipiirai committed Jan 15, 2024
1 parent 8daccb1 commit 515d59b
Showing 1 changed file with 25 additions and 12 deletions.
37 changes: 25 additions & 12 deletions packages/nuekit/src/browser/page-router.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@

// Router for multi-page applications
const is_browser = typeof window == 'object'

export async function loadPage(path) {
dispatchEvent(new Event('before:route'))
Expand Down Expand Up @@ -43,6 +42,7 @@ export async function loadPage(path) {

loadCSS(paths, () => {
scrollTo(0, 0)
setSelected(path)
dispatchEvent(new Event('route'))
})
}
Expand Down Expand Up @@ -75,24 +75,37 @@ export function onclick(root, fn) {
})
}

// TODO: switch to aria-selected
export function setSelected(path, className='selected') {
const el = $(`[href="${path}"]`)

// remove old selections
$$('.' + className).forEach(el => el.classList.remove(className))
el?.classList.add(className)

// add new ones
$$(`[href="${path}"]`).forEach(el => el.classList.add(className))
}


// Fix: window.onpopstate, event.state == null?
// https://stackoverflow.com/questions/11092736/window-onpopstate-event-state-null
is_browser && history.pushState({ path: location.pathname }, 0)
// browser environment
const is_browser = typeof window == 'object'

if (is_browser) {

// Fix: window.onpopstate, event.state == null?
// https://stackoverflow.com/questions/11092736/window-onpopstate-event-state-null
history.pushState({ path: location.pathname }, 0)

// autoroute / document clicks
onclick(document, async path => {
await loadPage(path)
history.pushState({ path }, 0, path)
})

// initial selected
setSelected(location.pathname)
}


// autoroute / document clicks
is_browser && onclick(document, (path) => {
loadPage(path)
history.pushState({ path }, 0, path)
setSelected(path)
})


/* -------- utilities ---------- */
Expand Down

0 comments on commit 515d59b

Please sign in to comment.