Repository: remix-run/history Branch: dev Commit: 3e9dab413f4e Files: 67 Total size: 116.0 KB Directory structure: gitextract_djn_y9xh/ ├── .browserslistrc ├── .eslintignore ├── .eslintrc ├── .github/ │ ├── lock.yml │ └── workflows/ │ ├── format.yml │ ├── release.yml │ └── test.yml ├── .gitignore ├── .prettierignore ├── .prettierrc ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── docs/ │ ├── README.md │ ├── api-reference.md │ ├── blocking-transitions.md │ ├── getting-started.md │ ├── installation.md │ └── navigation.md ├── fixtures/ │ ├── block-library/ │ │ ├── index.html │ │ └── index.js │ ├── block-vanilla/ │ │ ├── index.html │ │ └── index.js │ ├── hash-click.html │ ├── hash-history-length.html │ └── unpkg-test.html ├── package.json ├── packages/ │ └── history/ │ ├── .eslintrc │ ├── __tests__/ │ │ ├── .eslintrc │ │ ├── TestSequences/ │ │ │ ├── BackButtonTransitionHook.js │ │ │ ├── BlockEverything.js │ │ │ ├── BlockPopWithoutListening.js │ │ │ ├── EncodedReservedCharacters.js │ │ │ ├── GoBack.js │ │ │ ├── GoForward.js │ │ │ ├── InitialLocationDefaultKey.js │ │ │ ├── InitialLocationHasKey.js │ │ │ ├── Listen.js │ │ │ ├── PushMissingPathname.js │ │ │ ├── PushNewLocation.js │ │ │ ├── PushRelativePathname.js │ │ │ ├── PushRelativePathnameWarning.js │ │ │ ├── PushSamePath.js │ │ │ ├── PushState.js │ │ │ ├── ReplaceNewLocation.js │ │ │ ├── ReplaceSamePath.js │ │ │ ├── ReplaceState.js │ │ │ └── utils.js │ │ ├── browser-test.js │ │ ├── create-path-test.js │ │ ├── hash-base-test.js │ │ ├── hash-test.js │ │ └── memory-test.js │ ├── browser.ts │ ├── hash.ts │ ├── index.ts │ ├── node-main.js │ └── package.json ├── scripts/ │ ├── build.js │ ├── karma.conf.js │ ├── publish.js │ ├── rollup/ │ │ └── history.config.js │ ├── test.js │ ├── tests.webpack.js │ └── version.js ├── tsconfig.json └── types/ └── global.d.ts ================================================ FILE CONTENTS ================================================ ================================================ FILE: .browserslistrc ================================================ # Browsers we support > 0.5% Chrome >= 73 ChromeAndroid >= 75 Firefox >= 67 Edge >= 17 IE 11 Safari >= 12.1 iOS >= 11.3 ================================================ FILE: .eslintignore ================================================ /build /fixtures node_modules/ ================================================ FILE: .eslintrc ================================================ { "extends": "react-app", "rules": { "import/no-anonymous-default-export": 0 } } ================================================ FILE: .github/lock.yml ================================================ # Configuration for lock-threads - https://github.com/dessant/lock-threads # Number of days of inactivity before a closed issue or pull request is locked daysUntilLock: 60 # Issues and pull requests with these labels will not be locked. Set to `[]` to disable exemptLabels: [] # Label to add before locking, such as `outdated`. Set to `false` to disable lockLabel: false # Comment to post before locking. Set to `false` to disable lockComment: false # Limit to only `issues` or `pulls` # only: issues # Optionally, specify configuration settings just for `issues` or `pulls` # issues: # exemptLabels: # - help-wanted # lockLabel: outdated # pulls: # daysUntilLock: 30 ================================================ FILE: .github/workflows/format.yml ================================================ name: Format on: push: branches: - main jobs: format: runs-on: ubuntu-latest steps: - name: Cancel Previous Runs uses: styfle/cancel-workflow-action@0.9.1 - name: Checkout Repository uses: actions/checkout@v2 - name: Use Node.js uses: actions/setup-node@v2 with: node-version: 14 - name: Install dependencies run: yarn install --frozen-lockfile - name: Format run: npm run format --if-present - name: Commit run: | git config --local user.email "github-actions@remix.run" git config --local user.name "Remix Run Bot" git add . if [ -z "$(git status --porcelain)" ]; then echo "💿 no formatting changed" exit 0 fi git commit -m "chore: format" -m "formatted $GITHUB_SHA" git push echo "💿 pushed formatting changes https://github.com/$GITHUB_REPOSITORY/commit/$(git rev-parse HEAD)" ================================================ FILE: .github/workflows/release.yml ================================================ name: release on: release: types: [published] jobs: release: if: github.repository == 'remix-run/history' runs-on: ubuntu-latest strategy: matrix: node-version: [14.x] steps: - uses: actions/checkout@v2 - name: Use Node.js ${{ matrix.node-version }} uses: actions/setup-node@v1 with: node-version: ${{ matrix.node-version }} # https://github.com/actions/setup-node/issues/213#issuecomment-833724757 - name: Install npm v7 run: npm i -g npm@7 --registry=https://registry.npmjs.org - name: Install dependencies run: npm ci - name: Build run: npm run build - name: Test run: npm run test & npm run size - name: Publish env: NPM_TOKEN: ${{ secrets.NPM_TOKEN }} run: | echo "//registry.npmjs.org/:_authToken=$NPM_TOKEN" > ~/.npmrc node scripts/publish.js ================================================ FILE: .github/workflows/test.yml ================================================ name: test on: [push, pull_request] jobs: test: runs-on: ubuntu-latest strategy: matrix: node-version: [14.x] steps: - uses: actions/checkout@v2 - name: Use Node.js ${{ matrix.node-version }} uses: actions/setup-node@v1 with: node-version: ${{ matrix.node-version }} # https://github.com/actions/setup-node/issues/213#issuecomment-833724757 - name: Install npm v7 run: npm i -g npm@7 --registry=https://registry.npmjs.org - name: Install dependencies run: npm ci - name: Build run: npm run build - name: Test run: npm run test & npm run size ================================================ FILE: .gitignore ================================================ /build/ /fixtures/*/history.js node_modules/ ================================================ FILE: .prettierignore ================================================ package.json package-lock.json ================================================ FILE: .prettierrc ================================================ {} ================================================ FILE: CONTRIBUTING.md ================================================ All development happens [on GitHub](https://github.com/remix-run/history). When [creating a pull request](https://help.github.com/articles/creating-a-pull-request/), please make sure that all of the following apply: - If you're adding a new feature or "fixing" a bug, please go into detail about your use case and why you think you need that feature or that bug fixed. This library has lots and lots of dependents, and we can't afford to make changes lightly without understanding why. - The tests pass. The test suite will automatically run when you create the PR. All you need to do is wait a few minutes to see the result in the PR. - Each commit in your PR should describe a significant piece of work. Work that was done in one commit and then undone later should be squashed into a single commit. If your PR fails to meet these guidelines, it may be closed without much of an explanation besides a link to this document. Thank you for your contribution! ================================================ FILE: LICENSE ================================================ MIT License Copyright (c) React Training 2016-2020 Copyright (c) Remix Software 2020-2021 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ # history · [![npm package][npm-badge]][npm] [npm-badge]: https://img.shields.io/npm/v/history.svg?style=flat-square [npm]: https://www.npmjs.org/package/history The history library lets you easily manage session history anywhere JavaScript runs. A `history` object abstracts away the differences in various environments and provides a minimal API that lets you manage the history stack, navigate, and persist state between sessions. ## Documentation Documentation for version 5 can be found in the [docs](docs) directory. This is the current stable release. Version 5 is used in React Router version 6. Documentation for version 4 can be found [on the v4 branch](https://github.com/remix-run/history/tree/v4/docs). Version 4 is used in React Router versions 4 and 5. ## Changes To see the changes that were made in a given release, please lookup the tag on [the releases page](https://github.com/remix-run/history/releases). For changes released in version 4.6.3 and earlier, please see [the `CHANGES.md` file](https://github.com/remix-run/history/blob/845d690c5576c7f55ecbe14babe0092e8e5bc2bb/CHANGES.md). ## Development Development of the current stable release, version 5, happens on [the `main` branch](https://github.com/remix-run/history/tree/main). Please keep in mind that this branch may include some work that has not yet been published as part of an official release. However, since `main` is always stable, you should feel free to build your own working release straight from `main` at any time. If you're interested in helping out, please read [our contributing guidelines](CONTRIBUTING.md). ## About `history` is developed and maintained by [Remix](https://remix.run). If you're interested in learning more about what React can do for your company, please [get in touch](mailto:hello@remix.run)! ## Thanks A big thank-you to [BrowserStack](https://www.browserstack.com/) for providing the infrastructure that allows us to run our build in real browsers. Also, thanks to [Dan Shaw](https://www.npmjs.com/~dshaw) for letting us use the `history` npm package name. Thanks, Dan! ================================================ FILE: docs/README.md ================================================ Welcome to the history docs! The history library lets you easily manage session history anywhere JavaScript runs. A `history` object abstracts away the differences in various environments and provides a minimal API that lets you manage the history stack, navigate, and persist state between sessions. The library is very small, so there are really just a few files here for you to browse. If this is your first time here, we'd recommend you start with the [Getting Started](getting-started.md) guide. You may also be interested in reading one of the following guides: - [Installation](installation.md) - [Navigation](navigation.md) - [Blocking Transitions](blocking-transitions.md) An [API Reference](api-reference.md) is also available. ================================================ FILE: docs/api-reference.md ================================================ # history API Reference This is the API reference for [the history JavaScript library](https://github.com/remix-run/history). The history library provides an API for tracking application history using [location](#location) objects that contain URLs and state. This reference includes type signatures and return values for the interfaces in the library. Please read the [getting started guide](getting-started.md) if you're looking for explanations about how to use the library to accomplish a specific task. ## Overview ### Environments The history library includes support for three different "environments", or modes of operation. - [Browser history](#createbrowserhistory) is used in web apps - [Hash history](#createhashhistory) is used in web apps where you don't want to/can't send the URL to the server for some reason - [Memory history](#creatememoryhistory) - is used in native apps and testing Just pick the right mode for your target environment and you're good to go. ### Listening To read the current location and action, use [`history.location`](#history.location) and [`history.action`](#history.action). Both of these properties are mutable and automatically update as the location changes. To be notified when the location changes, setup a listener using [`history.listen`](#history.listen). ### Navigation To change the current location, you'll want to use one of the following: - [`history.push`](#history.push) - Pushes a new location onto the history stack - [`history.replace`](#history.replace) - Replaces the current location with another - [`history.go`](#history.go) - Changes the current index in the history stack by a given delta - [`history.back`](#history.back) - Navigates one entry back in the history stack - [`history.forward`](#history.forward) - Navigates one entry forward in the history stack ### Confirming Navigation To prevent the location from changing, use [`history.block`](#history.block). This API allows you to prevent the location from changing so you can prompt the user before retrying the transition. ### Creating `href` values If you're building a link, you'll want to use [`history.createHref`](#history.createhref) to get a URL you can use as the value of ``. --- ## Reference The [source code](https://github.com/remix-run/history/tree/main/packages/history) for the history library is written in TypeScript, but it is compiled to JavaScript before publishing. Some of the function signatures in this reference include their TypeScript type annotations, but you can always refer to the original source as well. ### Action An `Action` represents a type of change that occurred in the history stack. `Action` is an `enum` with three members: - `Action.Pop` - A change to an arbitrary index in the stack, such as a back or forward navigation. This does not describe the direction of the navigation, only that the index changed. This is the default action for newly created history objects. - `Action.Push` - Indicates a new entry being added to the history stack, such as when a link is clicked and a new page loads. When this happens, all subsequent entries in the stack are lost. - `Action.Replace` - Indicates the entry at the current index in the history stack being replaced by a new one. See [the Getting Started guide](getting-started.md) for more information. ### `History` A `History` object represents the shared interface for `BrowserHistory`, `HashHistory`, and `MemoryHistory`.
Type declaration ```ts interface History { readonly action: Action; readonly location: Location; createHref(to: To): string; push(to: To, state?: any): void; replace(to: To, state?: any): void; go(delta: number): void; back(): void; forward(): void; listen(listener: Listener): () => void; block(blocker: Blocker): () => void; } ```
### `createBrowserHistory`
Type declaration ```tsx function createBrowserHistory(options?: { window?: Window }): BrowserHistory; interface BrowserHistory extends History {} ```
A browser history object keeps track of the browsing history of an application using the browser's built-in history stack. It is designed to run in modern web browsers that support the HTML5 history interface including `pushState`, `replaceState`, and the `popstate` event. `createBrowserHistory` returns a `BrowserHistory` instance. `window` defaults to [the `defaultView` of the current `document`](https://developer.mozilla.org/en-US/docs/Web/API/Document/defaultView). ```ts import { createBrowserHistory } from "history"; let history = createBrowserHistory(); ``` See [the Getting Started guide](getting-started.md) for more information. ### `createPath` and `parsePath`
Type declaration ```ts function createPath(partialPath: Partial): string; function parsePath(path: string): Partial; interface Path { pathname: string; search: string; hash: string; } ```
The `createPath` and `parsePath` functions are useful for creating and parsing URL paths. ```ts createPath({ pathname: "/login", search: "?next=home" }); // "/login?next=home" parsePath("/login?next=home"); // { pathname: '/login', search: '?next=home' } ``` ### `createHashHistory`
Type declaration ```ts createHashHistory({ window?: Window }): HashHistory; interface HashHistory extends History {} ```
A hash history object keeps track of the browsing history of an application using the browser's built-in history stack. It is designed to be run in modern web browsers that support the HTML5 history interface including `pushState`, `replaceState`, and the `popstate` event. `createHashHistory` returns a `HashHistory` instance. `window` defaults to [the `defaultView` of the current `document`](https://developer.mozilla.org/en-US/docs/Web/API/Document/defaultView). The main difference between this and [browser history](#createbrowserhistory) is that a hash history stores the current location in the [`hash` portion of the URL](https://developer.mozilla.org/en-US/docs/Web/API/Location/hash#:~:text=The%20hash%20property%20of%20the,an%20empty%20string%2C%20%22%22%20.), which means that it is not ever sent to the server. This can be useful if you are hosting your site on a domain where you do not have full control over the server routes, or e.g. in an Electron app where you don't want to configure the "server" to serve the same page at different URLs. ```ts import { createHashHistory } from "history"; let history = createHashHistory(); ``` See [the Getting Started guide](getting-started.md) for more information. ### `createMemoryHistory`
Type declaration ```ts function createMemoryHistory({ initialEntries?: InitialEntry[], initialIndex?: number }): MemoryHistory; type InitialEntry = string | Partial; interface MemoryHistory extends History { readonly index: number; } ```
A memory history object keeps track of the browsing history of an application using an internal array. This makes it ideal in situations where you need complete control over the history stack, like React Native and tests. `createMemoryHistory` returns a `MemoryHistory` instance. You can provide initial entries to this history instance through the `initialEntries` property, which defaults to `['/']` (a single location at the root `/` URL). The `initialIndex` defaults to the index of the last item in `initialEntries`. ```ts import { createMemoryHistory } from "history"; let history = createMemoryHistory(); // Or, to pre-seed the history instance with some URLs: let history = createMemoryHistory({ initialEntries: ["/home", "/profile", "/about"], }); ``` See [the Getting Started guide](getting-started.md) for more information. ### `history.action` The current (most recent) [`Action`](#action) that modified the history stack. This property is mutable and automatically updates as the current location changes. See also [`history.listen`](#history.listen). ### `history.back()` Goes back one entry in the history stack. Alias for `history.go(-1)`. See [the Navigation guide](navigation.md) for more information. ### `history.block(blocker: Blocker)`
Type declaration ```ts interface Blocker { (tx: Transition): void; } interface Transition { action: Action; location: Location; retry(): void; } ```
Prevents changes to the history stack from happening. This is useful when you want to prevent the user navigating away from the current page, for example when they have some unsaved data on the current page. ```ts // To start blocking location changes... let unblock = history.block(({ action, location, retry }) => { // A transition was blocked! }); // Later, when you want to start allowing transitions again... unblock(); ``` See [the guide on Blocking Transitions](blocking-transitions.md) for more information. ### `history.createHref(to: To)` Returns a string suitable for use as an `` value that will navigate to the given destination. ### `history.forward()` Goes forward one entry in the history stack. Alias for `history.go(1)`. See [the Navigation guide](navigation.md) for more information. ### `history.go(delta: number)` Navigates back/forward by `delta` entries in the stack. See [the Navigation guide](navigation.md) for more information. ### `history.index` The current index in the history stack. > [!Note:] > > This property is available only on [memory history](#memoryhistory) instances. ### `history.listen(listener: Listener)`
Type declaration ```ts interface Listener { (update: Update): void; } interface Update { action: Action; location: Location; } ```
Starts listening for location changes and calls the given callback with an `Update` when it does. ```ts // To start listening for location changes... let unlisten = history.listen(({ action, location }) => { // The current location changed. }); // Later, when you are done listening for changes... unlisten(); ``` See [the Getting Started guide](getting-started.md#listening) for more information. ### `history.location` The current [`Location`](#location). This property is mutable and automatically updates as the current location changes. Also see [`history.listen`](#history.listen). ### `history.push(to: To, state?: any)` Pushes a new entry onto the stack. See [the Navigation guide](navigation.md) for more information. ### `history.replace(to: To, state?: any)` Replaces the current entry in the stack with a new one. See [the Navigation guide](navigation.md) for more information. ### Location
Type declaration ```ts interface Location { pathname: string; search: string; hash: string; state: unknown; key: string; } ```
A `location` is a particular entry in the history stack, usually analogous to a "page" or "screen" in your app. As the user clicks on links and moves around the app, the current location changes. ### `location.pathname` The `location.pathname` property is a string that contains an initial `/` followed by the remainder of the URL up to the `?`. See also [`URL.pathname`](https://developer.mozilla.org/en-US/docs/Web/API/URL/pathname). ### `location.search` The `location.search` property is a string that contains an initial `?` followed by the `key=value` pairs in the query string. If there are no parameters, this value may be the empty string (i.e. `''`). See also [`URL.search`](https://developer.mozilla.org/en-US/docs/Web/API/URL/search). ### `location.hash` The `location.hash` property is a string that contains an initial `#` followed by fragment identifier of the URL. If there is no fragment identifier, this value may be the empty string (i.e. `''`). See also [`URL.hash`](https://developer.mozilla.org/en-US/docs/Web/API/URL/hash). ### `location.state` The `location.state` property is a user-supplied [`State`](#state) object that is associated with this location. This can be a useful place to store any information you do not want to put in the URL, e.g. session-specific data. > [!Note:] > > In web browsers, this state is managed using the browser's built-in > `pushState`, `replaceState`, and `popstate` APIs. See also > [`History.state`](https://developer.mozilla.org/en-US/docs/Web/API/History/state). ### `location.key` The `location.key` property is a unique string associated with this location. On the initial location, this will be the string `default`. On all subsequent locations, this string will be a unique identifier. This can be useful in situations where you need to keep track of 2 different states for the same URL. For example, you could use this as the key to some network or device storage API. ### State A `State` value is an arbitrary value that holds extra information associated with a [`Location`](#location) but does not appear in the URL. This value is always associated with that location. See [the Navigation guide](navigation.md) for more information. ### To
Type declaration ```ts type To = string | Partial; interface Path { pathname: string; search: string; hash: string; } ```
A [`To`](https://github.com/remix-run/history/blob/main/packages/history/index.ts#L178) value represents a destination location, but doesn't contain all the information that a normal [`location`](#location) object does. It is primarily used as the first argument to [`history.push`](#history.push) and [`history.replace`](#history.replace). See [the Navigation guide](navigation.md) for more information. ================================================ FILE: docs/blocking-transitions.md ================================================ # Blocking Transitions `history` lets you block navigation away from the current page using the [`history.block(blocker: Blocker)`](api-reference.md#history.block) API. For example, you can make sure the user knows that if they leave the current page they will lose some unsaved changes they've made. ```js // Block navigation and register a callback that // fires when a navigation attempt is blocked. let unblock = history.block((tx) => { // Navigation was blocked! Let's show a confirmation dialog // so the user can decide if they actually want to navigate // away and discard changes they've made in the current page. let url = tx.location.pathname; if (window.confirm(`Are you sure you want to go to ${url}?`)) { // Unblock the navigation. unblock(); // Retry the transition. tx.retry(); } }); ``` This example uses [`window.confirm`](https://developer.mozilla.org/en-US/docs/Web/API/Window/confirm), but you could also use your own custom confirm dialog if you'd prefer. ## Caveats `history.block` will call your callback for all in-page navigation attempts, but for navigation that reloads the page (e.g. the refresh button or a link that doesn't use `history.push`) it registers [a `beforeunload` handler](https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event) to prevent the navigation. In modern browsers you are not able to customize this dialog. Instead, you'll see something like this (Chrome): ![Chrome navigation confirm dialog](images/block.png) One subtle side effect of registering a `beforeunload` handler is that the page will not be [salvageable](https://html.spec.whatwg.org/#unloading-documents) in [the `pagehide` event](https://developer.mozilla.org/en-US/docs/Web/API/Window/pagehide_event). This means the page may not be reused by the browser, so things like timers, scroll position, and event sources will not be reused when the user navigates back to that page. ================================================ FILE: docs/getting-started.md ================================================ # Intro The history library provides history tracking and navigation primitives for JavaScript applications that run in browsers and other stateful environments. If you haven't yet, please take a second to read through [the Installation guide](installation.md) to get the library installed and running on your system. We provide 3 different methods for working with history, depending on your environment: - A "browser history" is for use in modern web browsers that support the [HTML5 history API](http://diveintohtml5.info/history.html) (see [cross-browser compatibility](http://caniuse.com/#feat=history)) - A "hash history" is for use in web browsers where you want to store the location in the [hash](https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/hash) portion of the current URL to avoid sending it to the server when the page reloads - A "memory history" is used as a reference implementation that may be used in non-browser environments, like [React Native](https://facebook.github.io/react-native/) or tests The main bundle exports one method for each environment: [`createBrowserHistory`](api-reference.md#createbrowserhistory) for browsers, [`createHashHistory`](api-reference.md#createhashhistory) for using hash history in browsers, and [`createMemoryHistory`](api-reference.md#creatememoryhistory) for creating an in-memory history. In addition to the main bundle, the library also includes `history/browser` and `history/hash` bundles that export singletons you can use to quickly get a history instance for [the current `document`](https://developer.mozilla.org/en-US/docs/Web/API/Window/document) (web page). ## Basic Usage Basic usage looks like this: ```js // Create your own history instance. import { createBrowserHistory } from "history"; let history = createBrowserHistory(); // ... or just import the browser history singleton instance. import history from "history/browser"; // Alternatively, if you're using hash history import // the hash history singleton instance. // import history from 'history/hash'; // Get the current location. let location = history.location; // Listen for changes to the current location. let unlisten = history.listen(({ location, action }) => { console.log(action, location.pathname, location.state); }); // Use push to push a new entry onto the history stack. history.push("/home", { some: "state" }); // Use replace to replace the current entry in the stack. history.replace("/logged-in"); // Use back/forward to navigate one entry back or forward. history.back(); // To stop listening, call the function returned from listen(). unlisten(); ``` If you're using memory history you'll need to create your own `history` object before you can use it. ```js import { createMemoryHistory } from "history"; let history = createMemoryHistory(); ``` If you're using browser or hash history with a `window` other than that of the current `document` (like an iframe), you'll need to create your own browser/hash history: ```js import { createBrowserHistory } from "history"; let history = createBrowserHistory({ window: iframe.contentWindow, }); ``` ## Properties Each `history` object has the following properties: - [`history.location`](api-reference.md#history.location) - The current location (see below) - [`history.action`](api-reference.md#history.action) - The current navigation action (see below) Additionally, memory history provides `history.index` that tells you the current index in the history stack. ## Listening You can listen for changes to the current location using `history.listen`: ```js history.listen(({ action, location }) => { console.log( `The current URL is ${location.pathname}${location.search}${location.hash}` ); console.log(`The last navigation action was ${action}`); }); ``` The [`location`](api-reference.md#location) object implements a subset of [the `window.location` interface](https://developer.mozilla.org/en-US/docs/Web/API/Location), including: - [`location.pathname`](api-reference.md#location.pathname) - The path of the URL - [`location.search`](api-reference.md#location.search) - The URL query string - [`location.hash`](api-reference.md#location.hash) - The URL hash fragment - [`location.state`](api-reference.md#location.state) - Some extra state for this location that does not reside in the URL (may be `null`) - [`location.key`](api-reference.md#location.key) - A unique string representing this location The [`action`](api-reference.md#action) is one of `Action.Push`, `Action.Replace`, or `Action.Pop` depending on how the user got to the current location. - `Action.Push` means one more entry was added to the history stack - `Action.Replace` means the current entry in the stack was replaced - `Action.Pop` means we went to some other location already in the stack ## Cleaning up When you attach a listener using `history.listen`, it returns a function that can be used to remove the listener, which can then be invoked in cleanup logic: ```js let unlisten = history.listen(myListener); // Later, when you're done... unlisten(); ``` ## Utilities The main history bundle also contains both `createPath` and `parsePath` methods that may be useful when working with URL paths. ```js let pathPieces = parsePath("/the/path?the=query#the-hash"); // pathPieces = { // pathname: '/the/path', // search: '?the=query', // hash: '#the-hash' // } let path = createPath(pathPieces); // path = '/the/path?the=query#the-hash' ``` ================================================ FILE: docs/installation.md ================================================ # Installation The history library is published to the public [npm](https://www.npmjs.com/) registry. You can install it using: $ npm install --save history ## Using a Bundler The best way to use the `history` library is with a bundler that supports JavaScript modules (we recommend [Rollup](https://rollupjs.org)). Recent versions of Webpack and Parcel are also good choices. Then you can write your code using JavaScript `import` statements, like this: ```js import { createBrowserHistory } from "history"; // ... ``` If you're using a bundler that doesn't understand JavaScript modules and only understands CommonJS, you can use `require` as you would with anything else: ```js var createBrowserHistory = require("history").createBrowserHistory; ``` ## Using ` ``` The `history.development.js` build is also available for non-production apps. In legacy browsers that do not yet support JavaScript modules, you can use one of our UMD (global) builds: ```html ``` You can find the library on `window.HistoryLibrary`. ================================================ FILE: docs/navigation.md ================================================ # Navigation `history` objects may be used to programmatically change the current location using the following methods: - [`history.push(to: To, state?: State)`](api-reference.md#history.push) - [`history.replace(to: To, state?: State)`](api-reference.md#history.replace) - [`history.go(delta: number)`](api-reference.md#history.go) - [`history.back()`](api-reference.md#history.back) - [`history.forward()`](api-reference.md#history.forward) An example: ```js // Push a new entry onto the history stack. history.push("/home"); // Push a new entry onto the history stack with a query string // and some state. Location state does not appear in the URL. history.push("/home?the=query", { some: "state" }); // If you prefer, use a location-like object to specify the URL. // This is equivalent to the example above. history.push( { pathname: "/home", search: "?the=query", }, { some: state, } ); // Go back to the previous history entry. The following // two lines are synonymous. history.go(-1); history.back(); ``` ================================================ FILE: fixtures/block-library/index.html ================================================

Navigation Blocking (library version)

back & forward:

pushState & replaceState:
push / push /one push /two replace /three

regular links:
/ /one

================================================ FILE: fixtures/block-library/index.js ================================================ /* eslint-disable no-console */ const express = require('express'); let port = process.env.PORT || 5000; let app = express(); app.use(express.static(__dirname)); app.get('*', (req, res) => { res.sendFile(__dirname + '/index.html'); }); app.listen(port, () => { console.log(`Server listening on http://localhost:${port}`); }); ================================================ FILE: fixtures/block-vanilla/index.html ================================================

Navigation Blocking (vanilla JS version)

back & forward:

pushState & replaceState:
push / push /one push /two replace /three

regular links:
/ /one

================================================ FILE: fixtures/block-vanilla/index.js ================================================ /* eslint-disable no-console */ const express = require('express'); let port = process.env.PORT || 5000; let app = express(); app.use(express.static(__dirname)); app.get('*', (req, res) => { res.sendFile(__dirname + '/index.html'); }); app.listen(port, () => { console.log(`Server listening on http://localhost:${port}`); }); ================================================ FILE: fixtures/hash-click.html ================================================ home #one #one w pushState #two #two w pushState ================================================ FILE: fixtures/hash-history-length.html ================================================ home #one #two ================================================ FILE: fixtures/unpkg-test.html ================================================ ================================================ FILE: package.json ================================================ { "private": true, "scripts": { "build": "node ./scripts/build.js", "clean": "git clean -fdX .", "lint": "eslint .", "format": "prettier --ignore-path .eslintignore --write .", "publish": "node ./scripts/publish.js", "size": "filesize", "test": "node ./scripts/test.js", "version": "node ./scripts/version.js", "watch": "node ./scripts/watch.js" }, "dependencies": { "@ampproject/filesize": "^4.3.0", "@ampproject/rollup-plugin-closure-compiler": "0.27.0", "@babel/core": "^7.15.0", "@babel/plugin-transform-runtime": "^7.15.0", "@babel/preset-env": "^7.15.0", "@babel/preset-modules": "0.1.4", "@babel/runtime": "^7.15.3", "@rollup/plugin-babel": "^5.3.0", "@rollup/plugin-replace": "^3.0.0", "@typescript-eslint/eslint-plugin": "^4.29.1", "@typescript-eslint/parser": "^4.29.1", "babel-core": "^7.0.0-bridge.0", "babel-eslint": "^10.1.0", "babel-loader": "^8.2.2", "babel-plugin-dev-expression": "0.2.2", "chalk": "^4.1.2", "eslint": "^7.32.0", "eslint-config-react-app": "^6.0.0", "eslint-plugin-flowtype": "^5.9.0", "eslint-plugin-import": "^2.24.0", "eslint-plugin-jsx-a11y": "^6.4.1", "eslint-plugin-react": "^7.24.0", "eslint-plugin-react-hooks": "^4.2.0", "expect": "^21.0.0", "express": "^4.17.1", "jest-mock": "^21.0.6", "jsonfile": "^6.1.0", "karma": "^6.3.4", "karma-browserstack-launcher": "^1.6.0", "karma-chrome-launcher": "^3.1.0", "karma-firefox-launcher": "^2.1.1", "karma-mocha": "^2.0.1", "karma-mocha-reporter": "^2.2.5", "karma-sourcemap-loader": "0.3.8", "karma-webpack": "^3.0.5", "mocha": "^5.2.0", "prettier": "^2.5.1", "prompt-confirm": "^2.0.4", "rollup": "^2.56.2", "rollup-plugin-copy": "^3.4.0", "rollup-plugin-prettier": "^2.1.0", "rollup-plugin-terser": "^7.0.2", "rollup-plugin-typescript2": "0.30.0", "semver": "^7.3.5", "typescript": "^4.3.5", "webpack": "^3.12.0" }, "workspaces": { "packages": [ "packages/history" ] }, "filesize": { "build/history/history.production.min.js": { "none": "5.06 kB" }, "build/history/umd/history.production.min.js": { "none": "6.03 kB" } } } ================================================ FILE: packages/history/.eslintrc ================================================ { "env": { "browser": true, "es6": true, "node": false }, "globals": { "__DEV__": true } } ================================================ FILE: packages/history/__tests__/.eslintrc ================================================ { "env": { "mocha": true }, "rules": { "import/no-unresolved": [2, { "ignore": ["history"] }] } } ================================================ FILE: packages/history/__tests__/TestSequences/BackButtonTransitionHook.js ================================================ import expect from "expect"; import { execSteps } from "./utils.js"; export default (history, done) => { let hookWasCalled = false; let unblock; let steps = [ ({ location }) => { expect(location).toMatchObject({ pathname: "/", }); history.push("/home"); }, ({ action, location }) => { expect(action).toBe("PUSH"); expect(location).toMatchObject({ pathname: "/home", }); unblock = history.block(() => { hookWasCalled = true; }); window.history.go(-1); }, ({ action, location }) => { expect(action).toBe("POP"); expect(location).toMatchObject({ pathname: "/", }); expect(hookWasCalled).toBe(true); unblock(); }, ]; execSteps(steps, history, done); }; ================================================ FILE: packages/history/__tests__/TestSequences/BlockEverything.js ================================================ import expect from "expect"; import { execSteps } from "./utils.js"; export default (history, done) => { let steps = [ ({ location }) => { expect(location).toMatchObject({ pathname: "/", }); let unblock = history.block(); history.push("/home"); expect(history.location).toMatchObject({ pathname: "/", }); unblock(); }, ]; execSteps(steps, history, done); }; ================================================ FILE: packages/history/__tests__/TestSequences/BlockPopWithoutListening.js ================================================ import expect from "expect"; export default (history, done) => { expect(history.location).toMatchObject({ pathname: "/", }); history.push("/home"); let transitionHookWasCalled = false; let unblock = history.block(() => { transitionHookWasCalled = true; }); // These timeouts are a hack to allow for the time it takes // for histories to reflect the change in the URL. Normally // we could just listen and avoid the waiting time. But this // test is designed to test what happens when we don't listen(), // so that's not an option here. // Allow some time for history to detect the PUSH. setTimeout(() => { history.back(); // Allow some time for history to detect the POP. setTimeout(() => { expect(transitionHookWasCalled).toBe(true); unblock(); done(); }, 100); }, 10); }; ================================================ FILE: packages/history/__tests__/TestSequences/EncodedReservedCharacters.js ================================================ import expect from "expect"; import { execSteps } from "./utils.js"; export default (history, done) => { let steps = [ () => { // encoded string let pathname = "/view/%23abc"; history.replace(pathname); }, ({ location }) => { expect(location).toMatchObject({ pathname: "/view/%23abc", }); // encoded object let pathname = "/view/%23abc"; history.replace({ pathname }); }, ({ location }) => { expect(location).toMatchObject({ pathname: "/view/%23abc", }); // unencoded string let pathname = "/view/#abc"; history.replace(pathname); }, ({ location }) => { expect(location).toMatchObject({ pathname: "/view/", hash: "#abc", }); }, ]; execSteps(steps, history, done); }; ================================================ FILE: packages/history/__tests__/TestSequences/GoBack.js ================================================ import expect from "expect"; import { execSteps } from "./utils.js"; export default (history, done) => { let steps = [ ({ location }) => { expect(location).toMatchObject({ pathname: "/", }); history.push("/home"); }, ({ action, location }) => { expect(action).toEqual("PUSH"); expect(location).toMatchObject({ pathname: "/home", }); history.back(); }, ({ action, location }) => { expect(action).toEqual("POP"); expect(location).toMatchObject({ pathname: "/", }); }, ]; execSteps(steps, history, done); }; ================================================ FILE: packages/history/__tests__/TestSequences/GoForward.js ================================================ import expect from "expect"; import { execSteps } from "./utils.js"; export default (history, done) => { let steps = [ ({ location }) => { expect(location).toMatchObject({ pathname: "/", }); history.push("/home"); }, ({ action, location }) => { expect(action).toEqual("PUSH"); expect(location).toMatchObject({ pathname: "/home", }); history.back(); }, ({ action, location }) => { expect(action).toEqual("POP"); expect(location).toMatchObject({ pathname: "/", }); history.forward(); }, ({ action, location }) => { expect(action).toEqual("POP"); expect(location).toMatchObject({ pathname: "/home", }); }, ]; execSteps(steps, history, done); }; ================================================ FILE: packages/history/__tests__/TestSequences/InitialLocationDefaultKey.js ================================================ import expect from "expect"; import { execSteps } from "./utils.js"; export default (history, done) => { let steps = [ ({ location }) => { expect(location.key).toBe("default"); }, ]; execSteps(steps, history, done); }; ================================================ FILE: packages/history/__tests__/TestSequences/InitialLocationHasKey.js ================================================ import expect from "expect"; import { execSteps } from "./utils.js"; export default (history, done) => { let steps = [ ({ location }) => { expect(location.key).toBeTruthy(); }, ]; execSteps(steps, history, done); }; ================================================ FILE: packages/history/__tests__/TestSequences/Listen.js ================================================ import expect from "expect"; import mock from "jest-mock"; export default (history, done) => { let spy = mock.fn(); let unlisten = history.listen(spy); expect(spy).not.toHaveBeenCalled(); unlisten(); done(); }; ================================================ FILE: packages/history/__tests__/TestSequences/PushMissingPathname.js ================================================ import expect from "expect"; import { execSteps } from "./utils.js"; export default (history, done) => { let steps = [ ({ location }) => { expect(location).toMatchObject({ pathname: "/", }); history.push("/home?the=query#the-hash"); }, ({ action, location }) => { expect(action).toBe("PUSH"); expect(location).toMatchObject({ pathname: "/home", search: "?the=query", hash: "#the-hash", }); history.push("?another=query#another-hash"); }, ({ action, location }) => { expect(action).toBe("PUSH"); expect(location).toMatchObject({ pathname: "/home", search: "?another=query", hash: "#another-hash", }); }, ]; execSteps(steps, history, done); }; ================================================ FILE: packages/history/__tests__/TestSequences/PushNewLocation.js ================================================ import expect from "expect"; import { execSteps } from "./utils.js"; export default (history, done) => { let steps = [ ({ location }) => { expect(location).toMatchObject({ pathname: "/", }); history.push("/home?the=query#the-hash"); }, ({ action, location }) => { expect(action).toBe("PUSH"); expect(location).toMatchObject({ pathname: "/home", search: "?the=query", hash: "#the-hash", state: null, key: expect.any(String), }); }, ]; execSteps(steps, history, done); }; ================================================ FILE: packages/history/__tests__/TestSequences/PushRelativePathname.js ================================================ import expect from "expect"; import { execSteps } from "./utils.js"; export default (history, done) => { let steps = [ ({ location }) => { expect(location).toMatchObject({ pathname: "/", }); history.push("/the/path?the=query#the-hash"); }, ({ action, location }) => { expect(action).toBe("PUSH"); expect(location).toMatchObject({ pathname: "/the/path", search: "?the=query", hash: "#the-hash", }); history.push("../other/path?another=query#another-hash"); }, ({ action, location }) => { expect(action).toBe("PUSH"); expect(location).toMatchObject({ pathname: "/other/path", search: "?another=query", hash: "#another-hash", }); }, ]; execSteps(steps, history, done); }; ================================================ FILE: packages/history/__tests__/TestSequences/PushRelativePathnameWarning.js ================================================ import expect from "expect"; import { execSteps, spyOn } from "./utils.js"; export default (history, done) => { let steps = [ ({ location }) => { expect(location).toMatchObject({ pathname: "/", }); history.push("/the/path?the=query#the-hash"); }, ({ action, location }) => { expect(action).toBe("PUSH"); expect(location).toMatchObject({ pathname: "/the/path", search: "?the=query", hash: "#the-hash", }); let { spy, destroy } = spyOn(console, "warn"); history.push("../other/path?another=query#another-hash"); expect(spy).toHaveBeenCalledWith( expect.stringContaining("relative pathnames are not supported") ); destroy(); }, ({ location }) => { expect(location).toMatchObject({ pathname: "../other/path", search: "?another=query", hash: "#another-hash", }); }, ]; execSteps(steps, history, done); }; ================================================ FILE: packages/history/__tests__/TestSequences/PushSamePath.js ================================================ import expect from "expect"; import { execSteps } from "./utils.js"; export default (history, done) => { let steps = [ ({ location }) => { expect(location).toMatchObject({ pathname: "/", }); history.push("/home"); }, ({ action, location }) => { expect(action).toBe("PUSH"); expect(location).toMatchObject({ pathname: "/home", }); history.push("/home"); }, ({ action, location }) => { expect(action).toBe("PUSH"); expect(location).toMatchObject({ pathname: "/home", }); history.back(); }, ({ action, location }) => { expect(action).toBe("POP"); expect(location).toMatchObject({ pathname: "/home", }); }, ]; execSteps(steps, history, done); }; ================================================ FILE: packages/history/__tests__/TestSequences/PushState.js ================================================ import expect from "expect"; import { execSteps } from "./utils.js"; export default (history, done) => { let steps = [ ({ location }) => { expect(location).toMatchObject({ pathname: "/", }); history.push("/home?the=query#the-hash", { the: "state" }); }, ({ action, location }) => { expect(action).toBe("PUSH"); expect(location).toMatchObject({ pathname: "/home", search: "?the=query", hash: "#the-hash", state: { the: "state" }, }); }, ]; execSteps(steps, history, done); }; ================================================ FILE: packages/history/__tests__/TestSequences/ReplaceNewLocation.js ================================================ import expect from "expect"; import { execSteps } from "./utils.js"; export default (history, done) => { let steps = [ ({ location }) => { expect(location).toMatchObject({ pathname: "/", }); history.replace("/home?the=query#the-hash"); }, ({ action, location }) => { expect(action).toBe("REPLACE"); expect(location).toMatchObject({ pathname: "/home", search: "?the=query", hash: "#the-hash", state: null, key: expect.any(String), }); history.replace("/"); }, ({ action, location }) => { expect(action).toBe("REPLACE"); expect(location).toMatchObject({ pathname: "/", search: "", state: null, key: expect.any(String), }); }, ]; execSteps(steps, history, done); }; ================================================ FILE: packages/history/__tests__/TestSequences/ReplaceSamePath.js ================================================ import expect from "expect"; import { execSteps } from "./utils.js"; export default (history, done) => { let prevLocation; let steps = [ ({ location }) => { expect(location).toMatchObject({ pathname: "/", }); history.replace("/home"); }, ({ action, location }) => { expect(action).toBe("REPLACE"); expect(location).toMatchObject({ pathname: "/home", }); prevLocation = location; history.replace("/home"); }, ({ action, location }) => { expect(action).toBe("REPLACE"); expect(location).toMatchObject({ pathname: "/home", }); expect(location).not.toBe(prevLocation); }, ]; execSteps(steps, history, done); }; ================================================ FILE: packages/history/__tests__/TestSequences/ReplaceState.js ================================================ import expect from "expect"; import { execSteps } from "./utils.js"; export default (history, done) => { let steps = [ ({ location }) => { expect(location).toMatchObject({ pathname: "/", }); history.replace("/home?the=query#the-hash", { the: "state" }); }, ({ action, location }) => { expect(action).toBe("REPLACE"); expect(location).toMatchObject({ pathname: "/home", search: "?the=query", hash: "#the-hash", state: { the: "state" }, }); }, ]; execSteps(steps, history, done); }; ================================================ FILE: packages/history/__tests__/TestSequences/utils.js ================================================ import mock from "jest-mock"; export function spyOn(object, method) { let original = object[method]; let spy = mock.fn(); object[method] = spy; return { spy, destroy() { object[method] = original; }, }; } export function execSteps(steps, history, done) { let index = 0, unlisten, cleanedUp = false; function cleanup(...args) { if (!cleanedUp) { cleanedUp = true; unlisten(); done(...args); } } function execNextStep(...args) { try { let nextStep = steps[index++]; if (!nextStep) throw new Error("Test is missing step " + index); nextStep(...args); if (index === steps.length) cleanup(); } catch (error) { cleanup(error); } } if (steps.length) { unlisten = history.listen(execNextStep); execNextStep({ action: history.action, location: history.location, }); } else { done(); } } ================================================ FILE: packages/history/__tests__/browser-test.js ================================================ import expect from "expect"; import { createBrowserHistory } from "history"; import InitialLocationDefaultKey from "./TestSequences/InitialLocationDefaultKey.js"; import Listen from "./TestSequences/Listen.js"; import PushNewLocation from "./TestSequences/PushNewLocation.js"; import PushSamePath from "./TestSequences/PushSamePath.js"; import PushState from "./TestSequences/PushState.js"; import PushMissingPathname from "./TestSequences/PushMissingPathname.js"; import PushRelativePathname from "./TestSequences/PushRelativePathname.js"; import ReplaceNewLocation from "./TestSequences/ReplaceNewLocation.js"; import ReplaceSamePath from "./TestSequences/ReplaceSamePath.js"; import ReplaceState from "./TestSequences/ReplaceState.js"; import EncodedReservedCharacters from "./TestSequences/EncodedReservedCharacters.js"; import GoBack from "./TestSequences/GoBack.js"; import GoForward from "./TestSequences/GoForward.js"; import BlockEverything from "./TestSequences/BlockEverything.js"; import BlockPopWithoutListening from "./TestSequences/BlockPopWithoutListening.js"; describe("a browser history", () => { let history; beforeEach(() => { window.history.replaceState(null, null, "/"); history = createBrowserHistory(); }); it("knows how to create hrefs from location objects", () => { const href = history.createHref({ pathname: "/the/path", search: "?the=query", hash: "#the-hash", }); expect(href).toEqual("/the/path?the=query#the-hash"); }); it("knows how to create hrefs from strings", () => { const href = history.createHref("/the/path?the=query#the-hash"); expect(href).toEqual("/the/path?the=query#the-hash"); }); it("does not encode the generated path", () => { const encodedHref = history.createHref({ pathname: "/%23abc", }); expect(encodedHref).toEqual("/%23abc"); const unencodedHref = history.createHref({ pathname: "/#abc", }); expect(unencodedHref).toEqual("/#abc"); }); describe("listen", () => { it("does not immediately call listeners", (done) => { Listen(history, done); }); }); describe("the initial location", () => { it('has the "default" key', (done) => { InitialLocationDefaultKey(history, done); }); }); describe("push a new path", () => { it("calls change listeners with the new location", (done) => { PushNewLocation(history, done); }); }); describe("push the same path", () => { it("calls change listeners with the new location", (done) => { PushSamePath(history, done); }); }); describe("push state", () => { it("calls change listeners with the new location", (done) => { PushState(history, done); }); }); describe("push with no pathname", () => { it("reuses the current location pathname", (done) => { PushMissingPathname(history, done); }); }); describe("push with a relative pathname", () => { it("normalizes the pathname relative to the current location", (done) => { PushRelativePathname(history, done); }); }); describe("replace a new path", () => { it("calls change listeners with the new location", (done) => { ReplaceNewLocation(history, done); }); }); describe("replace the same path", () => { it("calls change listeners with the new location", (done) => { ReplaceSamePath(history, done); }); }); describe("replace state", () => { it("calls change listeners with the new location", (done) => { ReplaceState(history, done); }); }); describe("location created with encoded/unencoded reserved characters", () => { it("produces different location objects", (done) => { EncodedReservedCharacters(history, done); }); }); describe("back", () => { it("calls change listeners with the previous location", (done) => { GoBack(history, done); }); }); describe("forward", () => { it("calls change listeners with the next location", (done) => { GoForward(history, done); }); }); describe("block", () => { it("blocks all transitions", (done) => { BlockEverything(history, done); }); }); describe("block a POP without listening", () => { it("receives the next ({ action, location })", (done) => { BlockPopWithoutListening(history, done); }); }); }); ================================================ FILE: packages/history/__tests__/create-path-test.js ================================================ import expect from "expect"; import { createPath } from "history"; describe("createPath", () => { describe("given only a pathname", () => { it("returns the pathname unchanged", () => { let path = createPath({ pathname: "https://google.com" }); expect(path).toBe("https://google.com"); }); }); describe("given a pathname and a search param", () => { it("returns the constructed pathname", () => { let path = createPath({ pathname: "https://google.com", search: "?something=cool", }); expect(path).toBe("https://google.com?something=cool"); }); }); describe("given a pathname and a search param without ?", () => { it("returns the constructed pathname", () => { let path = createPath({ pathname: "https://google.com", search: "something=cool", }); expect(path).toBe("https://google.com?something=cool"); }); }); describe("given a pathname and a hash param", () => { it("returns the constructed pathname", () => { let path = createPath({ pathname: "https://google.com", hash: "#section-1", }); expect(path).toBe("https://google.com#section-1"); }); }); describe("given a pathname and a hash param without #", () => { it("returns the constructed pathname", () => { let path = createPath({ pathname: "https://google.com", hash: "section-1", }); expect(path).toBe("https://google.com#section-1"); }); }); describe("given a full location object", () => { it("returns the constructed pathname", () => { let path = createPath({ pathname: "https://google.com", search: "something=cool", hash: "#section-1", }); expect(path).toBe("https://google.com?something=cool#section-1"); }); }); }); ================================================ FILE: packages/history/__tests__/hash-base-test.js ================================================ import expect from "expect"; import { createHashHistory } from "history"; describe("a hash history on a page with a tag", () => { let history, base; beforeEach(() => { if (window.location.hash !== "#/") { window.location.hash = "/"; } base = document.createElement("base"); base.setAttribute("href", "/prefix"); document.head.appendChild(base); history = createHashHistory(); }); afterEach(() => { document.head.removeChild(base); }); it("knows how to create hrefs", () => { const hashIndex = window.location.href.indexOf("#"); const upToHash = hashIndex === -1 ? window.location.href : window.location.href.slice(0, hashIndex); const href = history.createHref({ pathname: "/the/path", search: "?the=query", hash: "#the-hash", }); expect(href).toEqual(upToHash + "#/the/path?the=query#the-hash"); }); }); ================================================ FILE: packages/history/__tests__/hash-test.js ================================================ import expect from "expect"; import { createHashHistory } from "history"; import Listen from "./TestSequences/Listen.js"; import InitialLocationDefaultKey from "./TestSequences/InitialLocationDefaultKey.js"; import PushNewLocation from "./TestSequences/PushNewLocation.js"; import PushSamePath from "./TestSequences/PushSamePath.js"; import PushState from "./TestSequences/PushState.js"; import PushMissingPathname from "./TestSequences/PushMissingPathname.js"; import PushRelativePathnameWarning from "./TestSequences/PushRelativePathnameWarning.js"; import ReplaceNewLocation from "./TestSequences/ReplaceNewLocation.js"; import ReplaceSamePath from "./TestSequences/ReplaceSamePath.js"; import ReplaceState from "./TestSequences/ReplaceState.js"; import EncodedReservedCharacters from "./TestSequences/EncodedReservedCharacters.js"; import GoBack from "./TestSequences/GoBack.js"; import GoForward from "./TestSequences/GoForward.js"; import BlockEverything from "./TestSequences/BlockEverything.js"; import BlockPopWithoutListening from "./TestSequences/BlockPopWithoutListening.js"; // TODO: Do we still need this? // const canGoWithoutReload = window.navigator.userAgent.indexOf('Firefox') === -1; // const describeGo = canGoWithoutReload ? describe : describe.skip; describe("a hash history", () => { let history; beforeEach(() => { window.history.replaceState(null, null, "#/"); history = createHashHistory(); }); it("knows how to create hrefs from location objects", () => { const href = history.createHref({ pathname: "/the/path", search: "?the=query", hash: "#the-hash", }); expect(href).toEqual("#/the/path?the=query#the-hash"); }); it("knows how to create hrefs from strings", () => { const href = history.createHref("/the/path?the=query#the-hash"); expect(href).toEqual("#/the/path?the=query#the-hash"); }); it("does not encode the generated path", () => { const encodedHref = history.createHref({ pathname: "/%23abc", }); expect(encodedHref).toEqual("#/%23abc"); const unencodedHref = history.createHref({ pathname: "/#abc", }); expect(unencodedHref).toEqual("#/#abc"); }); describe("listen", () => { it("does not immediately call listeners", (done) => { Listen(history, done); }); }); describe("the initial location", () => { it('has the "default" key', (done) => { InitialLocationDefaultKey(history, done); }); }); describe("push a new path", () => { it("calls change listeners with the new location", (done) => { PushNewLocation(history, done); }); }); describe("push the same path", () => { it("calls change listeners with the new location", (done) => { PushSamePath(history, done); }); }); describe("push state", () => { it("calls change listeners with the new location", (done) => { PushState(history, done); }); }); describe("push with no pathname", () => { it("reuses the current location pathname", (done) => { PushMissingPathname(history, done); }); }); describe("push with a relative pathname", () => { it("issues a warning", (done) => { PushRelativePathnameWarning(history, done); }); }); describe("replace a new path", () => { it("calls change listeners with the new location", (done) => { ReplaceNewLocation(history, done); }); }); describe("replace the same path", () => { it("calls change listeners with the new location", (done) => { ReplaceSamePath(history, done); }); }); describe("replace state", () => { it("calls change listeners with the new location", (done) => { ReplaceState(history, done); }); }); describe("location created with encoded/unencoded reserved characters", () => { it("produces different location objects", (done) => { EncodedReservedCharacters(history, done); }); }); describe("back", () => { it("calls change listeners with the previous location", (done) => { GoBack(history, done); }); }); describe("forward", () => { it("calls change listeners with the next location", (done) => { GoForward(history, done); }); }); describe("block", () => { it("blocks all transitions", (done) => { BlockEverything(history, done); }); }); describe("block a POP without listening", () => { it("receives the next location and action as arguments", (done) => { BlockPopWithoutListening(history, done); }); }); }); ================================================ FILE: packages/history/__tests__/memory-test.js ================================================ import expect from "expect"; import { createMemoryHistory } from "history"; import Listen from "./TestSequences/Listen.js"; import InitialLocationHasKey from "./TestSequences/InitialLocationHasKey.js"; import PushNewLocation from "./TestSequences/PushNewLocation.js"; import PushSamePath from "./TestSequences/PushSamePath.js"; import PushState from "./TestSequences/PushState.js"; import PushMissingPathname from "./TestSequences/PushMissingPathname.js"; import PushRelativePathnameWarning from "./TestSequences/PushRelativePathnameWarning.js"; import ReplaceNewLocation from "./TestSequences/ReplaceNewLocation.js"; import ReplaceSamePath from "./TestSequences/ReplaceSamePath.js"; import ReplaceState from "./TestSequences/ReplaceState.js"; import EncodedReservedCharacters from "./TestSequences/EncodedReservedCharacters.js"; import GoBack from "./TestSequences/GoBack.js"; import GoForward from "./TestSequences/GoForward.js"; import BlockEverything from "./TestSequences/BlockEverything.js"; import BlockPopWithoutListening from "./TestSequences/BlockPopWithoutListening.js"; describe("a memory history", () => { let history; beforeEach(() => { history = createMemoryHistory(); }); it("has an index property", () => { expect(typeof history.index).toBe("number"); }); it("knows how to create hrefs", () => { const href = history.createHref({ pathname: "/the/path", search: "?the=query", hash: "#the-hash", }); expect(href).toEqual("/the/path?the=query#the-hash"); }); it("knows how to create hrefs from strings", () => { const href = history.createHref("/the/path?the=query#the-hash"); expect(href).toEqual("/the/path?the=query#the-hash"); }); it("does not encode the generated path", () => { const encodedHref = history.createHref({ pathname: "/%23abc", }); expect(encodedHref).toEqual("/%23abc"); const unencodedHref = history.createHref({ pathname: "/#abc", }); expect(unencodedHref).toEqual("/#abc"); }); describe("listen", () => { it("does not immediately call listeners", (done) => { Listen(history, done); }); }); describe("the initial location", () => { it("has a key", (done) => { InitialLocationHasKey(history, done); }); }); describe("push a new path", () => { it("calls change listeners with the new location", (done) => { PushNewLocation(history, done); }); }); describe("push the same path", () => { it("calls change listeners with the new location", (done) => { PushSamePath(history, done); }); }); describe("push state", () => { it("calls change listeners with the new location", (done) => { PushState(history, done); }); }); describe("push with no pathname", () => { it("reuses the current location pathname", (done) => { PushMissingPathname(history, done); }); }); describe("push with a relative pathname", () => { it("issues a warning", (done) => { PushRelativePathnameWarning(history, done); }); }); describe("replace a new path", () => { it("calls change listeners with the new location", (done) => { ReplaceNewLocation(history, done); }); }); describe("replace the same path", () => { it("calls change listeners with the new location", (done) => { ReplaceSamePath(history, done); }); }); describe("replace state", () => { it("calls change listeners with the new location", (done) => { ReplaceState(history, done); }); }); describe("location created with encoded/unencoded reserved characters", () => { it("produces different location objects", (done) => { EncodedReservedCharacters(history, done); }); }); describe("back", () => { it("calls change listeners with the previous location", (done) => { GoBack(history, done); }); }); describe("forward", () => { it("calls change listeners with the next location", (done) => { GoForward(history, done); }); }); describe("block", () => { it("blocks all transitions", (done) => { BlockEverything(history, done); }); }); describe("block a POP without listening", () => { it("receives the next location and action as arguments", (done) => { BlockPopWithoutListening(history, done); }); }); }); describe("a memory history with some initial entries", () => { it("clamps the initial index to a valid value", () => { let history = createMemoryHistory({ initialEntries: ["/one", "/two", "/three"], initialIndex: 3, // invalid }); expect(history.index).toBe(2); }); it("starts at the last entry by default", () => { let history = createMemoryHistory({ initialEntries: ["/one", "/two", "/three"], }); expect(history.index).toBe(2); expect(history.location).toMatchObject({ pathname: "/three", search: "", hash: "", state: null, key: expect.any(String), }); }); }); ================================================ FILE: packages/history/browser.ts ================================================ import { createBrowserHistory } from "history"; /** * Create a default instance for the current document. */ export default createBrowserHistory(); ================================================ FILE: packages/history/hash.ts ================================================ import { createHashHistory } from "history"; /** * Create a default instance for the current document. */ export default createHashHistory(); ================================================ FILE: packages/history/index.ts ================================================ /** * Actions represent the type of change to a location value. * * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#action */ export enum Action { /** * A POP indicates a change to an arbitrary index in the history stack, such * as a back or forward navigation. It does not describe the direction of the * navigation, only that the current index changed. * * Note: This is the default action for newly created history objects. */ Pop = "POP", /** * A PUSH indicates a new entry being added to the history stack, such as when * a link is clicked and a new page loads. When this happens, all subsequent * entries in the stack are lost. */ Push = "PUSH", /** * A REPLACE indicates the entry at the current index in the history stack * being replaced by a new one. */ Replace = "REPLACE", } /** * A URL pathname, beginning with a /. * * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#location.pathname */ export type Pathname = string; /** * A URL search string, beginning with a ?. * * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#location.search */ export type Search = string; /** * A URL fragment identifier, beginning with a #. * * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#location.hash */ export type Hash = string; /** * An object that is used to associate some arbitrary data with a location, but * that does not appear in the URL path. * * @deprecated * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#location.state */ export type State = unknown; /** * A unique string associated with a location. May be used to safely store * and retrieve data in some other storage API, like `localStorage`. * * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#location.key */ export type Key = string; /** * The pathname, search, and hash values of a URL. */ export interface Path { /** * A URL pathname, beginning with a /. * * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#location.pathname */ pathname: Pathname; /** * A URL search string, beginning with a ?. * * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#location.search */ search: Search; /** * A URL fragment identifier, beginning with a #. * * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#location.hash */ hash: Hash; } /** * An entry in a history stack. A location contains information about the * URL path, as well as possibly some arbitrary state and a key. * * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#location */ export interface Location extends Path { /** * A value of arbitrary data associated with this location. * * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#location.state */ state: unknown; /** * A unique string associated with this location. May be used to safely store * and retrieve data in some other storage API, like `localStorage`. * * Note: This value is always "default" on the initial location. * * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#location.key */ key: Key; } /** * A partial Path object that may be missing some properties. * * @deprecated */ export type PartialPath = Partial; /** * A partial Location object that may be missing some properties. * * @deprecated */ export type PartialLocation = Partial; /** * A change to the current location. */ export interface Update { /** * The action that triggered the change. */ action: Action; /** * The new location. */ location: Location; } /** * A function that receives notifications about location changes. */ export interface Listener { (update: Update): void; } /** * A change to the current location that was blocked. May be retried * after obtaining user confirmation. */ export interface Transition extends Update { /** * Retries the update to the current location. */ retry(): void; } /** * A function that receives transitions when navigation is blocked. */ export interface Blocker { (tx: Transition): void; } /** * Describes a location that is the destination of some navigation, either via * `history.push` or `history.replace`. May be either a URL or the pieces of a * URL path. */ export type To = string | Partial; /** * A history is an interface to the navigation stack. The history serves as the * source of truth for the current location, as well as provides a set of * methods that may be used to change it. * * It is similar to the DOM's `window.history` object, but with a smaller, more * focused API. */ export interface History { /** * The last action that modified the current location. This will always be * Action.Pop when a history instance is first created. This value is mutable. * * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#history.action */ readonly action: Action; /** * The current location. This value is mutable. * * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#history.location */ readonly location: Location; /** * Returns a valid href for the given `to` value that may be used as * the value of an attribute. * * @param to - The destination URL * * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#history.createHref */ createHref(to: To): string; /** * Pushes a new location onto the history stack, increasing its length by one. * If there were any entries in the stack after the current one, they are * lost. * * @param to - The new URL * @param state - Data to associate with the new location * * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#history.push */ push(to: To, state?: any): void; /** * Replaces the current location in the history stack with a new one. The * location that was replaced will no longer be available. * * @param to - The new URL * @param state - Data to associate with the new location * * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#history.replace */ replace(to: To, state?: any): void; /** * Navigates `n` entries backward/forward in the history stack relative to the * current index. For example, a "back" navigation would use go(-1). * * @param delta - The delta in the stack index * * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#history.go */ go(delta: number): void; /** * Navigates to the previous entry in the stack. Identical to go(-1). * * Warning: if the current location is the first location in the stack, this * will unload the current document. * * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#history.back */ back(): void; /** * Navigates to the next entry in the stack. Identical to go(1). * * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#history.forward */ forward(): void; /** * Sets up a listener that will be called whenever the current location * changes. * * @param listener - A function that will be called when the location changes * @returns unlisten - A function that may be used to stop listening * * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#history.listen */ listen(listener: Listener): () => void; /** * Prevents the current location from changing and sets up a listener that * will be called instead. * * @param blocker - A function that will be called when a transition is blocked * @returns unblock - A function that may be used to stop blocking * * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#history.block */ block(blocker: Blocker): () => void; } /** * A browser history stores the current location in regular URLs in a web * browser environment. This is the standard for most web apps and provides the * cleanest URLs the browser's address bar. * * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#browserhistory */ export interface BrowserHistory extends History {} /** * A hash history stores the current location in the fragment identifier portion * of the URL in a web browser environment. * * This is ideal for apps that do not control the server for some reason * (because the fragment identifier is never sent to the server), including some * shared hosting environments that do not provide fine-grained controls over * which pages are served at which URLs. * * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#hashhistory */ export interface HashHistory extends History {} /** * A memory history stores locations in memory. This is useful in stateful * environments where there is no web browser, such as node tests or React * Native. * * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#memoryhistory */ export interface MemoryHistory extends History { readonly index: number; } const readOnly: (obj: T) => Readonly = __DEV__ ? (obj) => Object.freeze(obj) : (obj) => obj; function warning(cond: any, message: string) { if (!cond) { // eslint-disable-next-line no-console if (typeof console !== "undefined") console.warn(message); try { // Welcome to debugging history! // // This error is thrown as a convenience so you can more easily // find the source for a warning that appears in the console by // enabling "pause on exceptions" in your JavaScript debugger. throw new Error(message); // eslint-disable-next-line no-empty } catch (e) {} } } //////////////////////////////////////////////////////////////////////////////// // BROWSER //////////////////////////////////////////////////////////////////////////////// type HistoryState = { usr: any; key?: string; idx: number; }; const BeforeUnloadEventType = "beforeunload"; const HashChangeEventType = "hashchange"; const PopStateEventType = "popstate"; export type BrowserHistoryOptions = { window?: Window }; /** * Browser history stores the location in regular URLs. This is the standard for * most web apps, but it requires some configuration on the server to ensure you * serve the same app at multiple URLs. * * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory */ export function createBrowserHistory( options: BrowserHistoryOptions = {} ): BrowserHistory { let { window = document.defaultView! } = options; let globalHistory = window.history; function getIndexAndLocation(): [number, Location] { let { pathname, search, hash } = window.location; let state = globalHistory.state || {}; return [ state.idx, readOnly({ pathname, search, hash, state: state.usr || null, key: state.key || "default", }), ]; } let blockedPopTx: Transition | null = null; function handlePop() { if (blockedPopTx) { blockers.call(blockedPopTx); blockedPopTx = null; } else { let nextAction = Action.Pop; let [nextIndex, nextLocation] = getIndexAndLocation(); if (blockers.length) { if (nextIndex != null) { let delta = index - nextIndex; if (delta) { // Revert the POP blockedPopTx = { action: nextAction, location: nextLocation, retry() { go(delta * -1); }, }; go(delta); } } else { // Trying to POP to a location with no index. We did not create // this location, so we can't effectively block the navigation. warning( false, // TODO: Write up a doc that explains our blocking strategy in // detail and link to it here so people can understand better what // is going on and how to avoid it. `You are trying to block a POP navigation to a location that was not ` + `created by the history library. The block will fail silently in ` + `production, but in general you should do all navigation with the ` + `history library (instead of using window.history.pushState directly) ` + `to avoid this situation.` ); } } else { applyTx(nextAction); } } } window.addEventListener(PopStateEventType, handlePop); let action = Action.Pop; let [index, location] = getIndexAndLocation(); let listeners = createEvents(); let blockers = createEvents(); if (index == null) { index = 0; globalHistory.replaceState({ ...globalHistory.state, idx: index }, ""); } function createHref(to: To) { return typeof to === "string" ? to : createPath(to); } // state defaults to `null` because `window.history.state` does function getNextLocation(to: To, state: any = null): Location { return readOnly({ pathname: location.pathname, hash: "", search: "", ...(typeof to === "string" ? parsePath(to) : to), state, key: createKey(), }); } function getHistoryStateAndUrl( nextLocation: Location, index: number ): [HistoryState, string] { return [ { usr: nextLocation.state, key: nextLocation.key, idx: index, }, createHref(nextLocation), ]; } function allowTx(action: Action, location: Location, retry: () => void) { return ( !blockers.length || (blockers.call({ action, location, retry }), false) ); } function applyTx(nextAction: Action) { action = nextAction; [index, location] = getIndexAndLocation(); listeners.call({ action, location }); } function push(to: To, state?: any) { let nextAction = Action.Push; let nextLocation = getNextLocation(to, state); function retry() { push(to, state); } if (allowTx(nextAction, nextLocation, retry)) { let [historyState, url] = getHistoryStateAndUrl(nextLocation, index + 1); // TODO: Support forced reloading // try...catch because iOS limits us to 100 pushState calls :/ try { globalHistory.pushState(historyState, "", url); } catch (error) { // They are going to lose state here, but there is no real // way to warn them about it since the page will refresh... window.location.assign(url); } applyTx(nextAction); } } function replace(to: To, state?: any) { let nextAction = Action.Replace; let nextLocation = getNextLocation(to, state); function retry() { replace(to, state); } if (allowTx(nextAction, nextLocation, retry)) { let [historyState, url] = getHistoryStateAndUrl(nextLocation, index); // TODO: Support forced reloading globalHistory.replaceState(historyState, "", url); applyTx(nextAction); } } function go(delta: number) { globalHistory.go(delta); } let history: BrowserHistory = { get action() { return action; }, get location() { return location; }, createHref, push, replace, go, back() { go(-1); }, forward() { go(1); }, listen(listener) { return listeners.push(listener); }, block(blocker) { let unblock = blockers.push(blocker); if (blockers.length === 1) { window.addEventListener(BeforeUnloadEventType, promptBeforeUnload); } return function () { unblock(); // Remove the beforeunload listener so the document may // still be salvageable in the pagehide event. // See https://html.spec.whatwg.org/#unloading-documents if (!blockers.length) { window.removeEventListener(BeforeUnloadEventType, promptBeforeUnload); } }; }, }; return history; } //////////////////////////////////////////////////////////////////////////////// // HASH //////////////////////////////////////////////////////////////////////////////// export type HashHistoryOptions = { window?: Window }; /** * Hash history stores the location in window.location.hash. This makes it ideal * for situations where you don't want to send the location to the server for * some reason, either because you do cannot configure it or the URL space is * reserved for something else. * * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory */ export function createHashHistory( options: HashHistoryOptions = {} ): HashHistory { let { window = document.defaultView! } = options; let globalHistory = window.history; function getIndexAndLocation(): [number, Location] { let { pathname = "/", search = "", hash = "", } = parsePath(window.location.hash.substr(1)); let state = globalHistory.state || {}; return [ state.idx, readOnly({ pathname, search, hash, state: state.usr || null, key: state.key || "default", }), ]; } let blockedPopTx: Transition | null = null; function handlePop() { if (blockedPopTx) { blockers.call(blockedPopTx); blockedPopTx = null; } else { let nextAction = Action.Pop; let [nextIndex, nextLocation] = getIndexAndLocation(); if (blockers.length) { if (nextIndex != null) { let delta = index - nextIndex; if (delta) { // Revert the POP blockedPopTx = { action: nextAction, location: nextLocation, retry() { go(delta * -1); }, }; go(delta); } } else { // Trying to POP to a location with no index. We did not create // this location, so we can't effectively block the navigation. warning( false, // TODO: Write up a doc that explains our blocking strategy in // detail and link to it here so people can understand better // what is going on and how to avoid it. `You are trying to block a POP navigation to a location that was not ` + `created by the history library. The block will fail silently in ` + `production, but in general you should do all navigation with the ` + `history library (instead of using window.history.pushState directly) ` + `to avoid this situation.` ); } } else { applyTx(nextAction); } } } window.addEventListener(PopStateEventType, handlePop); // popstate does not fire on hashchange in IE 11 and old (trident) Edge // https://developer.mozilla.org/de/docs/Web/API/Window/popstate_event window.addEventListener(HashChangeEventType, () => { let [, nextLocation] = getIndexAndLocation(); // Ignore extraneous hashchange events. if (createPath(nextLocation) !== createPath(location)) { handlePop(); } }); let action = Action.Pop; let [index, location] = getIndexAndLocation(); let listeners = createEvents(); let blockers = createEvents(); if (index == null) { index = 0; globalHistory.replaceState({ ...globalHistory.state, idx: index }, ""); } function getBaseHref() { let base = document.querySelector("base"); let href = ""; if (base && base.getAttribute("href")) { let url = window.location.href; let hashIndex = url.indexOf("#"); href = hashIndex === -1 ? url : url.slice(0, hashIndex); } return href; } function createHref(to: To) { return getBaseHref() + "#" + (typeof to === "string" ? to : createPath(to)); } function getNextLocation(to: To, state: any = null): Location { return readOnly({ pathname: location.pathname, hash: "", search: "", ...(typeof to === "string" ? parsePath(to) : to), state, key: createKey(), }); } function getHistoryStateAndUrl( nextLocation: Location, index: number ): [HistoryState, string] { return [ { usr: nextLocation.state, key: nextLocation.key, idx: index, }, createHref(nextLocation), ]; } function allowTx(action: Action, location: Location, retry: () => void) { return ( !blockers.length || (blockers.call({ action, location, retry }), false) ); } function applyTx(nextAction: Action) { action = nextAction; [index, location] = getIndexAndLocation(); listeners.call({ action, location }); } function push(to: To, state?: any) { let nextAction = Action.Push; let nextLocation = getNextLocation(to, state); function retry() { push(to, state); } warning( nextLocation.pathname.charAt(0) === "/", `Relative pathnames are not supported in hash history.push(${JSON.stringify( to )})` ); if (allowTx(nextAction, nextLocation, retry)) { let [historyState, url] = getHistoryStateAndUrl(nextLocation, index + 1); // TODO: Support forced reloading // try...catch because iOS limits us to 100 pushState calls :/ try { globalHistory.pushState(historyState, "", url); } catch (error) { // They are going to lose state here, but there is no real // way to warn them about it since the page will refresh... window.location.assign(url); } applyTx(nextAction); } } function replace(to: To, state?: any) { let nextAction = Action.Replace; let nextLocation = getNextLocation(to, state); function retry() { replace(to, state); } warning( nextLocation.pathname.charAt(0) === "/", `Relative pathnames are not supported in hash history.replace(${JSON.stringify( to )})` ); if (allowTx(nextAction, nextLocation, retry)) { let [historyState, url] = getHistoryStateAndUrl(nextLocation, index); // TODO: Support forced reloading globalHistory.replaceState(historyState, "", url); applyTx(nextAction); } } function go(delta: number) { globalHistory.go(delta); } let history: HashHistory = { get action() { return action; }, get location() { return location; }, createHref, push, replace, go, back() { go(-1); }, forward() { go(1); }, listen(listener) { return listeners.push(listener); }, block(blocker) { let unblock = blockers.push(blocker); if (blockers.length === 1) { window.addEventListener(BeforeUnloadEventType, promptBeforeUnload); } return function () { unblock(); // Remove the beforeunload listener so the document may // still be salvageable in the pagehide event. // See https://html.spec.whatwg.org/#unloading-documents if (!blockers.length) { window.removeEventListener(BeforeUnloadEventType, promptBeforeUnload); } }; }, }; return history; } //////////////////////////////////////////////////////////////////////////////// // MEMORY //////////////////////////////////////////////////////////////////////////////// /** * A user-supplied object that describes a location. Used when providing * entries to `createMemoryHistory` via its `initialEntries` option. */ export type InitialEntry = string | Partial; export type MemoryHistoryOptions = { initialEntries?: InitialEntry[]; initialIndex?: number; }; /** * Memory history stores the current location in memory. It is designed for use * in stateful non-browser environments like tests and React Native. * * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#creatememoryhistory */ export function createMemoryHistory( options: MemoryHistoryOptions = {} ): MemoryHistory { let { initialEntries = ["/"], initialIndex } = options; let entries: Location[] = initialEntries.map((entry) => { let location = readOnly({ pathname: "/", search: "", hash: "", state: null, key: createKey(), ...(typeof entry === "string" ? parsePath(entry) : entry), }); warning( location.pathname.charAt(0) === "/", `Relative pathnames are not supported in createMemoryHistory({ initialEntries }) (invalid entry: ${JSON.stringify( entry )})` ); return location; }); let index = clamp( initialIndex == null ? entries.length - 1 : initialIndex, 0, entries.length - 1 ); let action = Action.Pop; let location = entries[index]; let listeners = createEvents(); let blockers = createEvents(); function createHref(to: To) { return typeof to === "string" ? to : createPath(to); } function getNextLocation(to: To, state: any = null): Location { return readOnly({ pathname: location.pathname, search: "", hash: "", ...(typeof to === "string" ? parsePath(to) : to), state, key: createKey(), }); } function allowTx(action: Action, location: Location, retry: () => void) { return ( !blockers.length || (blockers.call({ action, location, retry }), false) ); } function applyTx(nextAction: Action, nextLocation: Location) { action = nextAction; location = nextLocation; listeners.call({ action, location }); } function push(to: To, state?: any) { let nextAction = Action.Push; let nextLocation = getNextLocation(to, state); function retry() { push(to, state); } warning( location.pathname.charAt(0) === "/", `Relative pathnames are not supported in memory history.push(${JSON.stringify( to )})` ); if (allowTx(nextAction, nextLocation, retry)) { index += 1; entries.splice(index, entries.length, nextLocation); applyTx(nextAction, nextLocation); } } function replace(to: To, state?: any) { let nextAction = Action.Replace; let nextLocation = getNextLocation(to, state); function retry() { replace(to, state); } warning( location.pathname.charAt(0) === "/", `Relative pathnames are not supported in memory history.replace(${JSON.stringify( to )})` ); if (allowTx(nextAction, nextLocation, retry)) { entries[index] = nextLocation; applyTx(nextAction, nextLocation); } } function go(delta: number) { let nextIndex = clamp(index + delta, 0, entries.length - 1); let nextAction = Action.Pop; let nextLocation = entries[nextIndex]; function retry() { go(delta); } if (allowTx(nextAction, nextLocation, retry)) { index = nextIndex; applyTx(nextAction, nextLocation); } } let history: MemoryHistory = { get index() { return index; }, get action() { return action; }, get location() { return location; }, createHref, push, replace, go, back() { go(-1); }, forward() { go(1); }, listen(listener) { return listeners.push(listener); }, block(blocker) { return blockers.push(blocker); }, }; return history; } //////////////////////////////////////////////////////////////////////////////// // UTILS //////////////////////////////////////////////////////////////////////////////// function clamp(n: number, lowerBound: number, upperBound: number) { return Math.min(Math.max(n, lowerBound), upperBound); } function promptBeforeUnload(event: BeforeUnloadEvent) { // Cancel the event. event.preventDefault(); // Chrome (and legacy IE) requires returnValue to be set. event.returnValue = ""; } type Events = { length: number; push: (fn: F) => () => void; call: (arg: any) => void; }; function createEvents(): Events { let handlers: F[] = []; return { get length() { return handlers.length; }, push(fn: F) { handlers.push(fn); return function () { handlers = handlers.filter((handler) => handler !== fn); }; }, call(arg) { handlers.forEach((fn) => fn && fn(arg)); }, }; } function createKey() { return Math.random().toString(36).substr(2, 8); } /** * Creates a string URL path from the given pathname, search, and hash components. * * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createpath */ export function createPath({ pathname = "/", search = "", hash = "", }: Partial) { if (search && search !== "?") pathname += search.charAt(0) === "?" ? search : "?" + search; if (hash && hash !== "#") pathname += hash.charAt(0) === "#" ? hash : "#" + hash; return pathname; } /** * Parses a string URL path into its separate pathname, search, and hash components. * * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#parsepath */ export function parsePath(path: string): Partial { let parsedPath: Partial = {}; if (path) { let hashIndex = path.indexOf("#"); if (hashIndex >= 0) { parsedPath.hash = path.substr(hashIndex); path = path.substr(0, hashIndex); } let searchIndex = path.indexOf("?"); if (searchIndex >= 0) { parsedPath.search = path.substr(searchIndex); path = path.substr(0, searchIndex); } if (path) { parsedPath.pathname = path; } } return parsedPath; } ================================================ FILE: packages/history/node-main.js ================================================ /* eslint-env node */ if (process.env.NODE_ENV === "production") { module.exports = require("./umd/history.production.min.js"); } else { module.exports = require("./umd/history.development.js"); } ================================================ FILE: packages/history/package.json ================================================ { "name": "history", "version": "5.3.0", "description": "Manage session history with JavaScript", "author": "Remix Software ", "repository": "remix-run/history", "license": "MIT", "main": "main.js", "module": "index.js", "types": "index.d.ts", "unpkg": "umd/history.production.min.js", "sideEffects": false, "dependencies": { "@babel/runtime": "^7.7.6" }, "keywords": [ "history", "location" ] } ================================================ FILE: scripts/build.js ================================================ const path = require("path"); const execSync = require("child_process").execSync; let config = path.resolve(__dirname, "rollup/history.config.js"); execSync(`rollup -c ${config}`, { env: process.env, stdio: "inherit", }); ================================================ FILE: scripts/karma.conf.js ================================================ var path = require("path"); var webpack = require("webpack"); module.exports = function (config) { var customLaunchers = { BS_Chrome: { name: "Chrome", base: "BrowserStack", os: "Windows", os_version: "10", browser: "Chrome", browser_version: "73.0", }, // BS_ChromeAndroid: { // base: 'BrowserStack', // device: 'Samsung Galaxy S8', // os_version: '7.0', // real_mobile: true // }, BS_Firefox: { name: "Firefox", base: "BrowserStack", os: "Windows", os_version: "10", browser: "Firefox", browser_version: "67.0", }, BS_Edge: { name: "Edge", base: "BrowserStack", os: "Windows", os_version: "10", browser: "Edge", browser_version: "17.0", }, BS_IE11: { name: "IE 11", base: "BrowserStack", os: "Windows", os_version: "10", browser: "IE", browser_version: "11.0", }, // Safari throws an error if you use replaceState more // than 100 times in 30 seconds :/ // BS_Safari: { // base: 'BrowserStack', // os: 'OS X', // os_version: 'Mojave', // browser: 'Safari', // browser_version: '12.1' // } // BS_iPhoneX: { // base: 'BrowserStack', // device: 'iPhone X', // os_version: '11', // real_mobile: true // }, // BS_iPhoneXS: { // base: 'BrowserStack', // device: 'iPhone XS', // os_version: '12', // real_mobile: true // }, }; config.set({ singleRun: true, customLaunchers: customLaunchers, browsers: ["Chrome" /*, 'Firefox'*/], frameworks: ["mocha" /*, 'webpack' */], reporters: ["mocha"], files: ["tests.webpack.js"], preprocessors: { "tests.webpack.js": ["webpack", "sourcemap"], }, webpack: { // TODO: Webpack 4+ // mode: 'none', devtool: "inline-source-map", resolve: { modules: [path.resolve(__dirname, "../"), "node_modules"], alias: { history: path.resolve(__dirname, "../build/history"), }, }, module: { rules: [ { test: /__tests__\/.*\.js$/, exclude: /node_modules/, use: { loader: "babel-loader", options: { presets: ["@babel/preset-env"], }, }, }, ], }, plugins: [ new webpack.DefinePlugin({ "process.env.NODE_ENV": JSON.stringify("test"), }), ], }, webpackServer: { noInfo: true, }, }); if (process.env.TRAVIS || process.env.USE_CLOUD) { config.browsers = Object.keys(customLaunchers); config.reporters = ["dots"]; config.concurrency = 2; config.browserDisconnectTimeout = 10000; config.browserDisconnectTolerance = 3; if (process.env.TRAVIS) { config.browserStack = { project: "history", build: process.env.TRAVIS_BRANCH, }; } else { config.browserStack = { project: "history", }; } } }; ================================================ FILE: scripts/publish.js ================================================ const path = require("path"); const execSync = require("child_process").execSync; const jsonfile = require("jsonfile"); const semver = require("semver"); const rootDir = path.resolve(__dirname, ".."); function invariant(cond, message) { if (!cond) throw new Error(message); } function getTaggedVersion() { let output = execSync("git tag --list --points-at HEAD").toString(); return output.replace(/^v|\n+$/g, ""); } async function ensureBuildVersion(packageName, version) { let file = path.join(rootDir, "build", packageName, "package.json"); let json = await jsonfile.readFile(file); invariant( json.version === version, `Package ${packageName} is on version ${json.version}, but should be on ${version}` ); } function publishBuild(packageName, tag) { let buildDir = path.join(rootDir, "build", packageName); console.log(); console.log(` npm publish ${buildDir} --tag ${tag}`); console.log(); execSync(`npm publish ${buildDir} --tag ${tag}`, { stdio: "inherit" }); } async function run() { try { // 0. Ensure we are in CI. We don't do this manually invariant( process.env.CI, `You should always run the publish script from the CI environment!` ); // 1. Get the current tag, which has the release version number let version = getTaggedVersion(); invariant( version !== "", "Missing release version. Run the version script first." ); // 2. Determine the appropriate npm tag to use let tag = semver.prerelease(version) == null ? "latest" : "next"; console.log(); console.log(` Publishing version ${version} to npm with tag "${tag}"`); // 3. Ensure build versions match the release version await ensureBuildVersion("history", version); // 4. Publish to npm publishBuild("history", tag); } catch (error) { console.log(); console.error(` ${error.message}`); console.log(); return 1; } return 0; } run().then((code) => { process.exit(code); }); ================================================ FILE: scripts/rollup/history.config.js ================================================ import { babel } from "@rollup/plugin-babel"; import copy from "rollup-plugin-copy"; import prettier from "rollup-plugin-prettier"; import replace from "@rollup/plugin-replace"; import { terser } from "rollup-plugin-terser"; import typescript from "rollup-plugin-typescript2"; const PRETTY = !!process.env.PRETTY; const SOURCE_DIR = "packages/history"; const OUTPUT_DIR = "build/history"; const modules = [ { input: `${SOURCE_DIR}/index.ts`, output: { file: `${OUTPUT_DIR}/index.js`, format: "esm", sourcemap: !PRETTY, }, external: ["@babel/runtime/helpers/esm/extends"], plugins: [ typescript({ tsconfigDefaults: { compilerOptions: { declaration: true, }, }, }), babel({ exclude: /node_modules/, extensions: [".ts"], presets: [["@babel/preset-env", { loose: true }]], plugins: [ "babel-plugin-dev-expression", ["@babel/plugin-transform-runtime", { useESModules: true }], ], babelHelpers: "runtime", }), copy({ targets: [ { src: "README.md", dest: OUTPUT_DIR }, { src: "LICENSE", dest: OUTPUT_DIR }, { src: `${SOURCE_DIR}/package.json`, dest: OUTPUT_DIR }, ], verbose: true, }), ].concat(PRETTY ? prettier({ parser: "babel" }) : []), }, ...["browser", "hash"].map((env) => { return { input: `${SOURCE_DIR}/${env}.ts`, output: { file: `${OUTPUT_DIR}/${env}.js`, format: "esm", sourcemap: !PRETTY, }, plugins: [ typescript({ tsconfigDefaults: { compilerOptions: { declaration: true, }, }, }), babel({ exclude: /node_modules/, extensions: [".ts"], presets: [["@babel/preset-env", { loose: true }]], plugins: ["babel-plugin-dev-expression"], babelHelpers: "bundled", }), ].concat(PRETTY ? prettier({ parser: "babel" }) : []), }; }), ]; const webModules = [ { input: `${SOURCE_DIR}/index.ts`, output: { file: `${OUTPUT_DIR}/history.development.js`, format: "esm", sourcemap: !PRETTY, }, plugins: [ typescript({ tsconfigOverride: { compilerOptions: { target: "es2016", }, }, }), babel({ exclude: /node_modules/, extensions: [".ts"], presets: ["@babel/preset-modules"], plugins: ["babel-plugin-dev-expression"], babelHelpers: "bundled", }), replace({ "process.env.NODE_ENV": JSON.stringify("development"), preventAssignment: false, }), ].concat(PRETTY ? prettier({ parser: "babel" }) : []), }, { input: `${SOURCE_DIR}/index.ts`, output: { file: `${OUTPUT_DIR}/history.production.min.js`, format: "esm", sourcemap: !PRETTY, }, plugins: [ typescript({ tsconfigOverride: { compilerOptions: { target: "es2016", }, }, }), babel({ exclude: /node_modules/, extensions: [".ts"], presets: ["@babel/preset-modules"], plugins: ["babel-plugin-dev-expression"], babelHelpers: "bundled", }), replace({ "process.env.NODE_ENV": JSON.stringify("production"), preventAssignment: false, }), terser({ ecma: 8, safari10: true }), ].concat(PRETTY ? prettier({ parser: "babel" }) : []), }, ]; const globals = [ { input: `${SOURCE_DIR}/index.ts`, output: { file: `${OUTPUT_DIR}/umd/history.development.js`, format: "umd", sourcemap: !PRETTY, name: "HistoryLibrary", }, plugins: [ typescript(), babel({ exclude: /node_modules/, extensions: [".ts"], presets: [["@babel/preset-env", { loose: true }]], plugins: ["babel-plugin-dev-expression"], babelHelpers: "bundled", }), replace({ "process.env.NODE_ENV": JSON.stringify("development"), preventAssignment: false, }), ].concat(PRETTY ? prettier({ parser: "babel" }) : []), }, { input: `${SOURCE_DIR}/index.ts`, output: { file: `${OUTPUT_DIR}/umd/history.production.min.js`, format: "umd", sourcemap: !PRETTY, name: "HistoryLibrary", }, plugins: [ typescript(), babel({ exclude: /node_modules/, extensions: [".ts"], presets: [["@babel/preset-env", { loose: true }]], plugins: ["babel-plugin-dev-expression"], babelHelpers: "bundled", }), replace({ "process.env.NODE_ENV": JSON.stringify("production"), preventAssignment: false, }), terser(), ].concat(PRETTY ? prettier({ parser: "babel" }) : []), }, ]; const node = [ { input: `${SOURCE_DIR}/node-main.js`, output: { file: `${OUTPUT_DIR}/main.js`, format: "cjs", }, plugins: PRETTY ? prettier({ parser: "babel" }) : [], }, ]; const config = [...modules, ...webModules, ...globals, ...node]; export default config; ================================================ FILE: scripts/test.js ================================================ const path = require("path"); const execSync = require("child_process").execSync; let karmaConfig = path.resolve(__dirname, "karma.conf.js"); execSync(`karma start ${karmaConfig}`, { env: process.env, stdio: "inherit", }); ================================================ FILE: scripts/tests.webpack.js ================================================ var context = require.context("../packages", true, /-test\.js$/); context.keys().forEach(context); ================================================ FILE: scripts/version.js ================================================ const path = require("path"); const execSync = require("child_process").execSync; const chalk = require("chalk"); const Confirm = require("prompt-confirm"); const jsonfile = require("jsonfile"); const semver = require("semver"); const rootDir = path.resolve(__dirname, ".."); function packageJson(packageName) { return path.join(rootDir, "packages", packageName, "package.json"); } function invariant(cond, message) { if (!cond) throw new Error(message); } function ensureCleanWorkingDirectory() { let status = execSync(`git status --porcelain`).toString().trim(); let lines = status.split("\n"); invariant( lines.every((line) => line === "" || line.startsWith("?")), "Working directory is not clean. Please commit or stash your changes." ); } function getNextVersion(currentVersion, givenVersion, prereleaseId) { invariant( givenVersion != null, `Missing next version. Usage: node version.js [nextVersion]` ); if (/^pre/.test(givenVersion)) { invariant( prereleaseId != null, `Missing prerelease id. Usage: node version.js ${givenVersion} [prereleaseId]` ); } let nextVersion = semver.inc(currentVersion, givenVersion, prereleaseId); invariant(nextVersion != null, `Invalid version specifier: ${givenVersion}`); return nextVersion; } async function prompt(question) { let confirm = new Confirm(question); let answer = await confirm.run(); return answer; } async function getPackageVersion(packageName) { let file = packageJson(packageName); let json = await jsonfile.readFile(file); return json.version; } async function updatePackageConfig(packageName, transform) { let file = packageJson(packageName); let json = await jsonfile.readFile(file); transform(json); await jsonfile.writeFile(file, json, { spaces: 2 }); } async function run() { try { let args = process.argv.slice(2); let givenVersion = args[0]; let prereleaseId = args[1]; // 0. Make sure the working directory is clean ensureCleanWorkingDirectory(); // 1. Get the next version number let currentVersion = await getPackageVersion("history"); let version = semver.valid(givenVersion); if (version == null) { version = getNextVersion(currentVersion, givenVersion, prereleaseId); } // 2. Confirm the next version number let answer = await prompt( `Are you sure you want to bump version ${currentVersion} to ${version}? [Yn] ` ); if (answer === false) return 0; // 3. Update history version await updatePackageConfig("history", (config) => { config.version = version; }); console.log(chalk.green(` Updated history to version ${version}`)); // 4. Commit and tag execSync(`git commit --all --message="Version ${version}"`); execSync(`git tag -a -m "Version ${version}" v${version}`); console.log(chalk.green(` Committed and tagged version ${version}`)); } catch (error) { console.log(); console.error(chalk.red(` ${error.message}`)); console.log(); return 1; } return 0; } run().then((code) => { process.exit(code); }); ================================================ FILE: tsconfig.json ================================================ { "include": ["packages", "types"], "compilerOptions": { "lib": ["dom", "esnext"], "module": "esnext", "target": "es2018", "moduleResolution": "node", "esModuleInterop": true, "strict": true, "noUnusedLocals": true, "noUnusedParameters": true, "noImplicitReturns": true } } ================================================ FILE: types/global.d.ts ================================================ // eslint-disable-next-line no-unused-vars declare const __DEV__: boolean;