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

V2: replace navigateTo with push and replace #5944

Merged
merged 4 commits into from
Jun 16, 2018
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions docs/docs/migrating-from-v1-to-v2.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ This is a reference for upgrading your site from Gatsby v1 to Gatsby v2. While t
- [Remove explicit polyfills](#remove-explicit-polyfills)
- [Change `modifyBabelrc` to `onCreateBabelConfig`](#change-modifybabelrc-to-oncreatebabelconfig)
- [Change `modifyWebpackConfig` to `onCreateWebpackConfig`](#change-modifywebpackconfig-to-oncreatewebpackconfig)
- [Change `navigateTo` to `push`](#change-navigateto-to-push)
- [Remove inlined CSS in `html.js`](#remove-inlined-css-in-htmljs)
- [Only allow defined keys on node.internal object](#only-allow-defined-keys-on-the-node-internal-object)
- [Import `graphql` types from `gatsby/graphql`](#import-graphql-types-from-gatsbygraphql)
Expand Down Expand Up @@ -403,6 +404,26 @@ Note usage of the new [`setWebpackConfig` action](/docs/actions/#setWebpackConfi

See [Gatsby's webpack docs for more details](/docs/add-custom-webpack-config) about configuring webpack.

## Change `navigateTo` to `push`

The `navigateTo` method in `gatsby-link` was renamed to `push` so as to mirror the browser history function. We also
added support for using `replace` as well.

In addition to the name change, `gatsby-link` is now directly exported from the `gatsby` package.

```diff
import React from "react"
- import { navigateTo } from "gatsby-link"
+ import { push } from "gatsby"

// Don't use push with an onClick btw :-)
// Generally just use the `<Link>` component.
export default props => (
- <div onClick={() => navigateTo(`/`)}>Click to go to home</div>
+ <div onClick={() => push(`/`)}>Click to go to home</div>
)
```

## Remove inlined CSS in `html.js`

Gatsby v2 automatically inlines CSS. You can remove any custom CSS inlining from your custom `html.js`.
Expand Down
12 changes: 6 additions & 6 deletions examples/gatsbygram/src/components/modal.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import Close from "react-icons/lib/md/close"
import findIndex from "lodash/findIndex"
import mousetrap from "mousetrap"
import * as PropTypes from "prop-types"
import { navigateTo, StaticQuery } from "gatsby"
import { push, StaticQuery } from "gatsby"

import { rhythm } from "../utils/typography"

Expand Down Expand Up @@ -55,7 +55,7 @@ class GatsbyGramModal extends React.Component {
} else {
nextPost = posts[currentIndex + 1]
}
navigateTo(`/${nextPost.id}/`)
push(`/${nextPost.id}/`)
}
}

Expand All @@ -72,7 +72,7 @@ class GatsbyGramModal extends React.Component {
} else {
previousPost = posts[currentIndex - 1]
}
navigateTo(`/${previousPost.id}/`)
push(`/${previousPost.id}/`)
}
}

Expand All @@ -97,7 +97,7 @@ class GatsbyGramModal extends React.Component {
return (
<Modal
isOpen={this.props.isOpen}
onRequestClose={() => navigateTo(`/`)}
onRequestClose={() => push(`/`)}
style={{
overlay: {
position: `fixed`,
Expand All @@ -123,7 +123,7 @@ class GatsbyGramModal extends React.Component {
contentLabel="Modal"
>
<div
onClick={() => navigateTo(`/`)}
onClick={() => push(`/`)}
css={{
display: `flex`,
position: `relative`,
Expand Down Expand Up @@ -164,7 +164,7 @@ class GatsbyGramModal extends React.Component {
</div>
<Close
data-testid="modal-close"
onClick={() => navigateTo(`/`)}
onClick={() => push(`/`)}
css={{
cursor: `pointer`,
color: `rgba(255,255,255,0.8)`,
Expand Down
4 changes: 4 additions & 0 deletions packages/gatsby-link/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@ export interface GatsbyLinkProps extends NavLinkProps {
style?:any;
}

export const push: (to: LocationDescriptor) => void;
export const replace: (to: LocationDescriptor) => void;

// TODO: Remove navigateTo for Gatsby v3
export const navigateTo: (to: LocationDescriptor) => void;

export const withPrefix: (path: string) => string;
Expand Down
26 changes: 20 additions & 6 deletions packages/gatsby-link/src/__tests__/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,20 @@ const getInstance = (props, pathPrefix = ``) => {
return new Link(props, context)
}

const getNavigateTo = () => {
const getPush = () => {
Object.assign(global.window, {
___navigateTo: jest.fn(),
___push: jest.fn(),
})

return require(`../`).navigateTo
return require(`../`).push
}

const getReplace = () => {
Object.assign(global.window, {
___replace: jest.fn(),
})

return require(`../`).replace
}

const getWithPrefix = (pathPrefix = ``) => {
Expand Down Expand Up @@ -113,10 +121,16 @@ describe(`<Link />`, () => {
})
})

it(`navigateTo is called with correct args`, () => {
getNavigateTo()(`/some-path`)
it(`push is called with correct args`, () => {
getPush()(`/some-path`)

expect(global.window.___push).toHaveBeenCalledWith(`/some-path`)
})

it(`replace is called with correct args`, () => {
getReplace()(`/some-path`)

expect(global.window.___navigateTo).toHaveBeenCalledWith(`/some-path`)
expect(global.window.___replace).toHaveBeenCalledWith(`/some-path`)
})
})

Expand Down
16 changes: 14 additions & 2 deletions packages/gatsby-link/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ class GatsbyLink extends React.Component {
// loaded before continuing.
if (process.env.NODE_ENV === `production`) {
e.preventDefault()
window.___navigateTo(this.state.to)
window.___push(this.state.to)
}
}

Expand All @@ -180,6 +180,18 @@ GatsbyLink.contextTypes = {

export default polyfill(GatsbyLink)

export const push = to => {
window.___push(to)
}

export const replace = to => {
window.___replace(to)
}

// TODO: Remove navigateTo for Gatsby v3
export const navigateTo = to => {
window.___navigateTo(to)
console.warn(
`The "navigateTo" method is now deprecated and will be removed in Gatsby v3. Please use "push" instead.`
)
return push(to)
}
8 changes: 4 additions & 4 deletions packages/gatsby-plugin-catch-links/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@ Intercepts local links from markdown and other non-react pages and does a
client-side pushState to avoid the browser having to refresh the page.

For instance, in a markdown file with relative links (transformed
to `a` tags by
[`gatsby-transformer-remark`](/packages/gatsby-transformer-remark/)), this
plugin replaces the default link behaviour
with that of [`gatsby-link`'s `navigateTo`](https://www.gatsbyjs.org/packages/gatsby-link/#programmatic-navigation), preserving the
to `a` tags by
[`gatsby-transformer-remark`](/packages/gatsby-transformer-remark/)), this
plugin replaces the default link behaviour
with that of [`gatsby-link`'s `push`](https://www.gatsbyjs.org/packages/gatsby-link/#programmatic-navigation), preserving the
SPA-like page change without reload.

Check out the [_Using Remark_ example](https://github.com/gatsbyjs/gatsby/tree/master/examples/using-remark) to see this plugin in action.
Expand Down
4 changes: 2 additions & 2 deletions packages/gatsby-plugin-catch-links/src/gatsby-browser.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { navigateTo } from "gatsby-link"
import { push } from "gatsby-link"

import catchLinks from "./catch-links"

exports.onClientEntry = () => {
catchLinks(window, href => {
navigateTo(href)
push(href)
})
}
6 changes: 3 additions & 3 deletions packages/gatsby/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,13 +66,13 @@ render () {
### Programmatic navigation

For cases when you can only use event handlers for navigation, you can use
`navigateTo`:
`push` (which uses `history.push`) or `replace` (which uses `history.replace`):

```jsx
import { navigateTo } from "gatsby"
import { push } from "gatsby"

render () {
<div onClick={ () => navigateTo('/example')}>
<div onClick={ () => push('/example')}>
<p>Example</p>
</div>
}
Expand Down
6 changes: 4 additions & 2 deletions packages/gatsby/src/cache-dir/gatsby-browser-entry.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React from "react"
import PropTypes from "prop-types"
import Link, { withPrefix, navigateTo } from "gatsby-link"
import Link, { withPrefix, push, replace, navigateTo } from "gatsby-link"
import pages from "./pages.json"
import loader from "./loader"
import JSONStore from "./json-store"
Expand Down Expand Up @@ -48,7 +48,9 @@ StaticQuery.propTypes = {
export {
Link,
withPrefix,
navigateTo,
push,
replace,
navigateTo, // TODO: remove navigateTo for v3
StaticQueryContext,
StaticQuery,
PageRenderer,
Expand Down
15 changes: 10 additions & 5 deletions packages/gatsby/src/cache-dir/production-app.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ apiRunnerAsync(`onClientEntry`).then(() => {
require(`./register-service-worker`)
}

const navigateTo = to => {
const navigate = (to, replace) => {
const location = createLocation(to, null, null, history.location)
let { pathname } = location
const redirect = redirectMap[pathname]
Expand All @@ -73,13 +73,17 @@ apiRunnerAsync(`onClientEntry`).then(() => {
return
}

const historyNavigateFunc = replace
? window.___history.replace
: window.___history.push

// Listen to loading events. If page resources load before
// a second, navigate immediately.
function eventHandler(e) {
if (e.page.path === loader.getPage(pathname).path) {
emitter.off(`onPostLoadPageResources`, eventHandler)
clearTimeout(timeoutId)
window.___history.push(location)
historyNavigateFunc(location)
}
}

Expand All @@ -88,13 +92,13 @@ apiRunnerAsync(`onClientEntry`).then(() => {
const timeoutId = setTimeout(() => {
emitter.off(`onPostLoadPageResources`, eventHandler)
emitter.emit(`onDelayedLoadPageResources`, { pathname })
window.___history.push(location)
historyNavigateFunc(location)
}, 1000)

if (loader.getResourcesForPathname(pathname)) {
// The resources are already loaded so off we go.
clearTimeout(timeoutId)
window.___history.push(location)
historyNavigateFunc(location)
} else {
// They're not loaded yet so let's add a listener for when
// they finish loading.
Expand All @@ -103,7 +107,8 @@ apiRunnerAsync(`onClientEntry`).then(() => {
}

// window.___loadScriptsForPath = loadScriptsForPath
window.___navigateTo = navigateTo
window.___push = to => navigate(to, false)
window.___replace = to => navigate(to, true)

// Call onRouteUpdate on the initial page load.
apiRunner(`onRouteUpdate`, {
Expand Down
9 changes: 7 additions & 2 deletions packages/gatsby/src/cache-dir/root.js
Original file line number Diff line number Diff line change
Expand Up @@ -112,11 +112,16 @@ function shouldUpdateScroll(prevRouterProps, { location: { pathname } }) {
return true
}

const navigateTo = to => {
const push = to => {
window.___history.push(to)
}

window.___navigateTo = navigateTo
const replace = to => {
window.___history.replace(to)
}

window.___push = push
window.___replace = replace

const AltRouter = apiRunner(`replaceRouterComponent`, { history })[0]

Expand Down
6 changes: 3 additions & 3 deletions www/src/components/layout.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import Modal from "react-modal"
import Helmet from "react-helmet"
import MdClose from "react-icons/lib/md/close"

import { navigateTo, PageRenderer } from "gatsby"
import { push, PageRenderer } from "gatsby"

import presets, { colors } from "../utils/presets"
import Navigation from "../components/navigation"
Expand Down Expand Up @@ -32,7 +32,7 @@ class DefaultLayout extends React.Component {
}

handleCloseModal() {
navigateTo(this.props.modalBackgroundPath)
push(this.props.modalBackgroundPath)
}

componentDidMount() {
Expand Down Expand Up @@ -105,7 +105,7 @@ class DefaultLayout extends React.Component {
backgroundColor: `rgba(255, 255, 255, 0.95)`,
},
}}
onRequestClose={() => navigateTo(this.props.modalBackgroundPath)}
onRequestClose={() => push(this.props.modalBackgroundPath)}
contentLabel="Site Details Modal"
>
<div
Expand Down
4 changes: 2 additions & 2 deletions www/src/components/search-form.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React, { Component } from "react"
import PropTypes from "prop-types"
import { navigateTo } from "gatsby"
import { push } from "gatsby"
import { rhythm } from "../utils/typography"

import presets, { colors } from "../utils/presets"
Expand Down Expand Up @@ -253,7 +253,7 @@ class SearchForm extends Component {
const a = document.createElement(`a`)
a.href = e._args[0].url
this.searchInput.blur()
navigateTo(`${a.pathname}${a.hash}`)
push(`${a.pathname}${a.hash}`)
}

componentDidMount() {
Expand Down
6 changes: 3 additions & 3 deletions www/src/templates/template-showcase-details.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import hex2rgba from "hex2rgba"

import presets, { colors } from "../utils/presets"
import { options, scale, rhythm } from "../utils/typography"
import { navigateTo, Link } from "gatsby"
import { push, Link } from "gatsby"
import Layout from "../components/layout"
import ShareMenu from "../components/share-menu"

Expand Down Expand Up @@ -59,7 +59,7 @@ class ShowcaseTemplate extends React.Component {

const nextSite = this.getNext()

navigateTo({
push({
pathname: nextSite.fields.slug,
state: {
isModal: location.state.isModal,
Expand All @@ -82,7 +82,7 @@ class ShowcaseTemplate extends React.Component {
const { location } = this.props

const previousSite = this.getPrevious()
navigateTo({
push({
pathname: previousSite.fields.slug,
state: {
isModal: location.state.isModal,
Expand Down