Skip to content

Commit 6c0125b

Browse files
committed
chore: tweak hashchange emitting a bit
1 parent 2df9bab commit 6c0125b

File tree

1 file changed

+6
-7
lines changed

1 file changed

+6
-7
lines changed

Diff for: src/client/app/router.ts

+6-7
Original file line numberDiff line numberDiff line change
@@ -64,16 +64,11 @@ export function createRouter(
6464
}
6565

6666
async function go(href: string = inBrowser ? location.href : '/') {
67-
const currentHash = inBrowser ? location.hash : ''
6867
href = normalizeHref(href)
6968
if ((await router.onBeforeRouteChange?.(href)) === false) return
7069
updateHistory(href)
7170
await loadPage(href)
7271
await router.onAfterRouteChanged?.(href)
73-
// do after the route is changed so location.hash in theme code is the new hash
74-
if (new URL(href, fakeHost).hash !== currentHash) {
75-
window.dispatchEvent(new Event('hashchange'))
76-
}
7772
}
7873

7974
let latestPendingPath: string | null = null
@@ -212,7 +207,7 @@ export function createRouter(
212207
// use smooth scroll when clicking on header anchor links
213208
scrollTo(link, hash, link.classList.contains('header-anchor'))
214209
} else {
215-
updateHistory(href)
210+
updateHistory(href, false) // already emitted hashchange above
216211
window.scrollTo(0, 0)
217212
}
218213
} else {
@@ -305,11 +300,15 @@ function shouldHotReload(payload: PageDataPayload): boolean {
305300
return payloadPath === locationPath
306301
}
307302

308-
function updateHistory(href: string) {
303+
function updateHistory(href: string, emitHashChange = true) {
309304
if (inBrowser && normalizeHref(href) !== normalizeHref(location.href)) {
305+
const currentHash = location.hash
310306
// save scroll position before changing url
311307
history.replaceState({ scrollPosition: window.scrollY }, document.title)
312308
history.pushState(null, '', href)
309+
if (emitHashChange && new URL(href, fakeHost).hash !== currentHash) {
310+
window.dispatchEvent(new Event('hashchange'))
311+
}
313312
}
314313
}
315314

0 commit comments

Comments
 (0)