-
Notifications
You must be signed in to change notification settings - Fork 2
/
router.ts
274 lines (224 loc) · 7.43 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
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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
import { Validator, object, errorDebugString } from 'idonttrustlikethat'
interface Router<ROUTES extends Record<string, RouteDefinition<string, {}>>> {
readonly definitions: ROUTES
/**
* The current route. It's always defined and can be the special 'not_found' route.
*/
readonly route: RouteUnionFromDefinitions<RoutesWithNotFound<ROUTES>>
/**
* Register a listener to be notified when the router's current 'route' field changes.
*/
readonly onChange: (callback: () => void) => Unsubscribe
/**
* Pushes an entry to the browser's history stack.
*/
readonly push: <NAME extends keyof ROUTES>(
routeName: NAME,
params: SerializableValues<ROUTES[NAME]['validator']['T']>
) => void
/**
* Modifies the current history entry in the history stack.
*/
readonly replace: <NAME extends keyof ROUTES>(
routeName: NAME,
params: SerializableValues<ROUTES[NAME]['validator']['T']>
) => void
/**
* Creates a link string.
*/
readonly link: <NAME extends keyof ROUTES>(
routeName: NAME,
params: SerializableValues<ROUTES[NAME]['validator']['T']>
) => string
}
/**
* The route factory function.
*/
export function Route<PARAMS extends Validator<{}>>(
path: string,
params?: PARAMS
): { path: string; validator: PARAMS } {
return { path, validator: params || ((object({}) as unknown) as PARAMS) }
}
/**
* The router factory function.
*/
export function Router<ROUTES extends Record<string, RouteDefinitionValue<{}>>>(
definitions: ROUTES,
options: Options<Router<RouteValueToDefinition<ROUTES>>>
): Router<RouteValueToDefinition<ROUTES>> {
const routes = Object.keys(definitions).reduce((acc, name) => {
const route = definitions[name]
acc[name] = { ...route, name, ...pathInfos(route.path) }
return acc
}, {} as Record<string, ParsedRouteDefinition<string, {}>>)
const notFound = { name: 'notFound', params: {} }
let subs: Function[] = []
let _route = notFound
function setRouteFromHistory() {
const path = location.pathname
const search = location.search
for (const parsedRoute of Object.values(routes)) {
const match = parsedRoute.pattern.exec(path)
if (!match) continue
const stringParams = parsedRoute.keys.reduce<Record<string, string>>((params, key, index) => {
params[key] = decodeURIComponent(match[index + 1])
return params
}, parseQueryParams(search.slice(1)))
const validatedParams = parsedRoute.validator.validate(stringParams)
if (!validatedParams.ok) {
return onRouteNotFound(
'route match but params error. ' + errorDebugString(validatedParams.errors)
)
}
return (_route = {
name: parsedRoute.name,
params: validatedParams.value
})
}
onRouteNotFound('No match found')
}
const PARAMS = /:[^\\?\/]*/g
function link(routeName: string, params: Record<string, string> = {}) {
const routeToLink = routes[routeName]
const path = routeToLink.path.replace(PARAMS, p => encodeURIComponent(params[p.substring(1)]))
const query = Object.keys(params)
.filter(p => !routeToLink.keys.includes(p) && params[p] !== undefined)
.map(p => `${p}=${encodeURIComponent(params[p])}`)
.join('&')
return path + (query.length ? `?${query}` : '')
}
const push = changeRoute(false)
const replace = changeRoute(true)
function changeRoute(replace: boolean) {
return (routeName: string, params: Record<string, any> = {}) => {
const uri = link(routeName, params)
if (replace) history.replaceState(uri, '', uri)
else history.pushState(uri, '', uri)
setRouteFromHistory()
fireOnChange()
}
}
function onChange(callback: () => void) {
subs.push(callback)
return () => {
subs.splice(subs.indexOf(callback), 1)
}
}
function fireOnChange() {
subs.forEach(fn => fn())
}
function onRouteNotFound(reason: string) {
// Set the route to notFound first, in case the onNotFound callback ends up redirecting to some other routes instead.
_route = notFound
options.onNotFound(reason, router)
// if no redirect occured then fire onChange, otherwise it already fired from push/replace.
if (_route.name === 'notFound') fireOnChange()
}
const router = ({
get route() {
return _route
},
definitions,
onChange,
push,
replace,
link
} as any) as Router<RouteValueToDefinition<ROUTES>>
setRouteFromHistory()
addEventListener('popstate', () => {
setRouteFromHistory()
fireOnChange()
})
return router
}
// Extracts a simple chain like /path/:id to a regexp and the list of path keys it found.
function pathInfos(str: string) {
let tmp,
keys = [],
pattern = '',
arr = str.split('/')
arr[0] || arr.shift()
while ((tmp = arr.shift())) {
if (tmp[0] === ':') {
keys.push(tmp.substring(1))
pattern += '/([^/]+?)'
} else {
pattern += '/' + tmp
}
}
return {
keys,
pattern: new RegExp('^' + pattern + '/?$', 'i')
}
}
function parseQueryParams(query: string) {
if (!query) return {}
return query.split('&').reduce<Record<string, string>>((res, paramValue) => {
const [param, value] = paramValue.split('=')
res[param] = decodeURIComponent(value)
return res
}, {})
}
// A route as defined during router initialization.
interface RouteDefinitionValue<PARAMS extends {}> {
path: string
validator: Validator<PARAMS>
}
interface RouteDefinition<NAME, PARAMS extends {}> {
name: NAME
path: string
validator: Validator<PARAMS>
}
type RouteValueToDefinition<ROUTES extends Record<string, RouteDefinitionValue<{}>>> = {
[NAME in keyof ROUTES]: NAME extends string
? { name: NAME; path: string; validator: ROUTES[NAME]['validator'] }
: never
}
interface ParsedRouteDefinition<NAME, PARAMS> extends RouteDefinition<NAME, PARAMS> {
keys: string[]
pattern: RegExp
}
interface CurrentRoute<NAME, PARAMS> {
name: NAME
params: PARAMS
}
interface Options<ROUTER> {
onNotFound: (reason: string, router: ROUTER) => void
}
type RouteUnionFromDefinitions<ROUTES extends Record<string, RouteDefinition<string, {}>>> = {
[NAME in keyof ROUTES]: ROUTES[NAME] extends ROUTES[keyof ROUTES]
? CurrentRouteFromDefinition<ROUTES[NAME]>
: never
}[keyof ROUTES]
type CurrentRouteFromDefinition<ROUTE extends RouteDefinition<string, {}>> = CurrentRoute<
ROUTE['name'],
ROUTE['validator']['T']
>
type Unsubscribe = () => void
type RoutesWithNotFound<ROUTES extends Record<string, RouteDefinition<string, {}>>> = ROUTES & {
notFound: {
name: 'notFound'
path: ''
validator: Validator<{}>
}
}
type ValueOf<T> = T[keyof T]
type SerializableValues<T> = {
[K in keyof T]: T[K] extends number | string | undefined ? T[K] : string
}
// Using a full router with its methods can lead to method signature incompatibilities.
type AnyBaseRouter = Pick<Router<any>, 'definitions'>
export type RouteParams<
ROUTER extends AnyBaseRouter,
NAME extends keyof ROUTER['definitions']
> = ROUTER['definitions'][NAME]['validator']['T']
type RouteAndParamsTemp<ROUTES extends Record<string, RouteDefinition<string, {}>>> = {
[NAME in keyof ROUTES]: ROUTES[NAME] extends ROUTES[keyof ROUTES]
? [NAME, SerializableValues<ROUTES[NAME]['validator']['T']>]
: never
}
// The union of all valid route name + params tuples that could be passed as arguments to push/replace/link
export type RouteAndParams<ROUTER extends AnyBaseRouter> = ValueOf<
RouteAndParamsTemp<ROUTER['definitions']>
>