From c6c983ed73a019027b452b3eaf0ee4b502d38818 Mon Sep 17 00:00:00 2001 From: Divyansh Singh <40380293+brc-dd@users.noreply.github.com> Date: Sun, 6 Aug 2023 15:42:58 +0530 Subject: [PATCH] fix(client): handle empty hash in links (#2738) --- src/client/app/router.ts | 44 +++++++++++++++++++--------------------- 1 file changed, 21 insertions(+), 23 deletions(-) diff --git a/src/client/app/router.ts b/src/client/app/router.ts index cbfc9e1460fe..4cbb7af65148 100644 --- a/src/client/app/router.ts +++ b/src/client/app/router.ts @@ -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) } @@ -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) @@ -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) } @@ -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) + } +}