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):

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
================================================