1 | import { nanoid } from 'nanoid/non-secure';
|
2 | export default function createMemoryHistory() {
|
3 | let index = 0;
|
4 | let items = []; // Pending callbacks for `history.go(n)`
|
5 | // We might modify the callback stored if it was interrupted, so we have a ref to identify it
|
6 |
|
7 | const pending = [];
|
8 |
|
9 | const interrupt = () => {
|
10 | // If another history operation was performed we need to interrupt existing ones
|
11 | // This makes sure that calls such as `history.replace` after `history.go` don't happen
|
12 | // Since otherwise it won't be correct if something else has changed
|
13 | pending.forEach(it => {
|
14 | const cb = it.cb;
|
15 |
|
16 | it.cb = () => cb(true);
|
17 | });
|
18 | };
|
19 |
|
20 | const history = {
|
21 | get index() {
|
22 | var _window$history$state;
|
23 |
|
24 | // We store an id in the state instead of an index
|
25 | // Index could get out of sync with in-memory values if page reloads
|
26 | const id = (_window$history$state = window.history.state) === null || _window$history$state === void 0 ? void 0 : _window$history$state.id;
|
27 |
|
28 | if (id) {
|
29 | const index = items.findIndex(item => item.id === id);
|
30 | return index > -1 ? index : 0;
|
31 | }
|
32 |
|
33 | return 0;
|
34 | },
|
35 |
|
36 | get(index) {
|
37 | return items[index];
|
38 | },
|
39 |
|
40 | backIndex(_ref) {
|
41 | let {
|
42 | path
|
43 | } = _ref;
|
44 |
|
45 | // We need to find the index from the element before current to get closest path to go back to
|
46 | for (let i = index - 1; i >= 0; i--) {
|
47 | const item = items[i];
|
48 |
|
49 | if (item.path === path) {
|
50 | return i;
|
51 | }
|
52 | }
|
53 |
|
54 | return -1;
|
55 | },
|
56 |
|
57 | push(_ref2) {
|
58 | let {
|
59 | path,
|
60 | state
|
61 | } = _ref2;
|
62 | interrupt();
|
63 | const id = nanoid(); // When a new entry is pushed, all the existing entries after index will be inaccessible
|
64 | // So we remove any existing entries after the current index to clean them up
|
65 |
|
66 | items = items.slice(0, index + 1);
|
67 | items.push({
|
68 | path,
|
69 | state,
|
70 | id
|
71 | });
|
72 | index = items.length - 1; // We pass empty string for title because it's ignored in all browsers except safari
|
73 | // We don't store state object in history.state because:
|
74 | // - browsers have limits on how big it can be, and we don't control the size
|
75 | // - while not recommended, there could be non-serializable data in state
|
76 |
|
77 | window.history.pushState({
|
78 | id
|
79 | }, '', path);
|
80 | },
|
81 |
|
82 | replace(_ref3) {
|
83 | var _window$history$state2, _window$history$state3;
|
84 |
|
85 | let {
|
86 | path,
|
87 | state
|
88 | } = _ref3;
|
89 | interrupt();
|
90 | const id = (_window$history$state2 = (_window$history$state3 = window.history.state) === null || _window$history$state3 === void 0 ? void 0 : _window$history$state3.id) !== null && _window$history$state2 !== void 0 ? _window$history$state2 : nanoid();
|
91 |
|
92 | if (!items.length || items.findIndex(item => item.id === id) < 0) {
|
93 | // There are two scenarios for creating an array with only one history record:
|
94 | // - When loaded id not found in the items array, this function by default will replace
|
95 | // the first item. We need to keep only the new updated object, otherwise it will break
|
96 | // the page when navigating forward in history.
|
97 | // - This is the first time any state modifications are done
|
98 | // So we need to push the entry as there's nothing to replace
|
99 | items = [{
|
100 | path,
|
101 | state,
|
102 | id
|
103 | }];
|
104 | index = 0;
|
105 | } else {
|
106 | items[index] = {
|
107 | path,
|
108 | state,
|
109 | id
|
110 | };
|
111 | }
|
112 |
|
113 | window.history.replaceState({
|
114 | id
|
115 | }, '', path);
|
116 | },
|
117 |
|
118 | // `history.go(n)` is asynchronous, there are couple of things to keep in mind:
|
119 | // - it won't do anything if we can't go `n` steps, the `popstate` event won't fire.
|
120 | // - each `history.go(n)` call will trigger a separate `popstate` event with correct location.
|
121 | // - the `popstate` event fires before the next frame after calling `history.go(n)`.
|
122 | // This method differs from `history.go(n)` in the sense that it'll go back as many steps it can.
|
123 | go(n) {
|
124 | interrupt(); // To guard against unexpected navigation out of the app we will assume that browser history is only as deep as the length of our memory
|
125 | // history. If we don't have an item to navigate to then update our index and navigate as far as we can without taking the user out of the app.
|
126 |
|
127 | const nextIndex = index + n;
|
128 | const lastItemIndex = items.length - 1;
|
129 |
|
130 | if (n < 0 && !items[nextIndex]) {
|
131 | // Attempted to navigate beyond the first index. Negating the current index will align the browser history with the first item.
|
132 | n = -index;
|
133 | index = 0;
|
134 | } else if (n > 0 && nextIndex > lastItemIndex) {
|
135 | // Attempted to navigate past the last index. Calculate how many indices away from the last index and go there.
|
136 | n = lastItemIndex - index;
|
137 | index = lastItemIndex;
|
138 | } else {
|
139 | index = nextIndex;
|
140 | }
|
141 |
|
142 | if (n === 0) {
|
143 | return;
|
144 | } // When we call `history.go`, `popstate` will fire when there's history to go back to
|
145 | // So we need to somehow handle following cases:
|
146 | // - There's history to go back, `history.go` is called, and `popstate` fires
|
147 | // - `history.go` is called multiple times, we need to resolve on respective `popstate`
|
148 | // - No history to go back, but `history.go` was called, browser has no API to detect it
|
149 |
|
150 |
|
151 | return new Promise((resolve, reject) => {
|
152 | const done = interrupted => {
|
153 | clearTimeout(timer);
|
154 |
|
155 | if (interrupted) {
|
156 | reject(new Error('History was changed during navigation.'));
|
157 | return;
|
158 | } // There seems to be a bug in Chrome regarding updating the title
|
159 | // If we set a title just before calling `history.go`, the title gets lost
|
160 | // However the value of `document.title` is still what we set it to
|
161 | // It's just not displayed in the tab bar
|
162 | // To update the tab bar, we need to reset the title to something else first (e.g. '')
|
163 | // And set the title to what it was before so it gets applied
|
164 | // It won't work without setting it to empty string coz otherwise title isn't changing
|
165 | // Which means that the browser won't do anything after setting the title
|
166 |
|
167 |
|
168 | const {
|
169 | title
|
170 | } = window.document;
|
171 | window.document.title = '';
|
172 | window.document.title = title;
|
173 | resolve();
|
174 | };
|
175 |
|
176 | pending.push({
|
177 | ref: done,
|
178 | cb: done
|
179 | }); // If navigation didn't happen within 100ms, assume that it won't happen
|
180 | // This may not be accurate, but hopefully it won't take so much time
|
181 | // In Chrome, navigation seems to happen instantly in next microtask
|
182 | // But on Firefox, it seems to take much longer, around 50ms from our testing
|
183 | // We're using a hacky timeout since there doesn't seem to be way to know for sure
|
184 |
|
185 | const timer = setTimeout(() => {
|
186 | const index = pending.findIndex(it => it.ref === done);
|
187 |
|
188 | if (index > -1) {
|
189 | pending[index].cb();
|
190 | pending.splice(index, 1);
|
191 | }
|
192 | }, 100);
|
193 |
|
194 | const onPopState = () => {
|
195 | var _window$history$state4;
|
196 |
|
197 | const id = (_window$history$state4 = window.history.state) === null || _window$history$state4 === void 0 ? void 0 : _window$history$state4.id;
|
198 | const currentIndex = items.findIndex(item => item.id === id); // Fix createMemoryHistory.index variable's value
|
199 | // as it may go out of sync when navigating in the browser.
|
200 |
|
201 | index = Math.max(currentIndex, 0);
|
202 | const last = pending.pop();
|
203 | window.removeEventListener('popstate', onPopState);
|
204 | last === null || last === void 0 ? void 0 : last.cb();
|
205 | };
|
206 |
|
207 | window.addEventListener('popstate', onPopState);
|
208 | window.history.go(n);
|
209 | });
|
210 | },
|
211 |
|
212 | // The `popstate` event is triggered when history changes, except `pushState` and `replaceState`
|
213 | // If we call `history.go(n)` ourselves, we don't want it to trigger the listener
|
214 | // Here we normalize it so that only external changes (e.g. user pressing back/forward) trigger the listener
|
215 | listen(listener) {
|
216 | const onPopState = () => {
|
217 | if (pending.length) {
|
218 | // This was triggered by `history.go(n)`, we shouldn't call the listener
|
219 | return;
|
220 | }
|
221 |
|
222 | listener();
|
223 | };
|
224 |
|
225 | window.addEventListener('popstate', onPopState);
|
226 | return () => window.removeEventListener('popstate', onPopState);
|
227 | }
|
228 |
|
229 | };
|
230 | return history;
|
231 | }
|
232 | //# sourceMappingURL=createMemoryHistory.js.map |
\ | No newline at end of file |