Skip to content

Commit

Permalink
chore: tweak hashchange emitting a bit
Browse files Browse the repository at this point in the history
  • Loading branch information
brc-dd committed Mar 6, 2024
1 parent 2df9bab commit 6c0125b
Showing 1 changed file with 6 additions and 7 deletions.
13 changes: 6 additions & 7 deletions src/client/app/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,16 +64,11 @@ export function createRouter(
}

async function go(href: string = inBrowser ? location.href : '/') {
const currentHash = inBrowser ? location.hash : ''
href = normalizeHref(href)
if ((await router.onBeforeRouteChange?.(href)) === false) return
updateHistory(href)
await loadPage(href)
await router.onAfterRouteChanged?.(href)
// do after the route is changed so location.hash in theme code is the new hash
if (new URL(href, fakeHost).hash !== currentHash) {
window.dispatchEvent(new Event('hashchange'))
}
}

let latestPendingPath: string | null = null
Expand Down Expand Up @@ -212,7 +207,7 @@ export function createRouter(
// use smooth scroll when clicking on header anchor links
scrollTo(link, hash, link.classList.contains('header-anchor'))
} else {
updateHistory(href)
updateHistory(href, false) // already emitted hashchange above
window.scrollTo(0, 0)
}
} else {
Expand Down Expand Up @@ -305,11 +300,15 @@ function shouldHotReload(payload: PageDataPayload): boolean {
return payloadPath === locationPath
}

function updateHistory(href: string) {
function updateHistory(href: string, emitHashChange = true) {
if (inBrowser && normalizeHref(href) !== normalizeHref(location.href)) {
const currentHash = location.hash
// save scroll position before changing url
history.replaceState({ scrollPosition: window.scrollY }, document.title)
history.pushState(null, '', href)
if (emitHashChange && new URL(href, fakeHost).hash !== currentHash) {
window.dispatchEvent(new Event('hashchange'))
}
}
}

Expand Down

0 comments on commit 6c0125b

Please sign in to comment.