UNPKG

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