Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(gatsby): Support numbers in navigate function #25611

Merged
merged 3 commits into from
Jul 10, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Expand Up @@ -33,6 +33,14 @@ describe(`navigation`, () => {
cy.location(`pathname`).should(`equal`, `/`)
})

it(`can navigate using numbers`, () => {
cy.getTestElement(`page-two`).click().waitForRouteChange()

cy.getTestElement(`back-by-number`).click()

cy.location(`pathname`).should(`equal`, `/`)
})

describe(`relative links`, () => {
it(`can navigate to a subdirectory`, () => {
cy.getTestElement(`subdir-link`)
Expand Down
4 changes: 4 additions & 0 deletions e2e-tests/development-runtime/src/pages/page-2.js
Expand Up @@ -3,6 +3,7 @@ import { Link } from "gatsby"

import Layout from "../components/layout"
import SEO from "../components/seo"
import { navigate } from "gatsby"

const SecondPage = () => (
<Layout>
Expand All @@ -12,6 +13,9 @@ const SecondPage = () => (
<Link to="/" data-testid="back-button">
Go back to the homepage
</Link>
<button data-testid="back-by-number" onClick={() => navigate(-1)}>
Navigate by number back
</button>
</Layout>
)

Expand Down
3 changes: 3 additions & 0 deletions packages/gatsby-link/src/index.js
Expand Up @@ -43,6 +43,9 @@ function absolutify(path, current) {
}

const rewriteLinkPath = (path, relativeTo) => {
if (typeof path === `number`) {
return path
}
if (!isLocalLink(path)) {
return path
}
Expand Down
8 changes: 8 additions & 0 deletions packages/gatsby/cache-dir/navigation.js
Expand Up @@ -47,6 +47,14 @@ const onRouteUpdate = (location, prevLocation) => {
}

const navigate = (to, options = {}) => {
// Support forward/backward navigation with numbers
// navigate(-2) (jumps back 2 history steps)
// navigate(2) (jumps forward 2 history steps)
if (typeof to === `number`) {
globalHistory.navigate(to)
return
}

let { pathname } = parsePath(to)
const redirect = redirectMap[pathname]

Expand Down