Skip to content

Commit

Permalink
<BrowserRouter> ignores the history prop. #1913 (#1936)
Browse files Browse the repository at this point in the history
* <BrowserRouter> ignores the history prop. #1913

* Also change Router import in production-app.js
  • Loading branch information
3axap4eHko authored and KyleAMathews committed Aug 28, 2017
1 parent a6e75e2 commit 3ffe266
Show file tree
Hide file tree
Showing 9 changed files with 139 additions and 139 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ node_modules/
.netlify

# IDE specific
.idea/
.vscode/
yarn.lock
package-lock.json
2 changes: 1 addition & 1 deletion packages/gatsby-plugin-offline/src/gatsby-node.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ exports.onPostBuild = (args, pluginOptions) => {
// the `public` prefix with `pathPrefix`.
// See more at:
// https://github.com/GoogleChrome/sw-precache#replaceprefix-string
replacePrefix: args.pathPrefix || '',
replacePrefix: args.pathPrefix || ``,
navigateFallback: `/offline-plugin-app-shell-fallback/index.html`,
// Only match URLs without extensions.
// So example.com/about/ will pass but
Expand Down
232 changes: 113 additions & 119 deletions packages/gatsby/cache-dir/production-app.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,10 @@
if(__POLYFILL__) {
if (__POLYFILL__) {
require("core-js/modules/es6.promise")
}
import { apiRunner, apiRunnerAsync } from "./api-runner-browser"
import React, { createElement } from "react"
import ReactDOM from "react-dom"
import {
BrowserRouter as Router,
Route,
withRouter,
matchPath,
} from "react-router-dom"
import { Router, Route, withRouter, matchPath } from "react-router-dom"
import { ScrollContext } from "react-router-scroll"
import createHistory from "history/createBrowserHistory"
import domReady from "domready"
Expand All @@ -26,137 +21,136 @@ window.___loader = loader
window.matchPath = matchPath

// Let the site/plugins run code very early.
apiRunnerAsync(`onClientEntry`)
.then(() => {
// Let plugins register a service worker. The plugin just needs
// to return true.
if (apiRunner(`registerServiceWorker`).length > 0) {
require(`./register-service-worker`)
apiRunnerAsync(`onClientEntry`).then(() => {
// Let plugins register a service worker. The plugin just needs
// to return true.
if (apiRunner(`registerServiceWorker`).length > 0) {
require(`./register-service-worker`)
}

const navigateTo = pathname => {
// If we're already at this path, do nothing.
if (window.location.pathname === pathname) {
return
}

const navigateTo = pathname => {
// If we're already at this path, do nothing.
if (window.location.pathname === pathname) {
return
}

// 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(pathname)
}
}

// Start a timer to wait for a second before transitioning and showing a
// loader in case resources aren't around yet.
const timeoutId = setTimeout(() => {
// 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)
emitter.emit(`onDelayedLoadPageResources`, { pathname })
window.___history.push(pathname)
}, 1000)

if (loader.getResourcesForPathname(pathname)) {
// The resources are already loaded so off we go.
clearTimeout(timeoutId)
window.___history.push(pathname)
} else {
// They're not loaded yet so let's add a listener for when
// they finish loading.
emitter.on(`onPostLoadPageResources`, eventHandler)
}
}

// window.___loadScriptsForPath = loadScriptsForPath
window.___navigateTo = navigateTo
// Start a timer to wait for a second before transitioning and showing a
// loader in case resources aren't around yet.
const timeoutId = setTimeout(() => {
emitter.off(`onPostLoadPageResources`, eventHandler)
emitter.emit(`onDelayedLoadPageResources`, { pathname })
window.___history.push(pathname)
}, 1000)

if (loader.getResourcesForPathname(pathname)) {
// The resources are already loaded so off we go.
clearTimeout(timeoutId)
window.___history.push(pathname)
} else {
// They're not loaded yet so let's add a listener for when
// they finish loading.
emitter.on(`onPostLoadPageResources`, eventHandler)
}
}

const history = createHistory()
// window.___loadScriptsForPath = loadScriptsForPath
window.___navigateTo = navigateTo

// Call onRouteUpdate on the initial page load.
apiRunner(`onRouteUpdate`, {
location: history.location,
action: history.action,
})
const history = createHistory()

function attachToHistory(history) {
if (!window.___history) {
window.___history = history
// Call onRouteUpdate on the initial page load.
apiRunner(`onRouteUpdate`, {
location: history.location,
action: history.action,
})

history.listen((location, action) => {
apiRunner(`onRouteUpdate`, { location, action })
})
}
}
function attachToHistory(history) {
if (!window.___history) {
window.___history = history

function shouldUpdateScroll(prevRouterProps, { location: { pathname } }) {
const results = apiRunner(`shouldUpdateScroll`, {
prevRouterProps,
pathname,
history.listen((location, action) => {
apiRunner(`onRouteUpdate`, { location, action })
})
if (results.length > 0) {
return results[0]
}

if (prevRouterProps) {
const { location: { pathname: oldPathname } } = prevRouterProps
if (oldPathname === pathname) {
return false
}
}
return true
}
}

const AltRouter = apiRunner(`replaceRouterComponent`, { history })[0]
const DefaultRouter = ({ children }) =>
<Router history={history}>
{children}
</Router>
function shouldUpdateScroll(prevRouterProps, { location: { pathname } }) {
const results = apiRunner(`shouldUpdateScroll`, {
prevRouterProps,
pathname,
})
if (results.length > 0) {
return results[0]
}

loader.getResourcesForPathname(window.location.pathname, () => {
const Root = () =>
if (prevRouterProps) {
const { location: { pathname: oldPathname } } = prevRouterProps
if (oldPathname === pathname) {
return false
}
}
return true
}

const AltRouter = apiRunner(`replaceRouterComponent`, { history })[0]
const DefaultRouter = ({ children }) =>
<Router history={history}>
{children}
</Router>

loader.getResourcesForPathname(window.location.pathname, () => {
const Root = () =>
createElement(
AltRouter ? AltRouter : DefaultRouter,
null,
createElement(
AltRouter ? AltRouter : DefaultRouter,
null,
createElement(
ScrollContext,
{ shouldUpdateScroll },
createElement(withRouter(ComponentRenderer), {
layout: true,
children: layoutProps =>
createElement(Route, {
render: routeProps => {
attachToHistory(routeProps.history)
const props = layoutProps ? layoutProps : routeProps

if (loader.getPage(props.location.pathname)) {
return createElement(ComponentRenderer, {
page: true,
...props,
})
} else {
return createElement(ComponentRenderer, {
location: { page: true, pathname: `/404.html` },
})
}
},
}),
})
)
ScrollContext,
{ shouldUpdateScroll },
createElement(withRouter(ComponentRenderer), {
layout: true,
children: layoutProps =>
createElement(Route, {
render: routeProps => {
attachToHistory(routeProps.history)
const props = layoutProps ? layoutProps : routeProps

if (loader.getPage(props.location.pathname)) {
return createElement(ComponentRenderer, {
page: true,
...props,
})
} else {
return createElement(ComponentRenderer, {
location: { page: true, pathname: `/404.html` },
})
}
},
}),
})
)
)

const NewRoot = apiRunner(`wrapRootComponent`, { Root }, Root)[0]
domReady(() =>
ReactDOM.render(
<NewRoot />,
typeof window !== `undefined`
? document.getElementById(`___gatsby`)
: void 0,
() => {
apiRunner(`onInitialClientRender`)
}
)
const NewRoot = apiRunner(`wrapRootComponent`, { Root }, Root)[0]
domReady(() =>
ReactDOM.render(
<NewRoot />,
typeof window !== `undefined`
? document.getElementById(`___gatsby`)
: void 0,
() => {
apiRunner(`onInitialClientRender`)
}
)
})
)
})
})
2 changes: 1 addition & 1 deletion packages/gatsby/cache-dir/root.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React, { createElement } from "react"
import {
BrowserRouter as Router,
Router,
Route,
matchPath,
withRouter,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -181,12 +181,12 @@ function printHandles(field: Field): string {
const printed = field.handles.map(handle => {
// For backward compatibility and also because this module is
// shared by ComponentScript.
const key =
handle.key === DEFAULT_HANDLE_KEY ? `` : `, key: "${handle.key}"`
const filters =
handle.filters == null
? ``
: `, filters: ${JSON.stringify(handle.filters.sort())}`
const key = handle.key === DEFAULT_HANDLE_KEY
? ``
: `, key: "${handle.key}"`
const filters = handle.filters == null
? ``
: `, filters: ${JSON.stringify(handle.filters.sort())}`
return `@__clientField(handle: "${handle.name}"${key}${filters})`
})
return printed.length ? ` ` + printed.join(` `) : ``
Expand Down
6 changes: 4 additions & 2 deletions packages/gatsby/src/redux/reducers/layouts.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,10 @@ module.exports = (state = [], action) => {
console.log(``)
console.error(JSON.stringify(action, null, 4))
console.log(``)
throw new Error(`Pages can only be created by plugins. There wasn't a plugin set
when creating this page.`)
throw new Error(
`Pages can only be created by plugins. There wasn't a plugin set
when creating this page.`
)
}
action.payload.pluginCreator___NODE = `Plugin ${action.plugin.name}`
const index = _.findIndex(state, l => l.id === action.payload.id)
Expand Down
6 changes: 4 additions & 2 deletions packages/gatsby/src/redux/reducers/pages.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,10 @@ module.exports = (state = [], action) => {
console.log(``)
console.error(JSON.stringify(action, null, 4))
console.log(``)
throw new Error(`Pages can only be created by plugins. There wasn't a plugin set
when creating this page.`)
throw new Error(
`Pages can only be created by plugins. There wasn't a plugin set
when creating this page.`
)
}
// Link page to its plugin.
action.payload.pluginCreator___NODE = action.plugin.id
Expand Down
12 changes: 6 additions & 6 deletions packages/gatsby/src/utils/develop.js
Original file line number Diff line number Diff line change
Expand Up @@ -169,10 +169,9 @@ async function startServer(program) {
}

if (program.open) {
const host =
listener.address().address === `127.0.0.1`
? `localhost`
: listener.address().address
const host = listener.address().address === `127.0.0.1`
? `localhost`
: listener.address().address
require(`opn`)(`http://${host}:${listener.address().port}`)
}
})
Expand All @@ -187,8 +186,9 @@ async function startServer(program) {

module.exports = (program: any) => {
const detect = require(`detect-port`)
const port =
typeof program.port === `string` ? parseInt(program.port, 10) : program.port
const port = typeof program.port === `string`
? parseInt(program.port, 10)
: program.port

detect(port, (err, _port) => {
if (err) {
Expand Down
5 changes: 3 additions & 2 deletions packages/gatsby/src/utils/serve.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,9 @@ function startServer(program, launchPort) {
}

module.exports = program => {
const port =
typeof program.port === `string` ? parseInt(program.port, 10) : program.port
const port = typeof program.port === `string`
? parseInt(program.port, 10)
: program.port

detect(port, (err, _port) => {
if (err) {
Expand Down

0 comments on commit 3ffe266

Please sign in to comment.