forked from vuejs/vitepress
-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.ts
221 lines (199 loc) · 6.36 KB
/
router.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
import { reactive, inject, markRaw, nextTick, readonly } from 'vue'
import type { Component, InjectionKey } from 'vue'
import { PageData } from '../shared'
import { inBrowser } from './utils'
import { siteDataRef } from './data'
export interface Route {
path: string
data: PageData
component: Component | null
}
export interface Router {
route: Route
go: (href?: string) => Promise<void>
}
export const RouterSymbol: InjectionKey<Router> = Symbol()
// 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 fakeHost = `http://a.com`
const getDefaultRoute = (): Route => ({
path: '/',
component: null,
// this will be set upon initial page load, which is before
// the app is mounted, so it's guaranteed to be available in
// components. We just need enough data for 404 pages to render.
data: { frontmatter: {} } as any
})
interface PageModule {
__pageData: string
default: Component
}
export function createRouter(
loadPageModule: (path: string) => PageModule | Promise<PageModule>,
fallbackComponent?: Component
): Router {
const route = reactive(getDefaultRoute())
function go(href: string = inBrowser ? location.href : '/') {
// ensure correct deep link so page refresh lands on correct files.
const url = new URL(href, fakeHost)
if (!url.pathname.endsWith('/') && !url.pathname.endsWith('.html')) {
url.pathname += '.html'
href = url.pathname + url.search + url.hash
}
if (inBrowser) {
// save scroll position before changing url
history.replaceState({ scrollPosition: window.scrollY }, document.title)
history.pushState(null, '', href)
}
return loadPage(href)
}
let latestPendingPath: string | null = null
async function loadPage(href: string, scrollPosition = 0) {
const targetLoc = new URL(href, fakeHost)
const pendingPath = (latestPendingPath = targetLoc.pathname)
try {
let page = loadPageModule(pendingPath)
// only await if it returns a Promise - this allows sync resolution
// on initial render in SSR.
if ('then' in page && typeof page.then === 'function') {
page = await page
}
if (latestPendingPath === pendingPath) {
latestPendingPath = null
const { default: comp, __pageData } = page as PageModule
if (!comp) {
throw new Error(`Invalid route component: ${comp}`)
}
route.path = pendingPath
route.component = markRaw(comp)
route.data = import.meta.env.PROD
? markRaw(JSON.parse(__pageData))
: (readonly(JSON.parse(__pageData)) as PageData)
if (inBrowser) {
nextTick(() => {
if (targetLoc.hash && !scrollPosition) {
let target: HTMLElement | null = null
try {
target = document.querySelector(
decodeURIComponent(targetLoc.hash)
) as HTMLElement
} catch (e) {
console.warn(e)
}
if (target) {
scrollTo(target, targetLoc.hash)
return
}
}
window.scrollTo(0, scrollPosition)
})
}
}
} catch (err: any) {
if (!err.message.match(/fetch/)) {
console.error(err)
}
if (latestPendingPath === pendingPath) {
latestPendingPath = null
route.path = pendingPath
route.component = fallbackComponent ? markRaw(fallbackComponent) : null
}
}
}
if (inBrowser) {
window.addEventListener(
'click',
(e) => {
const link = (e.target as Element).closest('a')
if (link) {
const { href, protocol, hostname, pathname, hash, target } = link
const currentUrl = window.location
const extMatch = pathname.match(/\.\w+$/)
// only intercept inbound links
if (
!e.ctrlKey &&
!e.shiftKey &&
!e.altKey &&
!e.metaKey &&
target !== `_blank` &&
protocol === currentUrl.protocol &&
hostname === currentUrl.hostname &&
!(extMatch && extMatch[0] !== '.html')
) {
e.preventDefault()
if (pathname === currentUrl.pathname) {
// scroll between hash anchors in the same page
if (hash && 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 {
go(href)
}
}
}
},
{ capture: true }
)
window.addEventListener('popstate', (e) => {
loadPage(location.href, (e.state && e.state.scrollPosition) || 0)
})
window.addEventListener('hashchange', (e) => {
e.preventDefault()
})
}
return {
route,
go
}
}
export function useRouter(): Router {
const router = inject(RouterSymbol)
if (!router) {
throw new Error('useRouter() is called without provider.')
}
// @ts-ignore
return router
}
export function useRoute(): Route {
return useRouter().route
}
function scrollTo(el: HTMLElement, hash: string, smooth = false) {
let target: Element | null = null
try {
target = el.classList.contains('header-anchor')
? el
: document.querySelector(decodeURIComponent(hash))
} catch (e) {
console.warn(e)
}
if (target) {
let offset = siteDataRef.value.scrollOffset
if (typeof offset === 'string') {
offset =
document.querySelector(offset)!.getBoundingClientRect().bottom + 24
}
const targetPadding = parseInt(
window.getComputedStyle(target as HTMLElement).paddingTop,
10
)
const targetTop =
window.scrollY +
(target as HTMLElement).getBoundingClientRect().top -
offset +
targetPadding
// 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'
})
}
}
}