-
Notifications
You must be signed in to change notification settings - Fork 169
/
routing.ts
255 lines (225 loc) · 7.11 KB
/
routing.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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
import { moduleExts } from '../../shared/constants.ts'
import util from '../../shared/util.ts'
import type { DependencyDescriptor, RouterURL } from '../../types.ts'
import events from './events.ts'
const ghostRoute: Route = { path: '', module: { url: '', hash: '' } }
export type Route = {
path: string
module: RouteModule
children?: Route[]
}
export type RouteModule = {
readonly url: string
readonly hash: string
readonly asyncDeps?: DependencyDescriptor[]
}
export class Routing {
private _routes: Route[]
private _baseUrl: string
private _defaultLocale: string
private _locales: string[]
constructor(
routes: Route[] = [],
baseUrl: string = '/',
defaultLocale: string = 'en',
locales: string[] = []
) {
this._routes = routes
this._baseUrl = baseUrl
this._defaultLocale = defaultLocale
this._locales = locales
}
get baseUrl() {
return this._baseUrl
}
get paths() {
const paths: string[] = []
this._lookup(path => { paths.push(path.map(r => r.path).join('')) }, true)
return paths
}
// routes returns the routes as copy
get routes(): Route[] {
return JSON.parse(JSON.stringify(this._routes))
}
update(module: RouteModule) {
const newRoute: Route = { path: toPagePath(module.url), module }
const dirtyRoutes: Set<Route[]> = new Set()
let exists = false
let targetRoutes = this._routes
this._lookup(routePath => {
const path = routePath.map(r => r.path).join('')
const route = routePath[routePath.length - 1]
const parentRoute = routePath[routePath.length - 2]
if (route.module.url === module.url) {
Object.assign(route.module, module)
exists = true
return false
}
if (!newRoute.path.endsWith('/') && path.startsWith(newRoute.path + '/')) {
const routes = parentRoute ? parentRoute.children! : this._routes
const index = routes.indexOf(route)
if (index >= 0) {
routes.splice(index, 1, ghostRoute)
dirtyRoutes.add(routes)
}
(newRoute.children || (newRoute.children = [])).push({ ...route, path: util.trimPrefix(path, newRoute.path) })
} else if (!path.endsWith('/') && newRoute.path.startsWith(path + '/')) {
newRoute.path = util.trimPrefix(newRoute.path, path)
targetRoutes = route.children || (route.children = [])
}
})
if (exists) {
return
}
dirtyRoutes.forEach(routes => {
let index: number
while (~(index = routes.indexOf(ghostRoute))) {
routes.splice(index, 1)
}
})
dirtyRoutes.clear()
targetRoutes.push(newRoute)
}
removeRoute(url: string) {
this._lookup(path => {
const route = path[path.length - 1]
if (route.module.url === url) {
const parentRoute = path[path.length - 2]
const routes = parentRoute ? parentRoute.children! : this._routes
const index = routes.indexOf(route)
if (index >= 0) {
routes.splice(index, 1, ...(route.children || []).map(r => ({ ...r, path: route.path + r.path })))
}
return false
}
})
}
createRouter(location?: { pathname: string, search?: string }): [RouterURL, RouteModule[]] {
const loc = location || (window as any).location || { pathname: '/' }
const query = new URLSearchParams(loc.search)
let locale = this._defaultLocale
let pathname = util.cleanPath(util.trimPrefix(loc.pathname, this._baseUrl))
let pagePath = ''
let params: Record<string, string> = {}
let chain: RouteModule[] = []
if (pathname !== '/' && this._locales.length > 0) {
const a = pathname.split('/')
const a1 = a[1]
if (a1 !== locale && this._locales.includes(a1)) {
locale = a1
pathname = '/' + a.slice(2).join('/')
}
}
this._lookup(routePath => {
const path = routePath.map(r => r.path).join('')
const [p, ok] = matchPath(path, pathname)
if (ok) {
chain = routePath.map(r => r.module)
const c = routePath[routePath.length - 1].children?.find(c => c.path === '/')
if (c) {
chain.push(c.module)
}
pagePath = path
params = p
return false
}
}, true)
return [{ locale, pathname, pagePath, params, query }, chain]
}
lookup(callback: (path: Route[]) => Boolean | void) {
this._lookup(callback)
}
private _lookup(
callback: (path: Route[]) => Boolean | void,
skipNestIndex = false,
__tracing: Route[] = [],
__routes = this._routes
) {
for (const route of __routes) {
if (skipNestIndex && __tracing.length > 0 && route.path === '/') {
continue
}
if (callback([...__tracing, route]) === false) {
return false
}
}
for (const route of __routes) {
if (route.path !== '/' && route.children?.length) {
if (this._lookup(callback, skipNestIndex, [...__tracing, route], route.children) === false) {
return false
}
}
}
}
}
function matchPath(routePath: string, locPath: string): [Record<string, string>, boolean] {
const params: Record<string, string> = {}
const routeSegments = util.splitPath(routePath)
const locSegments = util.splitPath(locPath)
const depth = Math.max(routeSegments.length, locSegments.length)
for (let i = 0; i < depth; i++) {
const routeSeg = routeSegments[i]
const locSeg = locSegments[i]
if (locSeg === undefined || routeSeg === undefined) {
return [{}, false]
}
if (routeSeg.startsWith('[...') && routeSeg.endsWith(']') && routeSeg.length > 5 && i === routeSegments.length - 1) {
params[routeSeg.slice(4, -1)] = locSegments.slice(i).map(decodeURIComponent).join('/')
break
}
if (routeSeg.startsWith('[') && routeSeg.endsWith(']') && routeSeg.length > 2) {
params[routeSeg.slice(1, -1)] = decodeURIComponent(locSeg)
} else if (routeSeg.startsWith('$') && routeSeg.length > 1) {
params[routeSeg.slice(1)] = decodeURIComponent(locSeg)
} else if (routeSeg !== locSeg) {
return [{}, false]
}
}
return [params, true]
}
export async function redirect(url: string, replace?: boolean) {
const { location, history } = window as any
if (!util.isNEString(url)) {
return
}
if (isHttpUrl(url)) {
location.href = url
return
}
url = util.cleanPath(url)
if (replace) {
history.replaceState(null, '', url)
} else {
history.pushState(null, '', url)
}
events.emit('popstate', { type: 'popstate', resetScroll: true })
}
export function isHttpUrl(url: string) {
try {
const { protocol } = new URL(url)
return protocol === 'https:' || protocol === 'http:'
} catch (error) {
return false
}
}
export function isModuleURL(url: string) {
for (const ext of moduleExts) {
if (url.endsWith('.' + ext)) {
return true
}
}
return false
}
export function toPagePath(url: string): string {
let pathname = util.trimModuleExt(url)
if (pathname.startsWith('/pages/')) {
pathname = util.trimPrefix(pathname, '/pages')
}
if (pathname.endsWith('/index')) {
pathname = util.trimSuffix(pathname, 'index')
}
if (pathname === '') {
pathname = '/'
}
return pathname
}