history.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746
  1. ////////////////////////////////////////////////////////////////////////////////
  2. //#region Types and Constants
  3. ////////////////////////////////////////////////////////////////////////////////
  4. /**
  5. * Actions represent the type of change to a location value.
  6. */
  7. export enum Action {
  8. /**
  9. * A POP indicates a change to an arbitrary index in the history stack, such
  10. * as a back or forward navigation. It does not describe the direction of the
  11. * navigation, only that the current index changed.
  12. *
  13. * Note: This is the default action for newly created history objects.
  14. */
  15. Pop = "POP",
  16. /**
  17. * A PUSH indicates a new entry being added to the history stack, such as when
  18. * a link is clicked and a new page loads. When this happens, all subsequent
  19. * entries in the stack are lost.
  20. */
  21. Push = "PUSH",
  22. /**
  23. * A REPLACE indicates the entry at the current index in the history stack
  24. * being replaced by a new one.
  25. */
  26. Replace = "REPLACE",
  27. }
  28. /**
  29. * The pathname, search, and hash values of a URL.
  30. */
  31. export interface Path {
  32. /**
  33. * A URL pathname, beginning with a /.
  34. */
  35. pathname: string;
  36. /**
  37. * A URL search string, beginning with a ?.
  38. */
  39. search: string;
  40. /**
  41. * A URL fragment identifier, beginning with a #.
  42. */
  43. hash: string;
  44. }
  45. // TODO: (v7) Change the Location generic default from `any` to `unknown` and
  46. // remove Remix `useLocation` wrapper.
  47. /**
  48. * An entry in a history stack. A location contains information about the
  49. * URL path, as well as possibly some arbitrary state and a key.
  50. */
  51. export interface Location<State = any> extends Path {
  52. /**
  53. * A value of arbitrary data associated with this location.
  54. */
  55. state: State;
  56. /**
  57. * A unique string associated with this location. May be used to safely store
  58. * and retrieve data in some other storage API, like `localStorage`.
  59. *
  60. * Note: This value is always "default" on the initial location.
  61. */
  62. key: string;
  63. }
  64. /**
  65. * A change to the current location.
  66. */
  67. export interface Update {
  68. /**
  69. * The action that triggered the change.
  70. */
  71. action: Action;
  72. /**
  73. * The new location.
  74. */
  75. location: Location;
  76. /**
  77. * The delta between this location and the former location in the history stack
  78. */
  79. delta: number | null;
  80. }
  81. /**
  82. * A function that receives notifications about location changes.
  83. */
  84. export interface Listener {
  85. (update: Update): void;
  86. }
  87. /**
  88. * Describes a location that is the destination of some navigation, either via
  89. * `history.push` or `history.replace`. This may be either a URL or the pieces
  90. * of a URL path.
  91. */
  92. export type To = string | Partial<Path>;
  93. /**
  94. * A history is an interface to the navigation stack. The history serves as the
  95. * source of truth for the current location, as well as provides a set of
  96. * methods that may be used to change it.
  97. *
  98. * It is similar to the DOM's `window.history` object, but with a smaller, more
  99. * focused API.
  100. */
  101. export interface History {
  102. /**
  103. * The last action that modified the current location. This will always be
  104. * Action.Pop when a history instance is first created. This value is mutable.
  105. */
  106. readonly action: Action;
  107. /**
  108. * The current location. This value is mutable.
  109. */
  110. readonly location: Location;
  111. /**
  112. * Returns a valid href for the given `to` value that may be used as
  113. * the value of an <a href> attribute.
  114. *
  115. * @param to - The destination URL
  116. */
  117. createHref(to: To): string;
  118. /**
  119. * Returns a URL for the given `to` value
  120. *
  121. * @param to - The destination URL
  122. */
  123. createURL(to: To): URL;
  124. /**
  125. * Encode a location the same way window.history would do (no-op for memory
  126. * history) so we ensure our PUSH/REPLACE navigations for data routers
  127. * behave the same as POP
  128. *
  129. * @param to Unencoded path
  130. */
  131. encodeLocation(to: To): Path;
  132. /**
  133. * Pushes a new location onto the history stack, increasing its length by one.
  134. * If there were any entries in the stack after the current one, they are
  135. * lost.
  136. *
  137. * @param to - The new URL
  138. * @param state - Data to associate with the new location
  139. */
  140. push(to: To, state?: any): void;
  141. /**
  142. * Replaces the current location in the history stack with a new one. The
  143. * location that was replaced will no longer be available.
  144. *
  145. * @param to - The new URL
  146. * @param state - Data to associate with the new location
  147. */
  148. replace(to: To, state?: any): void;
  149. /**
  150. * Navigates `n` entries backward/forward in the history stack relative to the
  151. * current index. For example, a "back" navigation would use go(-1).
  152. *
  153. * @param delta - The delta in the stack index
  154. */
  155. go(delta: number): void;
  156. /**
  157. * Sets up a listener that will be called whenever the current location
  158. * changes.
  159. *
  160. * @param listener - A function that will be called when the location changes
  161. * @returns unlisten - A function that may be used to stop listening
  162. */
  163. listen(listener: Listener): () => void;
  164. }
  165. type HistoryState = {
  166. usr: any;
  167. key?: string;
  168. idx: number;
  169. };
  170. const PopStateEventType = "popstate";
  171. //#endregion
  172. ////////////////////////////////////////////////////////////////////////////////
  173. //#region Memory History
  174. ////////////////////////////////////////////////////////////////////////////////
  175. /**
  176. * A user-supplied object that describes a location. Used when providing
  177. * entries to `createMemoryHistory` via its `initialEntries` option.
  178. */
  179. export type InitialEntry = string | Partial<Location>;
  180. export type MemoryHistoryOptions = {
  181. initialEntries?: InitialEntry[];
  182. initialIndex?: number;
  183. v5Compat?: boolean;
  184. };
  185. /**
  186. * A memory history stores locations in memory. This is useful in stateful
  187. * environments where there is no web browser, such as node tests or React
  188. * Native.
  189. */
  190. export interface MemoryHistory extends History {
  191. /**
  192. * The current index in the history stack.
  193. */
  194. readonly index: number;
  195. }
  196. /**
  197. * Memory history stores the current location in memory. It is designed for use
  198. * in stateful non-browser environments like tests and React Native.
  199. */
  200. export function createMemoryHistory(
  201. options: MemoryHistoryOptions = {}
  202. ): MemoryHistory {
  203. let { initialEntries = ["/"], initialIndex, v5Compat = false } = options;
  204. let entries: Location[]; // Declare so we can access from createMemoryLocation
  205. entries = initialEntries.map((entry, index) =>
  206. createMemoryLocation(
  207. entry,
  208. typeof entry === "string" ? null : entry.state,
  209. index === 0 ? "default" : undefined
  210. )
  211. );
  212. let index = clampIndex(
  213. initialIndex == null ? entries.length - 1 : initialIndex
  214. );
  215. let action = Action.Pop;
  216. let listener: Listener | null = null;
  217. function clampIndex(n: number): number {
  218. return Math.min(Math.max(n, 0), entries.length - 1);
  219. }
  220. function getCurrentLocation(): Location {
  221. return entries[index];
  222. }
  223. function createMemoryLocation(
  224. to: To,
  225. state: any = null,
  226. key?: string
  227. ): Location {
  228. let location = createLocation(
  229. entries ? getCurrentLocation().pathname : "/",
  230. to,
  231. state,
  232. key
  233. );
  234. warning(
  235. location.pathname.charAt(0) === "/",
  236. `relative pathnames are not supported in memory history: ${JSON.stringify(
  237. to
  238. )}`
  239. );
  240. return location;
  241. }
  242. function createHref(to: To) {
  243. return typeof to === "string" ? to : createPath(to);
  244. }
  245. let history: MemoryHistory = {
  246. get index() {
  247. return index;
  248. },
  249. get action() {
  250. return action;
  251. },
  252. get location() {
  253. return getCurrentLocation();
  254. },
  255. createHref,
  256. createURL(to) {
  257. return new URL(createHref(to), "http://localhost");
  258. },
  259. encodeLocation(to: To) {
  260. let path = typeof to === "string" ? parsePath(to) : to;
  261. return {
  262. pathname: path.pathname || "",
  263. search: path.search || "",
  264. hash: path.hash || "",
  265. };
  266. },
  267. push(to, state) {
  268. action = Action.Push;
  269. let nextLocation = createMemoryLocation(to, state);
  270. index += 1;
  271. entries.splice(index, entries.length, nextLocation);
  272. if (v5Compat && listener) {
  273. listener({ action, location: nextLocation, delta: 1 });
  274. }
  275. },
  276. replace(to, state) {
  277. action = Action.Replace;
  278. let nextLocation = createMemoryLocation(to, state);
  279. entries[index] = nextLocation;
  280. if (v5Compat && listener) {
  281. listener({ action, location: nextLocation, delta: 0 });
  282. }
  283. },
  284. go(delta) {
  285. action = Action.Pop;
  286. let nextIndex = clampIndex(index + delta);
  287. let nextLocation = entries[nextIndex];
  288. index = nextIndex;
  289. if (listener) {
  290. listener({ action, location: nextLocation, delta });
  291. }
  292. },
  293. listen(fn: Listener) {
  294. listener = fn;
  295. return () => {
  296. listener = null;
  297. };
  298. },
  299. };
  300. return history;
  301. }
  302. //#endregion
  303. ////////////////////////////////////////////////////////////////////////////////
  304. //#region Browser History
  305. ////////////////////////////////////////////////////////////////////////////////
  306. /**
  307. * A browser history stores the current location in regular URLs in a web
  308. * browser environment. This is the standard for most web apps and provides the
  309. * cleanest URLs the browser's address bar.
  310. *
  311. * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#browserhistory
  312. */
  313. export interface BrowserHistory extends UrlHistory {}
  314. export type BrowserHistoryOptions = UrlHistoryOptions;
  315. /**
  316. * Browser history stores the location in regular URLs. This is the standard for
  317. * most web apps, but it requires some configuration on the server to ensure you
  318. * serve the same app at multiple URLs.
  319. *
  320. * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory
  321. */
  322. export function createBrowserHistory(
  323. options: BrowserHistoryOptions = {}
  324. ): BrowserHistory {
  325. function createBrowserLocation(
  326. window: Window,
  327. globalHistory: Window["history"]
  328. ) {
  329. let { pathname, search, hash } = window.location;
  330. return createLocation(
  331. "",
  332. { pathname, search, hash },
  333. // state defaults to `null` because `window.history.state` does
  334. (globalHistory.state && globalHistory.state.usr) || null,
  335. (globalHistory.state && globalHistory.state.key) || "default"
  336. );
  337. }
  338. function createBrowserHref(window: Window, to: To) {
  339. return typeof to === "string" ? to : createPath(to);
  340. }
  341. return getUrlBasedHistory(
  342. createBrowserLocation,
  343. createBrowserHref,
  344. null,
  345. options
  346. );
  347. }
  348. //#endregion
  349. ////////////////////////////////////////////////////////////////////////////////
  350. //#region Hash History
  351. ////////////////////////////////////////////////////////////////////////////////
  352. /**
  353. * A hash history stores the current location in the fragment identifier portion
  354. * of the URL in a web browser environment.
  355. *
  356. * This is ideal for apps that do not control the server for some reason
  357. * (because the fragment identifier is never sent to the server), including some
  358. * shared hosting environments that do not provide fine-grained controls over
  359. * which pages are served at which URLs.
  360. *
  361. * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#hashhistory
  362. */
  363. export interface HashHistory extends UrlHistory {}
  364. export type HashHistoryOptions = UrlHistoryOptions;
  365. /**
  366. * Hash history stores the location in window.location.hash. This makes it ideal
  367. * for situations where you don't want to send the location to the server for
  368. * some reason, either because you do cannot configure it or the URL space is
  369. * reserved for something else.
  370. *
  371. * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory
  372. */
  373. export function createHashHistory(
  374. options: HashHistoryOptions = {}
  375. ): HashHistory {
  376. function createHashLocation(
  377. window: Window,
  378. globalHistory: Window["history"]
  379. ) {
  380. let {
  381. pathname = "/",
  382. search = "",
  383. hash = "",
  384. } = parsePath(window.location.hash.substr(1));
  385. // Hash URL should always have a leading / just like window.location.pathname
  386. // does, so if an app ends up at a route like /#something then we add a
  387. // leading slash so all of our path-matching behaves the same as if it would
  388. // in a browser router. This is particularly important when there exists a
  389. // root splat route (<Route path="*">) since that matches internally against
  390. // "/*" and we'd expect /#something to 404 in a hash router app.
  391. if (!pathname.startsWith("/") && !pathname.startsWith(".")) {
  392. pathname = "/" + pathname;
  393. }
  394. return createLocation(
  395. "",
  396. { pathname, search, hash },
  397. // state defaults to `null` because `window.history.state` does
  398. (globalHistory.state && globalHistory.state.usr) || null,
  399. (globalHistory.state && globalHistory.state.key) || "default"
  400. );
  401. }
  402. function createHashHref(window: Window, to: To) {
  403. let base = window.document.querySelector("base");
  404. let href = "";
  405. if (base && base.getAttribute("href")) {
  406. let url = window.location.href;
  407. let hashIndex = url.indexOf("#");
  408. href = hashIndex === -1 ? url : url.slice(0, hashIndex);
  409. }
  410. return href + "#" + (typeof to === "string" ? to : createPath(to));
  411. }
  412. function validateHashLocation(location: Location, to: To) {
  413. warning(
  414. location.pathname.charAt(0) === "/",
  415. `relative pathnames are not supported in hash history.push(${JSON.stringify(
  416. to
  417. )})`
  418. );
  419. }
  420. return getUrlBasedHistory(
  421. createHashLocation,
  422. createHashHref,
  423. validateHashLocation,
  424. options
  425. );
  426. }
  427. //#endregion
  428. ////////////////////////////////////////////////////////////////////////////////
  429. //#region UTILS
  430. ////////////////////////////////////////////////////////////////////////////////
  431. /**
  432. * @private
  433. */
  434. export function invariant(value: boolean, message?: string): asserts value;
  435. export function invariant<T>(
  436. value: T | null | undefined,
  437. message?: string
  438. ): asserts value is T;
  439. export function invariant(value: any, message?: string) {
  440. if (value === false || value === null || typeof value === "undefined") {
  441. throw new Error(message);
  442. }
  443. }
  444. export function warning(cond: any, message: string) {
  445. if (!cond) {
  446. // eslint-disable-next-line no-console
  447. if (typeof console !== "undefined") console.warn(message);
  448. try {
  449. // Welcome to debugging history!
  450. //
  451. // This error is thrown as a convenience, so you can more easily
  452. // find the source for a warning that appears in the console by
  453. // enabling "pause on exceptions" in your JavaScript debugger.
  454. throw new Error(message);
  455. // eslint-disable-next-line no-empty
  456. } catch (e) {}
  457. }
  458. }
  459. function createKey() {
  460. return Math.random().toString(36).substr(2, 8);
  461. }
  462. /**
  463. * For browser-based histories, we combine the state and key into an object
  464. */
  465. function getHistoryState(location: Location, index: number): HistoryState {
  466. return {
  467. usr: location.state,
  468. key: location.key,
  469. idx: index,
  470. };
  471. }
  472. /**
  473. * Creates a Location object with a unique key from the given Path
  474. */
  475. export function createLocation(
  476. current: string | Location,
  477. to: To,
  478. state: any = null,
  479. key?: string
  480. ): Readonly<Location> {
  481. let location: Readonly<Location> = {
  482. pathname: typeof current === "string" ? current : current.pathname,
  483. search: "",
  484. hash: "",
  485. ...(typeof to === "string" ? parsePath(to) : to),
  486. state,
  487. // TODO: This could be cleaned up. push/replace should probably just take
  488. // full Locations now and avoid the need to run through this flow at all
  489. // But that's a pretty big refactor to the current test suite so going to
  490. // keep as is for the time being and just let any incoming keys take precedence
  491. key: (to && (to as Location).key) || key || createKey(),
  492. };
  493. return location;
  494. }
  495. /**
  496. * Creates a string URL path from the given pathname, search, and hash components.
  497. */
  498. export function createPath({
  499. pathname = "/",
  500. search = "",
  501. hash = "",
  502. }: Partial<Path>) {
  503. if (search && search !== "?")
  504. pathname += search.charAt(0) === "?" ? search : "?" + search;
  505. if (hash && hash !== "#")
  506. pathname += hash.charAt(0) === "#" ? hash : "#" + hash;
  507. return pathname;
  508. }
  509. /**
  510. * Parses a string URL path into its separate pathname, search, and hash components.
  511. */
  512. export function parsePath(path: string): Partial<Path> {
  513. let parsedPath: Partial<Path> = {};
  514. if (path) {
  515. let hashIndex = path.indexOf("#");
  516. if (hashIndex >= 0) {
  517. parsedPath.hash = path.substr(hashIndex);
  518. path = path.substr(0, hashIndex);
  519. }
  520. let searchIndex = path.indexOf("?");
  521. if (searchIndex >= 0) {
  522. parsedPath.search = path.substr(searchIndex);
  523. path = path.substr(0, searchIndex);
  524. }
  525. if (path) {
  526. parsedPath.pathname = path;
  527. }
  528. }
  529. return parsedPath;
  530. }
  531. export interface UrlHistory extends History {}
  532. export type UrlHistoryOptions = {
  533. window?: Window;
  534. v5Compat?: boolean;
  535. };
  536. function getUrlBasedHistory(
  537. getLocation: (window: Window, globalHistory: Window["history"]) => Location,
  538. createHref: (window: Window, to: To) => string,
  539. validateLocation: ((location: Location, to: To) => void) | null,
  540. options: UrlHistoryOptions = {}
  541. ): UrlHistory {
  542. let { window = document.defaultView!, v5Compat = false } = options;
  543. let globalHistory = window.history;
  544. let action = Action.Pop;
  545. let listener: Listener | null = null;
  546. let index = getIndex()!;
  547. // Index should only be null when we initialize. If not, it's because the
  548. // user called history.pushState or history.replaceState directly, in which
  549. // case we should log a warning as it will result in bugs.
  550. if (index == null) {
  551. index = 0;
  552. globalHistory.replaceState({ ...globalHistory.state, idx: index }, "");
  553. }
  554. function getIndex(): number {
  555. let state = globalHistory.state || { idx: null };
  556. return state.idx;
  557. }
  558. function handlePop() {
  559. action = Action.Pop;
  560. let nextIndex = getIndex();
  561. let delta = nextIndex == null ? null : nextIndex - index;
  562. index = nextIndex;
  563. if (listener) {
  564. listener({ action, location: history.location, delta });
  565. }
  566. }
  567. function push(to: To, state?: any) {
  568. action = Action.Push;
  569. let location = createLocation(history.location, to, state);
  570. if (validateLocation) validateLocation(location, to);
  571. index = getIndex() + 1;
  572. let historyState = getHistoryState(location, index);
  573. let url = history.createHref(location);
  574. // try...catch because iOS limits us to 100 pushState calls :/
  575. try {
  576. globalHistory.pushState(historyState, "", url);
  577. } catch (error) {
  578. // If the exception is because `state` can't be serialized, let that throw
  579. // outwards just like a replace call would so the dev knows the cause
  580. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#shared-history-push/replace-state-steps
  581. // https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeinternal
  582. if (error instanceof DOMException && error.name === "DataCloneError") {
  583. throw error;
  584. }
  585. // They are going to lose state here, but there is no real
  586. // way to warn them about it since the page will refresh...
  587. window.location.assign(url);
  588. }
  589. if (v5Compat && listener) {
  590. listener({ action, location: history.location, delta: 1 });
  591. }
  592. }
  593. function replace(to: To, state?: any) {
  594. action = Action.Replace;
  595. let location = createLocation(history.location, to, state);
  596. if (validateLocation) validateLocation(location, to);
  597. index = getIndex();
  598. let historyState = getHistoryState(location, index);
  599. let url = history.createHref(location);
  600. globalHistory.replaceState(historyState, "", url);
  601. if (v5Compat && listener) {
  602. listener({ action, location: history.location, delta: 0 });
  603. }
  604. }
  605. function createURL(to: To): URL {
  606. // window.location.origin is "null" (the literal string value) in Firefox
  607. // under certain conditions, notably when serving from a local HTML file
  608. // See https://bugzilla.mozilla.org/show_bug.cgi?id=878297
  609. let base =
  610. window.location.origin !== "null"
  611. ? window.location.origin
  612. : window.location.href;
  613. let href = typeof to === "string" ? to : createPath(to);
  614. // Treating this as a full URL will strip any trailing spaces so we need to
  615. // pre-encode them since they might be part of a matching splat param from
  616. // an ancestor route
  617. href = href.replace(/ $/, "%20");
  618. invariant(
  619. base,
  620. `No window.location.(origin|href) available to create URL for href: ${href}`
  621. );
  622. return new URL(href, base);
  623. }
  624. let history: History = {
  625. get action() {
  626. return action;
  627. },
  628. get location() {
  629. return getLocation(window, globalHistory);
  630. },
  631. listen(fn: Listener) {
  632. if (listener) {
  633. throw new Error("A history only accepts one active listener");
  634. }
  635. window.addEventListener(PopStateEventType, handlePop);
  636. listener = fn;
  637. return () => {
  638. window.removeEventListener(PopStateEventType, handlePop);
  639. listener = null;
  640. };
  641. },
  642. createHref(to) {
  643. return createHref(window, to);
  644. },
  645. createURL,
  646. encodeLocation(to) {
  647. // Encode a Location the same way window.location would
  648. let url = createURL(to);
  649. return {
  650. pathname: url.pathname,
  651. search: url.search,
  652. hash: url.hash,
  653. };
  654. },
  655. push,
  656. replace,
  657. go(n) {
  658. return globalHistory.go(n);
  659. },
  660. };
  661. return history;
  662. }
  663. //#endregion