Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

history.js

115 lines2.9 KB

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