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

[1.0] Upgrade React Router to v4 #940

Merged
merged 18 commits into from
May 11, 2017
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
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
60 changes: 30 additions & 30 deletions packages/gatsby-link/src/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React from "react"
import Link from "react-router/lib/Link"
import { Link } from "react-router-dom"
import createClass from "create-react-class"
import PropTypes from "prop-types"

Expand All @@ -15,38 +15,38 @@ const GatsbyLink = createClass({
propTypes: {
to: PropTypes.string.isRequired,
},
componentDidMount() {
// Only enable prefetching of Link resources in production and for browsers
// that don't support service workers *cough* Safari/IE *cough*.
if (
(process.env.NODE_ENV === `production` &&
!(`serviceWorker` in navigator)) ||
window.location.protocol !== `https:`
) {
const routes = window.gatsbyRootRoute
const { createMemoryHistory } = require(`history`)
const matchRoutes = require(`react-router/lib/matchRoutes`)
const getComponents = require(`react-router/lib/getComponents`)
// componentDidMount() {
// // Only enable prefetching of Link resources in production and for browsers
// // that don't support service workers *cough* Safari/IE *cough*.
// if (
// (process.env.NODE_ENV === `production` &&
// !(`serviceWorker` in navigator)) ||
// window.location.protocol !== `https:`
// ) {
// const routes = window.gatsbyRootRoute
// const { createMemoryHistory } = require(`history`)
// const matchRoutes = require(`react-router/lib/matchRoutes`)
// const getComponents = require(`react-router/lib/getComponents`)

const createLocation = createMemoryHistory().createLocation
// const createLocation = createMemoryHistory().createLocation

if (typeof routes !== `undefined`) {
matchRoutes(
[routes],
createLocation(this.props.to),
(error, nextState) => {
if (error) {
return console.error(error)
}
// if (typeof routes !== `undefined`) {
// matchRoutes(
// [routes],
// createLocation(this.props.to),
// (error, nextState) => {
// if (error) {
// return console.error(error)
// }

if (nextState) {
getComponents(nextState)
}
}
)
}
}
},
// if (nextState) {
// getComponents(nextState)
// }
// }
// )
// }
// }
// },
render() {
const to = linkPrefix + this.props.to
return <Link {...this.props} to={to} />
Expand Down
66 changes: 50 additions & 16 deletions packages/gatsby/lib/cache-dir/root.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,22 @@
import React from "react"
import { applyRouterMiddleware, Router, browserHistory } from "react-router"
import useScroll from "react-router-scroll/lib/useScroll"
import { BrowserRouter as Router, Route } from "react-router-dom"
import createHistory from "history/createBrowserHistory"

const apiRunner = require(`./api-runner-browser`)
const rootRoute = require(`./child-routes`)
console.log(rootRoute)
import apiRunner from "./api-runner-browser"
// import rootRoute from "./child-routes"
import syncRequires from "./sync-requires"
import routes from "./routes.json"

console.log(syncRequires)
console.log(routes)

let currentLocation

browserHistory.listen(location => {
currentLocation = location
const history = createHistory()
history.listen((location, action) => {
console.log("action", action)
apiRunner(`onRouteUpdate`, location, action)
})

function shouldUpdateScroll(prevRouterProps, { location: { pathname } }) {
Expand All @@ -30,16 +37,43 @@ function shouldUpdateScroll(prevRouterProps, { location: { pathname } }) {
return true
}

const Root = () => (
<Router
history={browserHistory}
routes={rootRoute}
render={applyRouterMiddleware(useScroll(shouldUpdateScroll))}
onUpdate={() => {
apiRunner(`onRouteUpdate`, currentLocation)
}}
/>
)
const DefaultLayout = () => {
return React.createElement(syncRequires.layouts["index"])
}

// TODO assemble component hierarchy on the fly. wrapper > ...layouts w/ data > page w/ data

const Root = () =>
React.createElement(
Router,
null,
React.createElement(Route, {
component: location =>
React.createElement(syncRequires.layouts["index"], { ...location }, [
...Object.keys(routes).map(path => {
const route = routes[path]
return React.createElement(Route, {
exact: true,
path,
component: props =>
React.createElement(
syncRequires.components[route.componentChunkName],
{
...props,
...syncRequires.json[route.jsonName],
}
),
})
}),
]),
})
)
// history={browserHistory}
// routes={rootRoute}
// render={applyRouterMiddleware(useScroll(shouldUpdateScroll))}
// onUpdate={() => {
// }}
// />

// Let site, plugins wrap the site e.g. for Redux.
const WrappedRoot = apiRunner(`wrapRootComponent`, { Root }, Root)[0]
Expand Down
94 changes: 88 additions & 6 deletions packages/gatsby/lib/query-runner/route-writer.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,87 @@ import {
// Loop through all paths and write them out to child-routes.js
const writeChildRoutes = () => {
const { program, config, pages } = store.getState()

// console.log(pages)
// Write out routes.json
const routesData = _.merge(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Refactor proposition:

const routesData = pages.reduce((mem, {path, componentChunkName, layout, jsonName}) => (
      { ...mem, ...{[path]: {componentChunkName, layout, jsonName}} }
    ), {})

https://codepen.io/fabien0102/pen/MmrqKe?editors=0011#

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I like it! I'll make that change. Object/array spreading makes reducing quite nice!

..._.values(
pages.map(p => {
const object = {}
object[p.path] = _.pick(p, [`componentChunkName`, `layout`, `jsonName`])
return object
})
)
)

// Get list of components, layouts, and json files.
let components = []
let layouts = []
let json = []

pages.forEach(p => {
components.push({
componentChunkName: p.componentChunkName,
component: p.component,
})
if (p.layout) {
layouts.push(p.layout)
}
json.push(p.jsonName)
})

// Add the default layout if it exists.
let defaultLayoutExists = false
console.log(`${program.directory}/src/layouts/index.*`)
console.log(glob.sync(`${program.directory}/src/layouts/index.*`))
if (glob.sync(`${program.directory}/src/layouts/index.*`).length !== 0) {
layouts.push(`index`)
defaultLayoutExists = true
}
console.log(layouts)

layouts = _.uniq(layouts)
components = _.uniqBy(components, c => c.componentChunkName)

console.log(components, layouts, json)

fs.writeFile(
`${program.directory}/.cache/routes.json`,
JSON.stringify(routesData, null, 4)
)

// Create file with sync requires of layouts/components/json files.
let syncRequires = `// prefer default export if available
const preferDefault = m => m && m.default || m
\n\n`
syncRequires += `exports.components = {\n${components
.map(
c =>
` "${c.componentChunkName}": preferDefault(require("${c.component}"))`
)
.join(`,\n`)}
}\n\n`
syncRequires += `exports.json = {\n${json
.map(j => ` "${j}": require("${program.directory + "/.cache/json/" + j}")`)
.join(`,\n`)}
}\n\n`
syncRequires += `exports.layouts = {\n${layouts
.map(l => {
console.log("layout", l)
let componentName = l
if (l !== false || typeof l !== `undefined`) {
componentName = `index`
return ` "${l}": preferDefault(require("${program.directory + `/src/layouts/` + componentName}"))`
} else {
return ` "${l}": false`
}
})
.join(`,\n`)}
}`

console.log(syncRequires)
fs.writeFile(`${program.directory}/.cache/sync-requires.js`, syncRequires)

let childRoutes = ``
let splitChildRoutes = ``

Expand Down Expand Up @@ -56,20 +137,21 @@ const writeChildRoutes = () => {
}

// Group pages under their layout component (if any).
let defaultLayoutExists = true
if (glob.sync(`${program.directory}/src/layouts/default.*`).length === 0) {
// let defaultLayoutExists = true
if (glob.sync(`${program.directory}/src/layouts/index.*`).length === 0) {
defaultLayoutExists = false
}
const groupedPages = _.groupBy(pages, page => {
// If is a string we'll assume it's a working layout component.
if (_.isString(page.layout)) {
console.log(page)
return page.layout
// If the user explicitely turns off layout, put page in undefined bucket.
} else if (page.layout === false) {
return `undefined`
// Otherwise assume the default layout should handle this page.
} else if (defaultLayoutExists) {
return `default`
return `index`
// We got nothing left, undefined.
} else {
return `undefined`
Expand Down Expand Up @@ -139,7 +221,7 @@ const writeChildRoutes = () => {
const notFoundPage = pages.find(page => page.path.indexOf(`/404`) !== -1)

if (notFoundPage) {
const defaultLayout = `preferDefault(require('${program.directory}/src/layouts/default'))`
const defaultLayout = `preferDefault(require('${program.directory}/src/layouts/index'))`
const notFoundPageStr = `
{
path: "*",
Expand Down Expand Up @@ -227,8 +309,8 @@ const writeChildRoutes = () => {
const preferDefault = m => m && m.default || m
const rootRoute = ${splitRootRoute}
module.exports = rootRoute`
fs.writeFileSync(`${program.directory}/.cache/child-routes.js`, childRoutes)
fs.writeFileSync(
fs.writeFile(`${program.directory}/.cache/child-routes.js`, childRoutes)
fs.writeFile(
`${program.directory}/.cache/split-child-routes.js`,
splitChildRoutes
)
Expand Down
7 changes: 4 additions & 3 deletions packages/gatsby/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@
"gray-matter": "^2.1.0",
"hapi": "^8.5.1",
"highlight.js": "^9.8.0",
"history": "^2.1.2",
"history": "^4.6.1",
"hosted-git-info": "^2.4.2",
"invariant": "^2.2.2",
"is-relative": "^0.2.1",
Expand Down Expand Up @@ -91,8 +91,9 @@
"react-document-title": "^2.0.1",
"react-dom": "^15.4.0",
"react-hot-loader": "^3.0.0-beta.6",
"react-router": "^2.8.1",
"react-router-scroll": "^0.3.3",
"react-router": "^4.1.1",
"react-router-dom": "^4.1.1",
"react-router-scroll": "https://github.com/ytase/react-router-scroll",
"redux": "^3.6.0",
"relay-compiler": "^1.0.0-rc.3",
"remote-redux-devtools": "^0.5.7",
Expand Down
1 change: 1 addition & 0 deletions www/src/layouts/default.js → www/src/layouts/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ module.exports = React.createClass({
}
},
render() {
console.log(this.props)
return (
<div>
<Helmet
Expand Down
2 changes: 1 addition & 1 deletion www/src/pages/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React from "react"
import Link from "react-router/lib/Link"
import Link from "gatsby-link"

const IndexRoute = React.createClass({
render() {
Expand Down