You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
vitepress/lib/app/router.js

185 lines
4.3 KiB

5 years ago
import { reactive, inject, nextTick, markRaw } from 'vue'
/**
* @typedef {import('vue').Component} Component
*
* @typedef {{
* path: string
* contentComponent: Component | null
* }} Route
5 years ago
*
* @typedef {{
* route: Route
5 years ago
* go: (href?: string) => Promise<void>
5 years ago
* }} Router
*/
/**
5 years ago
* @type {import('vue').InjectionKey<Router>}
*/
5 years ago
export const RouterSymbol = Symbol()
/**
* @returns {Route}
*/
const getDefaultRoute = () => ({
5 years ago
path: '/',
contentComponent: null
})
5 years ago
/**
* @param {(route: Route) => Component | Promise<Component>} loadComponent
* @param {Component} [fallbackComponent]
5 years ago
* @returns {Router}
*/
5 years ago
export function createRouter(loadComponent, fallbackComponent) {
const route = reactive(getDefaultRoute())
5 years ago
const inBrowser = typeof window !== 'undefined'
5 years ago
/**
5 years ago
* @param {string} [href]
5 years ago
* @returns {Promise<void>}
*/
function go(href) {
5 years ago
href = href || (inBrowser ? location.href : '/')
5 years ago
if (inBrowser) {
// save scroll position before changing url
history.replaceState({ scrollPosition: window.scrollY }, document.title)
history.pushState(null, '', href)
}
return loadPage(href)
}
/**
* @param {string} href
* @param {number} scrollPosition
* @returns {Promise<void>}
*/
async function loadPage(href, scrollPosition = 0) {
// we are just using URL to parse the pathname and hash - the base doesn't
// matter and is only passed to support same-host hrefs.
const targetLoc = new URL(href, `http://vuejs.org`)
5 years ago
const pendingPath = (route.path = targetLoc.pathname)
try {
let comp = loadComponent(route)
// only await if it returns a Promise - this allows sync resolution
// on initial render in SSR.
if ('then' in comp && typeof comp.then === 'function') {
comp = await comp
}
if (route.path === pendingPath) {
if (!comp) {
throw new Error(`Invalid route component: ${comp}`)
}
route.contentComponent = markRaw(comp)
if (inBrowser) {
5 years ago
await nextTick()
if (targetLoc.hash && !scrollPosition) {
/**
* @type {HTMLElement | null}
*/
const target = document.querySelector(targetLoc.hash)
if (target) {
scrollPosition = target.offsetTop
}
}
window.scrollTo({
left: 0,
top: scrollPosition,
behavior: 'auto'
})
}
}
} catch (err) {
if (!err.message.match(/fetch/)) {
console.error(err)
}
if (route.path === pendingPath) {
route.contentComponent = fallbackComponent
? markRaw(fallbackComponent)
: null
}
}
5 years ago
}
if (inBrowser) {
window.addEventListener(
'click',
/**
* @param {*} e
*/
(e) => {
const link = e.target.closest('a')
if (link) {
const { href, target } = link
5 years ago
const targetUrl = new URL(href)
const currentUrl = window.location
if (
target !== `_blank` &&
targetUrl.protocol === currentUrl.protocol &&
targetUrl.hostname === currentUrl.hostname
) {
if (targetUrl.pathname === currentUrl.pathname) {
// smooth scroll bewteen hash anchors in the same page
if (targetUrl.hash !== currentUrl.hash) {
e.preventDefault()
window.scrollTo({
left: 0,
top: link.offsetTop,
5 years ago
behavior: 'smooth'
})
}
} else {
e.preventDefault()
5 years ago
go(href)
}
}
}
5 years ago
},
{ capture: true }
)
window.addEventListener(
'popstate',
/**
* @param {*} e
*/
(e) => {
loadPage(location.href, (e.state && e.state.scrollPosition) || 0)
}
5 years ago
)
}
5 years ago
/**
* @type {Router}
*/
const router = {
route,
go
}
5 years ago
return router
}
/**
5 years ago
* @return {Router}
*/
5 years ago
export function useRouter() {
const router = inject(RouterSymbol)
5 years ago
if (!router) {
throw new Error('useRouter() is called without provider.')
}
5 years ago
// @ts-ignore
return router
}
5 years ago
/**
* @returns {Route}
*/
export function useRoute() {
return useRouter().route
}