Skip to content

Commit

Permalink
fix(client): don't reload page on hash change (#3777)
Browse files Browse the repository at this point in the history
  • Loading branch information
brc-dd committed Apr 10, 2024
1 parent f65053c commit 74b725a
Showing 1 changed file with 10 additions and 4 deletions.
14 changes: 10 additions & 4 deletions src/client/app/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,8 @@ export function createRouter(
if ((await router.onBeforeRouteChange?.(href)) === false) return
if (inBrowser && href !== normalizeHref(location.href)) {
// save scroll position before changing url
history.replaceState({ scrollPosition: window.scrollY }, document.title)
history.pushState(null, '', href)
history.replaceState({ scrollPosition: window.scrollY }, '')
history.pushState({}, '', href)
}
await loadPage(href)
await router.onAfterRouteChanged?.(href)
Expand Down Expand Up @@ -111,7 +111,7 @@ export function createRouter(
if (actualPathname !== targetLoc.pathname) {
targetLoc.pathname = actualPathname
href = actualPathname + targetLoc.search + targetLoc.hash
history.replaceState(null, '', href)
history.replaceState({}, '', href)
}

if (targetLoc.hash && !scrollPosition) {
Expand Down Expand Up @@ -162,6 +162,9 @@ export function createRouter(
}

if (inBrowser) {
if (history.state === null) {
history.replaceState({}, '')
}
window.addEventListener(
'click',
(e) => {
Expand Down Expand Up @@ -203,7 +206,7 @@ export function createRouter(
// scroll between hash anchors in the same page
// avoid duplicate history entries when the hash is same
if (hash !== currentUrl.hash) {
history.pushState(null, '', href)
history.pushState({}, '', href)
// still emit the event so we can listen to it in themes
window.dispatchEvent(
new HashChangeEvent('hashchange', {
Expand All @@ -228,6 +231,9 @@ export function createRouter(
)

window.addEventListener('popstate', async (e) => {
if (e.state === null) {
return
}
await loadPage(
normalizeHref(location.href),
(e.state && e.state.scrollPosition) || 0
Expand Down

0 comments on commit 74b725a

Please sign in to comment.