Open History to see the last commit
1// Most of these utilities have been respectfully
2// copied or modified from @reach/router by Ryan Florence
3// and their licenses have been included in this project.
4// Thanks Ryan!
5β
6function getLocation(source) {
7 return {
8 ...source.location,
9 state: source.history.state,
10 id: (source.history.state && source.history.state.id) || 'initial',
11 }
12}
13β
14export function createHistory(source) {
15 let listeners = []
16 let location = getLocation(source)
17 let transitioning = false
18 let resolveTransition = () => {}
19β
20 return {
21 get location() {
22 return location
23 },
24β
25 get transitioning() {
26 return transitioning
27 },
28β
29 _onTransitionComplete() {
30 transitioning = false
31 resolveTransition()
32 },
33β
34 listen(listener) {
35 listeners.push(listener)
36β
37 const popstateListener = () => {
38 location = getLocation(source)
39 listener({ location, action: 'POP' })
40 }
41β
42 source.addEventListener('popstate', popstateListener)
43β
44 return () => {
45 source.removeEventListener('popstate', popstateListener)
46 listeners = listeners.filter(fn => fn !== listener)
47 }
48 },
49β
50 _navigate(to, { state, replace = false } = {}) {
51 state = { ...state, id: `${Date.now()}` }
52 // try...catch iOS Safari limits to 100 pushState calls
53 try {
54 if (transitioning || replace) {
55 source.history.replaceState(state, null, to)
56 } else {
57 source.history.pushState(state, null, to)
58 }
59 } catch (e) {
60 source.location[replace ? 'replace' : 'assign'](to)
61 }
62β
63 location = getLocation(source)
64 transitioning = true
65 const transition = new Promise(resolve => {
66 resolveTransition = resolve
67 })
68 // setTimeout here to ensure that any unsubs have run before we try and notify them
69 setTimeout(() => {
70 listeners.forEach(listener => listener({ location, action: 'PUSH' }))
71 }, 1)
72 return transition
73 },
74 }
75}
76β
77export function createMemorySource(initialPathname = '/') {
78 let index = 0
79 const stack = [{ pathname: initialPathname, search: '', hash: '' }]
80 const states = []
81β
82 return {
83 get location() {
84 return stack[index]
85 },
86 addEventListener() {},
87 removeEventListener() {},
88 history: {
89 get entries() {
90 return stack
91 },
92 get index() {
93 return index
94 },
95 get state() {
96 return states[index]
97 },
98 pushState(state, _, href) {
99 const [pathname, search = ''] = href.split('?')
100 const hash = pathname.includes('#')
101 ? pathname.split('#').reverse()[0]
102 : ''
103 index += 1
104 stack.push({ pathname, search, href, hash })
105 states.push(state)
106 },
107 replaceState(state, _, href) {
108 const [pathname, search = ''] = href.split('?')
109 const hash = pathname.includes('#')
110 ? pathname.split('#').reverse()[0]
111 : ''
112 stack[index] = { pathname, search, href, hash }
113 states[index] = state
114 },
115 },
116 }
117}