UNPKG

12 kBJavaScriptView Raw
1/**
2 * react-router v8.5.3
3 *
4 * Copyright (c) Remix Software Inc.
5 *
6 * This source code is licensed under the MIT license found in the
7 * LICENSE.md file in the root directory of this source tree.
8 *
9 * @license MIT
10 */
11import { PROTOCOL_RELATIVE_URL_REGEX } from "./url.js";
12//#region lib/router/history.ts
13/**
14* Actions represent the type of change to a location value.
15*/
16let Action = /* @__PURE__ */ function(Action) {
17 /**
18 * A POP indicates a change to an arbitrary index in the history stack, such
19 * as a back or forward navigation. It does not describe the direction of the
20 * navigation, only that the current index changed.
21 *
22 * Note: This is the default action for newly created history objects.
23 */
24 Action["Pop"] = "POP";
25 /**
26 * A PUSH indicates a new entry being added to the history stack, such as when
27 * a link is clicked and a new page loads. When this happens, all subsequent
28 * entries in the stack are lost.
29 */
30 Action["Push"] = "PUSH";
31 /**
32 * A REPLACE indicates the entry at the current index in the history stack
33 * being replaced by a new one.
34 */
35 Action["Replace"] = "REPLACE";
36 return Action;
37}({});
38const PopStateEventType = "popstate";
39function isLocation(obj) {
40 return typeof obj === "object" && obj != null && "pathname" in obj && "search" in obj && "hash" in obj && "state" in obj && "key" in obj;
41}
42/**
43* Memory history stores the current location in memory. It is designed for use
44* in stateful non-browser environments like tests and React Native.
45*/
46function createMemoryHistory(options = {}) {
47 let { initialEntries = ["/"], initialIndex, v5Compat = false } = options;
48 let entries;
49 entries = initialEntries.map((entry, index) => createMemoryLocation(entry, typeof entry === "string" ? null : entry.state, index === 0 ? "default" : void 0, typeof entry === "string" ? void 0 : entry.mask));
50 let index = clampIndex(initialIndex == null ? entries.length - 1 : initialIndex);
51 let action = "POP";
52 let listener = null;
53 function clampIndex(n) {
54 return Math.min(Math.max(n, 0), entries.length - 1);
55 }
56 function getCurrentLocation() {
57 return entries[index];
58 }
59 function createMemoryLocation(to, state = null, key, mask) {
60 let location = createLocation(entries ? getCurrentLocation().pathname : "/", to, state, key, mask);
61 warning(location.pathname.charAt(0) === "/", `relative pathnames are not supported in memory history: ${JSON.stringify(to)}`);
62 return location;
63 }
64 function createHref(to) {
65 return typeof to === "string" ? to : createPath(to);
66 }
67 return {
68 get index() {
69 return index;
70 },
71 get action() {
72 return action;
73 },
74 get location() {
75 return getCurrentLocation();
76 },
77 createHref,
78 createURL(to) {
79 return new URL(createHref(to), "http://localhost");
80 },
81 encodeLocation(to) {
82 let path = typeof to === "string" ? parsePath(to) : to;
83 return {
84 pathname: path.pathname || "",
85 search: path.search || "",
86 hash: path.hash || ""
87 };
88 },
89 push(to, state) {
90 action = "PUSH";
91 let nextLocation = isLocation(to) ? to : createMemoryLocation(to, state);
92 index += 1;
93 entries.splice(index, entries.length, nextLocation);
94 if (v5Compat && listener) listener({
95 action,
96 location: nextLocation,
97 delta: 1
98 });
99 },
100 replace(to, state) {
101 action = "REPLACE";
102 let nextLocation = isLocation(to) ? to : createMemoryLocation(to, state);
103 entries[index] = nextLocation;
104 if (v5Compat && listener) listener({
105 action,
106 location: nextLocation,
107 delta: 0
108 });
109 },
110 go(delta) {
111 action = "POP";
112 let nextIndex = clampIndex(index + delta);
113 let nextLocation = entries[nextIndex];
114 let actualDelta = nextIndex - index;
115 index = nextIndex;
116 if (listener) listener({
117 action,
118 location: nextLocation,
119 delta: actualDelta
120 });
121 },
122 listen(fn) {
123 listener = fn;
124 return () => {
125 listener = null;
126 };
127 }
128 };
129}
130/**
131* Browser history stores the location in regular URLs. This is the standard for
132* most web apps, but it requires some configuration on the server to ensure you
133* serve the same app at multiple URLs.
134*
135* @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory
136*/
137function createBrowserHistory(options = {}) {
138 function createBrowserLocation(window, globalHistory) {
139 let maskedLocation = globalHistory.state?.masked;
140 let { pathname, search, hash } = maskedLocation || window.location;
141 return createLocation("", {
142 pathname,
143 search,
144 hash
145 }, globalHistory.state && globalHistory.state.usr || null, globalHistory.state && globalHistory.state.key || "default", maskedLocation ? {
146 pathname: window.location.pathname,
147 search: window.location.search,
148 hash: window.location.hash
149 } : void 0);
150 }
151 function createBrowserHref(window, to) {
152 return typeof to === "string" ? to : createPath(to);
153 }
154 return getUrlBasedHistory(createBrowserLocation, createBrowserHref, null, options);
155}
156/**
157* Hash history stores the location in window.location.hash. This makes it ideal
158* for situations where you don't want to send the location to the server for
159* some reason, either because you do cannot configure it or the URL space is
160* reserved for something else.
161*
162* @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory
163*/
164function createHashHistory(options = {}) {
165 function createHashLocation(window, globalHistory) {
166 let { pathname = "/", search = "", hash = "" } = parsePath(window.location.hash.substring(1));
167 if (!pathname.startsWith("/") && !pathname.startsWith(".")) pathname = "/" + pathname;
168 let maskedLocation = globalHistory.state?.masked;
169 return createLocation("", maskedLocation || {
170 pathname,
171 search,
172 hash
173 }, globalHistory.state && globalHistory.state.usr || null, globalHistory.state && globalHistory.state.key || "default", maskedLocation ? {
174 pathname,
175 search,
176 hash
177 } : void 0);
178 }
179 function createHashHref(window, to) {
180 let base = window.document.querySelector("base");
181 let href = "";
182 if (base && base.getAttribute("href")) {
183 let url = window.location.href;
184 let hashIndex = url.indexOf("#");
185 href = hashIndex === -1 ? url : url.slice(0, hashIndex);
186 }
187 return href + "#" + (typeof to === "string" ? to : createPath(to));
188 }
189 function validateHashLocation(location, to) {
190 warning(location.pathname.charAt(0) === "/", `relative pathnames are not supported in hash history.push(${JSON.stringify(to)})`);
191 }
192 return getUrlBasedHistory(createHashLocation, createHashHref, validateHashLocation, options);
193}
194function invariant(value, message) {
195 if (value === false || value === null || typeof value === "undefined") throw new Error(message);
196}
197function warning(cond, message) {
198 if (!cond) {
199 if (typeof console !== "undefined") console.warn(message);
200 try {
201 throw new Error(message);
202 } catch {}
203 }
204}
205function createKey() {
206 return Math.random().toString(36).substring(2, 10);
207}
208/**
209* For browser-based histories, we combine the state and key into an object
210*/
211function getHistoryState(location, index) {
212 return {
213 usr: location.state,
214 key: location.key,
215 idx: index,
216 masked: location.mask ? {
217 pathname: location.pathname,
218 search: location.search,
219 hash: location.hash
220 } : void 0
221 };
222}
223/**
224* Creates a Location object with a unique key from the given Path
225*/
226function createLocation(current, to, state = null, key, mask) {
227 return {
228 pathname: typeof current === "string" ? current : current.pathname,
229 search: "",
230 hash: "",
231 ...typeof to === "string" ? parsePath(to) : to,
232 state,
233 key: to && to.key || key || createKey(),
234 mask
235 };
236}
237/**
238* Creates a string URL path from the given pathname, search, and hash components.
239*
240* @public
241* @category Utils
242* @param path The pathname, search, and hash components to combine.
243* @returns The combined URL path.
244*/
245function createPath({ pathname = "/", search = "", hash = "" }) {
246 if (search && search !== "?") pathname += search.charAt(0) === "?" ? search : "?" + search;
247 if (hash && hash !== "#") pathname += hash.charAt(0) === "#" ? hash : "#" + hash;
248 return pathname;
249}
250/**
251* Parses a string URL path into its separate pathname, search, and hash components.
252*
253* @public
254* @category Utils
255* @param path The URL path to parse.
256* @returns The parsed pathname, search, and hash components.
257*/
258function parsePath(path) {
259 let parsedPath = {};
260 if (path) {
261 let hashIndex = path.indexOf("#");
262 if (hashIndex >= 0) {
263 parsedPath.hash = path.substring(hashIndex);
264 path = path.substring(0, hashIndex);
265 }
266 let searchIndex = path.indexOf("?");
267 if (searchIndex >= 0) {
268 parsedPath.search = path.substring(searchIndex);
269 path = path.substring(0, searchIndex);
270 }
271 if (path) parsedPath.pathname = path;
272 }
273 return parsedPath;
274}
275function getUrlBasedHistory(getLocation, createHref, validateLocation, options = {}) {
276 let { window = document.defaultView, v5Compat = false } = options;
277 let globalHistory = window.history;
278 let action = "POP";
279 let listener = null;
280 let index = getIndex();
281 if (index == null) {
282 index = 0;
283 globalHistory.replaceState({
284 ...globalHistory.state,
285 idx: index
286 }, "");
287 }
288 function getIndex() {
289 return (globalHistory.state || { idx: null }).idx;
290 }
291 function handlePop() {
292 action = "POP";
293 let nextIndex = getIndex();
294 let delta = nextIndex == null ? null : nextIndex - index;
295 index = nextIndex;
296 if (listener) listener({
297 action,
298 location: history.location,
299 delta
300 });
301 }
302 function push(to, state) {
303 action = "PUSH";
304 let location = isLocation(to) ? to : createLocation(history.location, to, state);
305 if (validateLocation) validateLocation(location, to);
306 index = getIndex() + 1;
307 let historyState = getHistoryState(location, index);
308 let url = history.createHref(location.mask || location);
309 try {
310 globalHistory.pushState(historyState, "", url);
311 } catch (error) {
312 if (error instanceof DOMException && error.name === "DataCloneError") throw error;
313 window.location.assign(url);
314 }
315 if (v5Compat && listener) listener({
316 action,
317 location: history.location,
318 delta: 1
319 });
320 }
321 function replace(to, state) {
322 action = "REPLACE";
323 let location = isLocation(to) ? to : createLocation(history.location, to, state);
324 if (validateLocation) validateLocation(location, to);
325 index = getIndex();
326 let historyState = getHistoryState(location, index);
327 let url = history.createHref(location.mask || location);
328 globalHistory.replaceState(historyState, "", url);
329 if (v5Compat && listener) listener({
330 action,
331 location: history.location,
332 delta: 0
333 });
334 }
335 function createURL(to) {
336 return createBrowserURLImpl(window, to);
337 }
338 let history = {
339 get action() {
340 return action;
341 },
342 get location() {
343 return getLocation(window, globalHistory);
344 },
345 listen(fn) {
346 if (listener) throw new Error("A history only accepts one active listener");
347 window.addEventListener(PopStateEventType, handlePop);
348 listener = fn;
349 return () => {
350 window.removeEventListener(PopStateEventType, handlePop);
351 listener = null;
352 };
353 },
354 createHref(to) {
355 return createHref(window, to);
356 },
357 createURL,
358 encodeLocation(to) {
359 let url = createURL(to);
360 return {
361 pathname: url.pathname,
362 search: url.search,
363 hash: url.hash
364 };
365 },
366 push,
367 replace,
368 go(n) {
369 return globalHistory.go(n);
370 }
371 };
372 return history;
373}
374function createBrowserURLImpl(windowImpl, to, isAbsolute = false) {
375 let base = "http://localhost";
376 if (windowImpl) base = windowImpl.location.origin !== "null" ? windowImpl.location.origin : windowImpl.location.href;
377 invariant(base, "No window.location.(origin|href) available to create URL");
378 let href = typeof to === "string" ? to : createPath(to);
379 href = href.replace(/ $/, "%20");
380 if (!isAbsolute && PROTOCOL_RELATIVE_URL_REGEX.test(href)) href = base + href;
381 return new URL(href, base);
382}
383//#endregion
384export { Action, createBrowserHistory, createBrowserURLImpl, createHashHistory, createLocation, createMemoryHistory, createPath, invariant, parsePath, warning };