scroll when clicking same link

pull/4511/head
Divyansh Singh 8 months ago
parent 791f937623
commit d55a401f5f

@ -159,7 +159,7 @@ function newRouter(): Router {
if (inBrowser) {
createApp().then(({ app, router, data }) => {
// wait until page component is fetched before mounting
router.go().then(() => {
router.go(location.href, { initialLoad: true }).then(() => {
// dynamically update head tags
useUpdateHead(router.route, data.site)
app.mount('#app')

@ -19,7 +19,15 @@ export interface Router {
/**
* Navigate to a new URL.
*/
go: (to?: string) => Promise<void>
go: (
to: string,
options?: {
// @internal
initialLoad?: boolean
// Whether to smoothly scroll to the target position.
smoothScroll?: boolean
}
) => Promise<void>
/**
* Called before the route changes. Return `false` to cancel the navigation.
*/
@ -72,19 +80,25 @@ export function createRouter(
}
async function go(
href: string = inBrowser ? location.href : '/',
smoothScroll = false
href: string,
{ smoothScroll = false, initialLoad = 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
if (href === loc) {
if (!initialLoad) {
if (hash) scrollTo(hash, smoothScroll)
else window.scrollTo(0, 0)
return
}
} else {
history.replaceState({ scrollPosition: window.scrollY }, '')
history.pushState({}, '', href)
@ -104,6 +118,7 @@ export function createRouter(
return
}
}
}
await loadPage(href)
await (router.onAfterRouteChange ?? router.onAfterRouteChanged)?.(href)
@ -229,7 +244,7 @@ export function createRouter(
// 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 }

Loading…
Cancel
Save