UNPKG

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