-
-
Notifications
You must be signed in to change notification settings - Fork 927
/
Copy pathrouter.js
279 lines (253 loc) · 8.81 KB
/
router.js
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
275
276
277
278
279
"use strict"
var Vnode = require("../render/vnode")
var m = require("../render/hyperscript")
var Promise = require("../promise/promise")
var buildPathname = require("../pathname/build")
var parsePathname = require("../pathname/parse")
var compileTemplate = require("../pathname/compileTemplate")
var assign = require("../util/assign")
var censor = require("../util/censor")
var sentinel = {}
function decodeURIComponentSave(component) {
try {
return decodeURIComponent(component)
} catch(e) {
return component
}
}
module.exports = function($window, mountRedraw) {
var callAsync = $window == null
// In case Mithril.js' loaded globally without the DOM, let's not break
? null
: typeof $window.setImmediate === "function" ? $window.setImmediate : $window.setTimeout
var p = Promise.resolve()
var scheduled = false
// state === 0: init
// state === 1: scheduled
// state === 2: done
var ready = false
var state = 0
var compiled, fallbackRoute
var currentResolver = sentinel, component, attrs, currentPath, lastUpdate
var RouterRoot = {
onbeforeupdate: function() {
state = state ? 2 : 1
return !(!state || sentinel === currentResolver)
},
onremove: function() {
$window.removeEventListener("popstate", fireAsync, false)
$window.removeEventListener("hashchange", resolveRoute, false)
},
view: function() {
if (!state || sentinel === currentResolver) return
// Wrap in a fragment to preserve existing key semantics
var vnode = [Vnode(component, attrs.key, attrs)]
if (currentResolver) vnode = currentResolver.render(vnode[0])
return vnode
},
}
var SKIP = route.SKIP = {}
function resolveRoute() {
scheduled = false
// Consider the pathname holistically. The prefix might even be invalid,
// but that's not our problem.
var prefix = $window.location.hash
if (route.prefix[0] !== "#") {
prefix = $window.location.search + prefix
if (route.prefix[0] !== "?") {
prefix = $window.location.pathname + prefix
if (prefix[0] !== "/") prefix = "/" + prefix
}
}
// This seemingly useless `.concat()` speeds up the tests quite a bit,
// since the representation is consistently a relatively poorly
// optimized cons string.
var path = prefix.concat()
.replace(/(?:%[a-f89][a-f0-9])+/gim, decodeURIComponentSave)
.slice(route.prefix.length)
var data = parsePathname(path)
assign(data.params, $window.history.state)
function reject(e) {
console.error(e)
setPath(fallbackRoute, null, {replace: true})
}
loop(0)
function loop(i) {
// state === 0: init
// state === 1: scheduled
// state === 2: done
for (; i < compiled.length; i++) {
if (compiled[i].check(data)) {
var payload = compiled[i].component
var matchedRoute = compiled[i].route
var localComp = payload
var update = lastUpdate = function(comp) {
if (update !== lastUpdate) return
if (comp === SKIP) return loop(i + 1)
component = comp != null && (typeof comp.view === "function" || typeof comp === "function")? comp : "div"
attrs = data.params, currentPath = path, lastUpdate = null
currentResolver = payload.render ? payload : null
if (state === 2) mountRedraw.redraw()
else {
state = 2
mountRedraw.redraw.sync()
}
}
// There's no understating how much I *wish* I could
// use `async`/`await` here...
if (payload.view || typeof payload === "function") {
payload = {}
update(localComp)
}
else if (payload.onmatch) {
p.then(function () {
return payload.onmatch(data.params, path, matchedRoute)
}).then(update, path === fallbackRoute ? null : reject)
}
else update("div")
return
}
}
if (path === fallbackRoute) {
throw new Error("Could not resolve default route " + fallbackRoute + ".")
}
setPath(fallbackRoute, null, {replace: true})
}
}
// Set it unconditionally so `m.route.set` and `m.route.Link` both work,
// even if neither `pushState` nor `hashchange` are supported. It's
// cleared if `hashchange` is used, since that makes it automatically
// async.
function fireAsync() {
if (!scheduled) {
scheduled = true
// TODO: just do `mountRedraw.redraw()` here and elide the timer
// dependency. Note that this will muck with tests a *lot*, so it's
// not as easy of a change as it sounds.
callAsync(resolveRoute)
}
}
function setPath(path, data, options) {
path = buildPathname(path, data)
if (ready) {
fireAsync()
var state = options ? options.state : null
var title = options ? options.title : null
if (options && options.replace) $window.history.replaceState(state, title, route.prefix + path)
else $window.history.pushState(state, title, route.prefix + path)
}
else {
$window.location.href = route.prefix + path
}
}
function route(root, defaultRoute, routes) {
if (!root) throw new TypeError("DOM element being rendered to does not exist.")
compiled = Object.keys(routes).map(function(route) {
if (route[0] !== "/") throw new SyntaxError("Routes must start with a '/'.")
if ((/:([^\/\.-]+)(\.{3})?:/).test(route)) {
throw new SyntaxError("Route parameter names must be separated with either '/', '.', or '-'.")
}
return {
route: route,
component: routes[route],
check: compileTemplate(route),
}
})
fallbackRoute = defaultRoute
if (defaultRoute != null) {
var defaultData = parsePathname(defaultRoute)
if (!compiled.some(function (i) { return i.check(defaultData) })) {
throw new ReferenceError("Default route doesn't match any known routes.")
}
}
if (typeof $window.history.pushState === "function") {
$window.addEventListener("popstate", fireAsync, false)
} else if (route.prefix[0] === "#") {
$window.addEventListener("hashchange", resolveRoute, false)
}
ready = true
mountRedraw.mount(root, RouterRoot)
resolveRoute()
}
route.set = function(path, data, options) {
if (lastUpdate != null) {
options = options || {}
options.replace = true
}
lastUpdate = null
setPath(path, data, options)
}
route.get = function() {return currentPath}
route.prefix = "#!"
route.Link = {
view: function(vnode) {
// Omit the used parameters from the rendered element - they are
// internal. Also, censor the various lifecycle methods.
//
// We don't strip the other parameters because for convenience we
// let them be specified in the selector as well.
var child = m(
vnode.attrs.selector || "a",
censor(vnode.attrs, ["options", "params", "selector", "onclick"]),
vnode.children
)
var options, onclick, href
// Let's provide a *right* way to disable a route link, rather than
// letting people screw up accessibility on accident.
//
// The attribute is coerced so users don't get surprised over
// `disabled: 0` resulting in a button that's somehow routable
// despite being visibly disabled.
if (child.attrs.disabled = Boolean(child.attrs.disabled)) {
child.attrs.href = null
child.attrs["aria-disabled"] = "true"
// If you *really* do want add `onclick` on a disabled link, use
// an `oncreate` hook to add it.
} else {
options = vnode.attrs.options
onclick = vnode.attrs.onclick
// Easier to build it now to keep it isomorphic.
href = buildPathname(child.attrs.href, vnode.attrs.params)
child.attrs.href = route.prefix + href
child.attrs.onclick = function(e) {
var result
if (typeof onclick === "function") {
result = onclick.call(e.currentTarget, e)
} else if (onclick == null || typeof onclick !== "object") {
// do nothing
} else if (typeof onclick.handleEvent === "function") {
onclick.handleEvent(e)
}
// Adapted from React Router's implementation:
// https://github.com/ReactTraining/react-router/blob/520a0acd48ae1b066eb0b07d6d4d1790a1d02482/packages/react-router-dom/modules/Link.js
//
// Try to be flexible and intuitive in how we handle links.
// Fun fact: links aren't as obvious to get right as you
// would expect. There's a lot more valid ways to click a
// link than this, and one might want to not simply click a
// link, but right click or command-click it to copy the
// link target, etc. Nope, this isn't just for blind people.
if (
// Skip if `onclick` prevented default
result !== false && !e.defaultPrevented &&
// Ignore everything but left clicks
(e.button === 0 || e.which === 0 || e.which === 1) &&
// Let the browser handle `target=_blank`, etc.
(!e.currentTarget.target || e.currentTarget.target === "_self") &&
// No modifier keys
!e.ctrlKey && !e.metaKey && !e.shiftKey && !e.altKey
) {
e.preventDefault()
e.redraw = false
route.set(href, null, options)
}
}
}
return child
},
}
route.param = function(key) {
return attrs && key != null ? attrs[key] : attrs
}
return route
}