Skip to content

Commit

Permalink
scroll when clicking same link
Browse files Browse the repository at this point in the history
  • Loading branch information
brc-dd committed Jan 22, 2025
1 parent 791f937 commit dd729b4
Showing 1 changed file with 24 additions and 21 deletions.
45 changes: 24 additions & 21 deletions src/client/app/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export interface Router {
/**
* Navigate to a new URL.
*/
go: (to?: string) => Promise<void>
go: (to?: string, options?: { smoothScroll?: boolean }) => Promise<void>
/**
* Called before the route changes. Return `false` to cancel the navigation.
*/
Expand Down Expand Up @@ -73,35 +73,37 @@ export function createRouter(

async function go(
href: string = inBrowser ? location.href : '/',
smoothScroll = false
{ smoothScroll = false } = {}
) {
href = normalizeHref(href)
const loc = inBrowser ? normalizeHref(location.href) : null

if ((await router.onBeforeRouteChange?.(href)) === false) return

if (loc !== null && href !== loc) {
if (loc !== null) {
const { pathname, hash } = new URL(href, fakeHost)
const currentLoc = new URL(loc, fakeHost)

// save scroll position before changing url
history.replaceState({ scrollPosition: window.scrollY }, '')
history.pushState({}, '', href)

if (pathname === currentLoc.pathname) {
if (hash !== currentLoc.hash) {
window.dispatchEvent(
new HashChangeEvent('hashchange', {
oldURL: currentLoc.href,
newURL: href
})
)

if (hash) scrollTo(hash, smoothScroll)
else window.scrollTo(0, 0)
}
if (href !== loc) {
// save scroll position before changing url
history.replaceState({ scrollPosition: window.scrollY }, '')
history.pushState({}, '', href)

if (pathname === currentLoc.pathname) {
if (hash !== currentLoc.hash) {
window.dispatchEvent(
new HashChangeEvent('hashchange', {
oldURL: currentLoc.href,
newURL: href
})
)
}

return
return
}
} else {
if (hash) scrollTo(hash, smoothScroll)
else window.scrollTo(0, 0)
}
}

Expand Down Expand Up @@ -226,10 +228,11 @@ export function createRouter(

const { href, origin, pathname } = new URL(linkHref, link.baseURI)
const currentLoc = new URL(location.href) // copy to keep old data

// only intercept inbound html links
if (origin === currentLoc.origin && treatAsHtml(pathname)) {
e.preventDefault()
go(href, link.classList.contains('header-anchor'))
go(href, { smoothScroll: link.classList.contains('header-anchor') })
}
},
{ capture: true }
Expand Down

0 comments on commit dd729b4

Please sign in to comment.