-
Notifications
You must be signed in to change notification settings - Fork 0
/
history.js
59 lines (55 loc) · 1.2 KB
/
history.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
import canUseDOM from './can-use-dom.js'
// TODO see if it makes sense to use the history module instead
const browser = () => ({
back() {
window.history.back()
},
forward() {
window.history.forward()
},
getUri() {
return window.location.href
},
onChange(listener) {
window.addEventListener('popstate', listener)
return () => window.removeEventListener('popstate', listener)
},
push(uri) {
window.history.pushState(null, null, uri)
}
})
const memory = initialUri => {
let current = 0
let history = [initialUri]
let listeners = []
return {
back() {
if (current > 0) {
current--
}
listeners.forEach(l => l())
},
forward() {
if (current < history.length - 1) {
current++
}
listeners.forEach(l => l())
},
getUri() {
return history[current]
},
onChange(listener) {
listeners.push(listener)
return () => {
listeners = listeners.filter(l => l !== listener)
}
},
push(uri) {
history = history.slice(0, current).concat(uri)
current = history.length - 1
}
}
}
export default initialUri => (
canUseDOM ? browser(initialUri) : memory(initialUri)
)