-
Notifications
You must be signed in to change notification settings - Fork 11
/
index.js
187 lines (151 loc) · 4.34 KB
/
index.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
import * as m from 'matchit'
const cache = new Map()
function clean (href) {
return href.replace(window.location.origin, '')
}
function parse (location, routes) {
let hash = ''
let search = ''
let [ pathname, ...parts ] = location.split(/#|\?/)
pathname = pathname.replace(/\/$/g, '')
pathname = pathname || '/'
for (let i = 0; i < parts.length; i++) {
const [ rest ] = location.split(parts[i])
if (rest[rest.length - 1] === '?') search = parts[i]
if (rest[rest.length - 1] === '#') hash = parts[i]
}
const match = m.match(pathname, routes.map(r => r.matcher))
const route = routes.filter(r => r.path === match[0].old)[0]
return match[0] ? Object.assign({}, route, {
params: m.exec(pathname, match),
hash,
search,
pathname,
location
}) : null
}
export default function app (selector, routes = ['*']) {
let root = document.querySelector(selector)
let queue
const middleware = []
const events = {}
routes = routes.concat(routes.indexOf('*') < 0 ? '*' : []).reduce((next, r) => {
if (typeof r === 'function') {
middleware.push(r)
return next
}
return next.concat(r)
}, []).map(r => {
return r.path ? Object.assign({}, r, {
matcher: m.parse(r.path)
}) : {
path: r,
matcher: m.parse(r)
}
})
const initialRoute = parse(clean(window.location.href), routes)
let state = Object.assign({
previousDocument: null,
}, initialRoute)
function emit(ev) {
return events[ev] ? events[ev].map(fn => fn(state)) : []
}
function done (doc, body, route, pop) {
state.previousDocument = doc.cloneNode(true)
Promise.all(
middleware.concat(route.handler || []).map(fn => fn(state))
).then(() => {
requestAnimationFrame(() => {
root.innerHTML = body
emit('after')
// after out-transitions
route.hash && emit('hash')
})
})
}
function get (href, route, cb) {
if (!route) return window.location.href = href
fetch(href, { credentials: 'include' })
.then(res => res.text())
.then(res => {
const doc = new window.DOMParser().parseFromString(res, 'text/html')
const c = [
doc,
doc.querySelector(selector).innerHTML
]
cache.set(href, c)
cb && cb(c[0], c[1], route)
})
}
function go (href, route, pop) {
queue = () => {
const cached = cache.get(href)
cached && route.cache !== false ? (
done(cached[0], cached[1], route, pop)
) : (
get(href, route, done)
)
}
Object.assign(state, route)
// allows for redirects
Promise.all(emit('before')).then(queue)
}
function match (url) {
const href = clean(url)
const route = parse(href, routes)
return [ href, route ]
}
document.body.addEventListener('click', e => {
if (e.ctrlKey || e.metaKey || e.altKey || e.shiftKey || e.defaultPrevented) return
let a = e.target
while (a && !(a.href && a.nodeName === 'A')) {
a = a.parentNode
}
if (!a) return e
const [ href, route ] = match(a.href)
if (route.ignore) return e
/**
* If a hash points to a location on the current page,
* update state with the hash, emit the event, and return,
* since we don't need to navigate anywhere.
*/
if (state.pathname === route.pathname && route.hash) {
e.preventDefault()
Object.assign(state, route)
emit('hash')
return e
}
if (
window.location.origin !== a.origin // external link
|| a.hasAttribute('download')
|| a.target === '_blank'
|| /^(?:mailto|tel):/.test(a.href)
|| a.classList.contains('no-ajax')
) return e
e.preventDefault()
state.location !== href && go(href, route, false)
emit('navigate', state)
return false
})
window.addEventListener('popstate', e => {
if (e.target.location.pathname === state.pathname) return // prevent popstate on hashchange
go(...match(e.target.location.href), true)
return false
})
return {
get state () {
return state
},
go (url) {
queue = null
go(...match(url), false)
},
load (href, cb) {
return get(...match(href, false), cb)
},
on (ev, fn) {
events[ev] = events[ev] ? events[ev].concat(fn) : [ fn ]
return () => events[ev].slice(events[ev].indexOf(fn), 1)
}
}
}