-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.js
78 lines (65 loc) · 1.74 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
var wayfarer = require('wayfarer')
var match = require('pathname-match')
var loadScript = require('load-script')
var root = require('global')
var router
var cache = {}
var dft = function () {}
var bundleResolve = function (routeObj) {
var appPath = match(routeObj.pathname)
var bundle = appPath + '/bundle.js'
return bundle
}
function render (routeObj, opts) {
router(match(routeObj.pathname), routeObj, opts)
}
function loadRoute (defaultParams, routeObj) {
var bundle = bundleResolve(routeObj)
if (!cache[bundle]) {
cache[bundle] = true
loadScript(bundle, function (err) {
if (err) {
return dft()
}
render(routeObj)
})
} else {
dft()
}
}
function lazyRouter (defaultRoute, opts) {
if (!router) {
opts = opts || {}
if (typeof defaultRoute !== 'string') {
throw new Error('You must supply a default route')
}
if (typeof opts.defaultAction === 'function') {
dft = opts.defaultAction
}
if (typeof opts.resolver === 'function') {
bundleResolve = opts.resolver
}
root.onpopstate = function (evt) {
render(document.location, evt.state || {})
}
router = wayfarer(defaultRoute)
router.on(defaultRoute, loadRoute)
router.push = function (route, opts) {
opts = opts || {}
var routeObj = document.createElement('a')
routeObj.href = route
root.history.pushState(opts, '', route)
render(routeObj, opts)
}
router.replace = function (route, opts) {
opts = opts || {}
var routeObj = document.createElement('a')
routeObj.href = route
root.history.replaceState(opts, '', route)
render(routeObj, opts)
}
root.__router = router
}
return router
}
module.exports = lazyRouter