Skip to content

Commit

Permalink
fix(client): handle empty hash in links (#2738)
Browse files Browse the repository at this point in the history
  • Loading branch information
brc-dd committed Aug 6, 2023
1 parent e54eea3 commit c6c983e
Showing 1 changed file with 21 additions and 23 deletions.
44 changes: 21 additions & 23 deletions src/client/app/router.ts
Expand Up @@ -74,11 +74,7 @@ export function createRouter(
href = url.pathname + url.search + url.hash
}
}
if (inBrowser && href !== location.href) {
// save scroll position before changing url
history.replaceState({ scrollPosition: window.scrollY }, document.title)
history.pushState(null, '', href)
}
updateHistory(href)
await loadPage(href)
await router.onAfterRouteChanged?.(href)
}
Expand Down Expand Up @@ -211,15 +207,18 @@ export function createRouter(
search === currentUrl.search
) {
// scroll between hash anchors in the same page
// avoid duplicate history entries when the hash is same
if (hash !== currentUrl.hash) {
history.pushState(null, '', hash)
// still emit the event so we can listen to it in themes
window.dispatchEvent(new Event('hashchange'))
}
if (hash) {
// avoid duplicate history entries when the hash is same
if (hash !== currentUrl.hash) {
history.pushState(null, '', hash)
// still emit the event so we can listen to it in themes
window.dispatchEvent(new Event('hashchange'))
}
// use smooth scroll when clicking on header anchor links
scrollTo(link, hash, link.classList.contains('header-anchor'))
} else {
updateHistory(href)
window.scrollTo(0, 0)
}
} else {
go(href)
Expand Down Expand Up @@ -292,20 +291,11 @@ export function scrollTo(el: Element, hash: string, smooth = false) {
target.getBoundingClientRect().top -
offset +
targetPadding
// only smooth scroll if distance is smaller than screen height.
function scrollToTarget() {
if (
!smooth ||
Math.abs(targetTop - window.scrollY) > window.innerHeight
) {
// only smooth scroll if distance is smaller than screen height.
if (!smooth || Math.abs(targetTop - window.scrollY) > window.innerHeight)
window.scrollTo(0, targetTop)
} else {
window.scrollTo({
left: 0,
top: targetTop,
behavior: 'smooth'
})
}
else window.scrollTo({ left: 0, top: targetTop, behavior: 'smooth' })
}
requestAnimationFrame(scrollToTarget)
}
Expand Down Expand Up @@ -338,3 +328,11 @@ function shouldHotReload(payload: PageDataPayload): boolean {
.slice(siteDataRef.value.base.length - 1)
return payloadPath === locationPath
}

function updateHistory(href: string) {
if (inBrowser && href !== location.href) {
// save scroll position before changing url
history.replaceState({ scrollPosition: window.scrollY }, document.title)
history.pushState(null, '', href)
}
}

0 comments on commit c6c983e

Please sign in to comment.