From 83926c8ff1df55898ffdeb49183163b5f0bc4270 Mon Sep 17 00:00:00 2001 From: Blaine Kasten Date: Fri, 10 Jul 2020 13:57:35 -0500 Subject: [PATCH] fix(gatsby): Support numbers in navigate function (#25611) * fix(gatsby): Support numbers in navigate function * Fix issue to properly support navigating back by number --- .../cypress/integration/navigation/linking.js | 8 ++++++++ e2e-tests/development-runtime/src/pages/page-2.js | 4 ++++ packages/gatsby-link/src/index.js | 3 +++ packages/gatsby/cache-dir/navigation.js | 8 ++++++++ 4 files changed, 23 insertions(+) diff --git a/e2e-tests/development-runtime/cypress/integration/navigation/linking.js b/e2e-tests/development-runtime/cypress/integration/navigation/linking.js index c15825a940ef8..e2ead7659398b 100644 --- a/e2e-tests/development-runtime/cypress/integration/navigation/linking.js +++ b/e2e-tests/development-runtime/cypress/integration/navigation/linking.js @@ -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`) diff --git a/e2e-tests/development-runtime/src/pages/page-2.js b/e2e-tests/development-runtime/src/pages/page-2.js index c6c81c46c047e..568ed111be153 100644 --- a/e2e-tests/development-runtime/src/pages/page-2.js +++ b/e2e-tests/development-runtime/src/pages/page-2.js @@ -3,6 +3,7 @@ import { Link } from "gatsby" import Layout from "../components/layout" import SEO from "../components/seo" +import { navigate } from "gatsby" const SecondPage = () => ( @@ -12,6 +13,9 @@ const SecondPage = () => ( Go back to the homepage + ) diff --git a/packages/gatsby-link/src/index.js b/packages/gatsby-link/src/index.js index 7206979c63e8d..76e8fbf3d89cf 100644 --- a/packages/gatsby-link/src/index.js +++ b/packages/gatsby-link/src/index.js @@ -58,6 +58,9 @@ function absolutify(path, current) { } const rewriteLinkPath = (path, relativeTo) => { + if (typeof path === `number`) { + return path + } if (!isLocalLink(path)) { return path } diff --git a/packages/gatsby/cache-dir/navigation.js b/packages/gatsby/cache-dir/navigation.js index b3f22f6e4de5f..d870bfec62cf1 100644 --- a/packages/gatsby/cache-dir/navigation.js +++ b/packages/gatsby/cache-dir/navigation.js @@ -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]