feat: support same page navigation in router.go (#4511)

pull/4509/merge
Divyansh Singh 8 months ago committed by GitHub
parent 4f77b4fdfd
commit 23d3281ed6
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -159,19 +159,14 @@ function newRouter(): Router {
if (inBrowser) { if (inBrowser) {
createApp().then(({ app, router, data }) => { createApp().then(({ app, router, data }) => {
// wait until page component is fetched before mounting // wait until page component is fetched before mounting
router.go().then(() => { router.go(location.href, { initialLoad: true }).then(() => {
// dynamically update head tags // dynamically update head tags
useUpdateHead(router.route, data.site) useUpdateHead(router.route, data.site)
app.mount('#app') app.mount('#app')
// scroll to hash on new tab during dev // scroll to hash on new tab during dev
if (import.meta.env.DEV && location.hash) { if (import.meta.env.DEV && location.hash) {
const target = document.getElementById( scrollTo(location.hash)
decodeURIComponent(location.hash).slice(1)
)
if (target) {
scrollTo(target, location.hash)
}
} }
}) })
}) })

@ -7,6 +7,8 @@ import { getScrollOffset, inBrowser, withBase } from './utils'
export interface Route { export interface Route {
path: string path: string
hash: string
query: string
data: PageData data: PageData
component: Component | null component: Component | null
} }
@ -19,7 +21,15 @@ export interface Router {
/** /**
* Navigate to a new URL. * 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. * Called before the route changes. Return `false` to cancel the navigation.
*/ */
@ -37,10 +47,6 @@ export interface Router {
* Called after the route changes. * Called after the route changes.
*/ */
onAfterRouteChange?: (to: string) => Awaitable<void> onAfterRouteChange?: (to: string) => Awaitable<void>
/**
* @deprecated use `onAfterRouteChange` instead
*/
onAfterRouteChanged?: (to: string) => Awaitable<void>
} }
export const RouterSymbol: InjectionKey<Router> = Symbol() export const RouterSymbol: InjectionKey<Router> = Symbol()
@ -51,6 +57,8 @@ const fakeHost = 'http://a.com'
const getDefaultRoute = (): Route => ({ const getDefaultRoute = (): Route => ({
path: '/', path: '/',
hash: '',
query: '',
component: null, component: null,
data: notFoundPageData data: notFoundPageData
}) })
@ -68,39 +76,32 @@ export function createRouter(
const router: Router = { const router: Router = {
route, route,
go async go(href, options) {
}
async function go(href: string = inBrowser ? location.href : '/') {
href = normalizeHref(href) href = normalizeHref(href)
if ((await router.onBeforeRouteChange?.(href)) === false) return if ((await router.onBeforeRouteChange?.(href)) === false) return
if (inBrowser && href !== normalizeHref(location.href)) { if (!inBrowser || (await changeRoute(href, options))) await loadPage(href)
// save scroll position before changing url syncRouteQueryAndHash()
history.replaceState({ scrollPosition: window.scrollY }, '') await router.onAfterRouteChange?.(href)
history.pushState({}, '', href)
} }
await loadPage(href)
await (router.onAfterRouteChange ?? router.onAfterRouteChanged)?.(href)
} }
let latestPendingPath: string | null = null let latestPendingPath: string | null = null
async function loadPage(href: string, scrollPosition = 0, isRetry = false) { async function loadPage(href: string, scrollPosition = 0, isRetry = false) {
if ((await router.onBeforePageLoad?.(href)) === false) return if ((await router.onBeforePageLoad?.(href)) === false) return
const targetLoc = new URL(href, fakeHost) const targetLoc = new URL(href, fakeHost)
const pendingPath = (latestPendingPath = targetLoc.pathname) const pendingPath = (latestPendingPath = targetLoc.pathname)
try { try {
let page = await loadPageModule(pendingPath) let page = await loadPageModule(pendingPath)
if (!page) { if (!page) throw new Error(`Page not found: ${pendingPath}`)
throw new Error(`Page not found: ${pendingPath}`)
}
if (latestPendingPath === pendingPath) { if (latestPendingPath === pendingPath) {
latestPendingPath = null latestPendingPath = null
const { default: comp, __pageData } = page const { default: comp, __pageData } = page
if (!comp) { if (!comp) throw new Error(`Invalid route component: ${comp}`)
throw new Error(`Invalid route component: ${comp}`)
}
await router.onAfterPageLoad?.(href) await router.onAfterPageLoad?.(href)
@ -109,36 +110,25 @@ export function createRouter(
route.data = import.meta.env.PROD route.data = import.meta.env.PROD
? markRaw(__pageData) ? markRaw(__pageData)
: (readonly(__pageData) as PageData) : (readonly(__pageData) as PageData)
syncRouteQueryAndHash(targetLoc)
if (inBrowser) { if (inBrowser) {
nextTick(() => { nextTick(() => {
let actualPathname = let actualPathname =
siteDataRef.value.base + siteDataRef.value.base +
__pageData.relativePath.replace(/(?:(^|\/)index)?\.md$/, '$1') __pageData.relativePath.replace(/(?:(^|\/)index)?\.md$/, '$1')
if (!siteDataRef.value.cleanUrls && !actualPathname.endsWith('/')) { if (!siteDataRef.value.cleanUrls && !actualPathname.endsWith('/')) {
actualPathname += '.html' actualPathname += '.html'
} }
if (actualPathname !== targetLoc.pathname) { if (actualPathname !== targetLoc.pathname) {
targetLoc.pathname = actualPathname targetLoc.pathname = actualPathname
href = actualPathname + targetLoc.search + targetLoc.hash href = actualPathname + targetLoc.search + targetLoc.hash
history.replaceState({}, '', href) history.replaceState({}, '', href)
} }
if (targetLoc.hash && !scrollPosition) { return scrollTo(targetLoc.hash, false, scrollPosition)
let target: HTMLElement | null = null
try {
target = document.getElementById(
decodeURIComponent(targetLoc.hash).slice(1)
)
} catch (e) {
console.warn(e)
}
if (target) {
scrollTo(target, targetLoc.hash)
return
}
}
window.scrollTo(0, scrollPosition)
}) })
} }
} }
@ -173,14 +163,22 @@ export function createRouter(
.replace(/^\//, '') .replace(/^\//, '')
: '404.md' : '404.md'
route.data = { ...notFoundPageData, relativePath } route.data = { ...notFoundPageData, relativePath }
syncRouteQueryAndHash(targetLoc)
} }
} }
} }
if (inBrowser) { function syncRouteQueryAndHash(
if (history.state === null) { loc: { search: string; hash: string } = inBrowser
history.replaceState({}, '') ? location
: { search: '', hash: '' }
) {
route.query = loc.search
route.hash = decodeURIComponent(loc.hash)
} }
if (inBrowser) {
if (history.state === null) history.replaceState({}, '')
window.addEventListener( window.addEventListener(
'click', 'click',
(e) => { (e) => {
@ -193,8 +191,9 @@ export function createRouter(
e.shiftKey || e.shiftKey ||
e.altKey || e.altKey ||
e.metaKey e.metaKey
) ) {
return return
}
const link = e.target.closest<HTMLAnchorElement | SVGAElement>('a') const link = e.target.closest<HTMLAnchorElement | SVGAElement>('a')
if ( if (
@ -202,47 +201,24 @@ export function createRouter(
link.closest('.vp-raw') || link.closest('.vp-raw') ||
link.hasAttribute('download') || link.hasAttribute('download') ||
link.hasAttribute('target') link.hasAttribute('target')
) ) {
return return
}
const linkHref = const linkHref =
link.getAttribute('href') ?? link.getAttribute('href') ??
(link instanceof SVGAElement ? link.getAttribute('xlink:href') : null) (link instanceof SVGAElement ? link.getAttribute('xlink:href') : null)
if (linkHref == null) return if (linkHref == null) return
const { href, origin, pathname, hash, search } = new URL( const { href, origin, pathname } = new URL(linkHref, link.baseURI)
linkHref, const currentLoc = new URL(location.href) // copy to keep old data
link.baseURI
)
const currentUrl = new URL(location.href) // copy to keep old data
// only intercept inbound html links // only intercept inbound html links
if (origin === currentUrl.origin && treatAsHtml(pathname)) { if (origin === currentLoc.origin && treatAsHtml(pathname)) {
e.preventDefault() e.preventDefault()
if ( router.go(href, {
pathname === currentUrl.pathname &&
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({}, '', href)
// still emit the event so we can listen to it in themes
window.dispatchEvent(
new HashChangeEvent('hashchange', {
oldURL: currentUrl.href,
newURL: href
})
)
}
if (hash) {
// use smooth scroll when clicking on header anchor links // use smooth scroll when clicking on header anchor links
scrollTo(link, hash, link.classList.contains('header-anchor')) smoothScroll: link.classList.contains('header-anchor')
} else { })
window.scrollTo(0, 0)
}
} else {
go(href)
}
} }
}, },
{ capture: true } { capture: true }
@ -252,11 +228,13 @@ export function createRouter(
if (e.state === null) return if (e.state === null) return
const href = normalizeHref(location.href) const href = normalizeHref(location.href)
await loadPage(href, (e.state && e.state.scrollPosition) || 0) await loadPage(href, (e.state && e.state.scrollPosition) || 0)
await (router.onAfterRouteChange ?? router.onAfterRouteChanged)?.(href) syncRouteQueryAndHash()
await router.onAfterRouteChange?.(href)
}) })
window.addEventListener('hashchange', (e) => { window.addEventListener('hashchange', (e) => {
e.preventDefault() e.preventDefault()
syncRouteQueryAndHash()
}) })
} }
@ -267,9 +245,7 @@ export function createRouter(
export function useRouter(): Router { export function useRouter(): Router {
const router = inject(RouterSymbol) const router = inject(RouterSymbol)
if (!router) { if (!router) throw new Error('useRouter() is called without provider.')
throw new Error('useRouter() is called without provider.')
}
return router return router
} }
@ -277,13 +253,16 @@ export function useRoute(): Route {
return useRouter().route return useRouter().route
} }
export function scrollTo(el: Element, hash: string, smooth = false) { export function scrollTo(hash: string, smooth = false, scrollPosition = 0) {
if (!hash || scrollPosition) {
window.scrollTo(0, scrollPosition)
return
}
let target: Element | null = null let target: Element | null = null
try { try {
target = el.classList.contains('header-anchor') target = document.getElementById(decodeURIComponent(hash).slice(1))
? el
: document.getElementById(decodeURIComponent(hash).slice(1))
} catch (e) { } catch (e) {
console.warn(e) console.warn(e)
} }
@ -293,17 +272,20 @@ export function scrollTo(el: Element, hash: string, smooth = false) {
window.getComputedStyle(target).paddingTop, window.getComputedStyle(target).paddingTop,
10 10
) )
const targetTop = const targetTop =
window.scrollY + window.scrollY +
target.getBoundingClientRect().top - target.getBoundingClientRect().top -
getScrollOffset() + getScrollOffset() +
targetPadding targetPadding
function scrollToTarget() { function scrollToTarget() {
// only smooth scroll if distance is smaller than screen height. // only smooth scroll if distance is smaller than screen height.
if (!smooth || Math.abs(targetTop - window.scrollY) > window.innerHeight) if (!smooth || Math.abs(targetTop - window.scrollY) > window.innerHeight)
window.scrollTo(0, targetTop) window.scrollTo(0, targetTop)
else window.scrollTo({ left: 0, top: targetTop, behavior: 'smooth' }) else window.scrollTo({ left: 0, top: targetTop, behavior: 'smooth' })
} }
requestAnimationFrame(scrollToTarget) requestAnimationFrame(scrollToTarget)
} }
} }
@ -313,9 +295,7 @@ function handleHMR(route: Route): void {
if (import.meta.hot) { if (import.meta.hot) {
// hot reload pageData // hot reload pageData
import.meta.hot.on('vitepress:pageData', (payload: PageDataPayload) => { import.meta.hot.on('vitepress:pageData', (payload: PageDataPayload) => {
if (shouldHotReload(payload)) { if (shouldHotReload(payload)) route.data = payload.pageData
route.data = payload.pageData
}
}) })
} }
} }
@ -332,9 +312,47 @@ function normalizeHref(href: string): string {
const url = new URL(href, fakeHost) const url = new URL(href, fakeHost)
url.pathname = url.pathname.replace(/(^|\/)index(\.html)?$/, '$1') url.pathname = url.pathname.replace(/(^|\/)index(\.html)?$/, '$1')
// ensure correct deep link so page refresh lands on correct files. // ensure correct deep link so page refresh lands on correct files.
if (siteDataRef.value.cleanUrls) if (siteDataRef.value.cleanUrls) {
url.pathname = url.pathname.replace(/\.html$/, '') url.pathname = url.pathname.replace(/\.html$/, '')
else if (!url.pathname.endsWith('/') && !url.pathname.endsWith('.html')) } else if (!url.pathname.endsWith('/') && !url.pathname.endsWith('.html')) {
url.pathname += '.html' url.pathname += '.html'
}
return url.pathname + url.search + url.hash return url.pathname + url.search + url.hash
} }
async function changeRoute(
href: string,
{ smoothScroll = false, initialLoad = false } = {}
): Promise<boolean> {
const loc = normalizeHref(location.href)
const { pathname, hash } = new URL(href, fakeHost)
const currentLoc = new URL(loc, fakeHost)
if (href === loc) {
if (!initialLoad) {
scrollTo(hash, smoothScroll)
return false
}
} else {
// save scroll position before changing URL
history.replaceState({ scrollPosition: window.scrollY }, '')
history.pushState({}, '', href)
if (pathname === currentLoc.pathname) {
// scroll between hash anchors on the same page, avoid duplicate entries
if (hash !== currentLoc.hash) {
window.dispatchEvent(
new HashChangeEvent('hashchange', {
oldURL: currentLoc.href,
newURL: href
})
)
scrollTo(hash, smoothScroll)
}
return false
}
}
return true
}

Loading…
Cancel
Save