Skip to content
This repository was archived by the owner on Oct 26, 2018. It is now read-only.

Uses es6 import/exports #86

Closed
wants to merge 1 commit into from
Closed
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
8 changes: 5 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,22 +72,24 @@ it, and also change it with an action.
Here's some code:

```js
import React from 'react'
import ReactDOM from 'react-dom'
import { createStore, combineReducers } from 'redux'
import { Provider } from 'react-redux'
import { Router, Route } from 'react-router'
import createBrowserHistory from 'history/lib/createBrowserHistory'
import { createHistory } from 'history'
import { syncReduxAndRouter, routeReducer } from 'redux-simple-router'
import reducers from '<project-path>/reducers'

const reducer = combineReducers(Object.assign({}, reducers, {
routing: routeReducer
}))
const store = createStore(reducer)
const history = createBrowserHistory()
const history = createHistory()

syncReduxAndRouter(history, store)

React.render(
ReactDOM.render(
<Provider store={store}>
<Router history={history}>
<Route path="/" component={App}>
Expand Down
28 changes: 19 additions & 9 deletions examples/basic/app.js
Original file line number Diff line number Diff line change
@@ -1,31 +1,41 @@
const React = require('react');
const ReactDOM = require('react-dom');
const { createStore, combineReducers } = require('redux');
const { compose, createStore, combineReducers } = require('redux');
const { Provider } = require('react-redux');
const { Router, Route, IndexRoute } = require('react-router');
const createHistory = require('history/lib/createHashHistory');
const { syncReduxAndRouter, routeReducer } = require('redux-simple-router');
import { devTools } from 'redux-devtools';
const { DevTools, DebugPanel, LogMonitor } = require('redux-devtools/lib/react');

const reducers = require('./reducers');
const { App, Home, Foo, Bar } = require('./components');

const reducer = combineReducers(Object.assign({}, reducers, {
routing: routeReducer
}));
const store = createStore(reducer);
const finalCreateStore = compose(
devTools()
)(createStore);
const store = finalCreateStore(reducer);
const history = createHistory();

syncReduxAndRouter(history, store);

ReactDOM.render(
<Provider store={store}>
<Router history={history}>
<Route path="/" component={App}>
<IndexRoute component={Home}/>
<Route path="foo" component={Foo}/>
<Route path="bar" component={Bar}/>
</Route>
</Router>
<div>
<Router history={history}>
<Route path="/" component={App}>
<IndexRoute component={Home}/>
<Route path="foo" component={Foo}/>
<Route path="bar" component={Bar}/>
</Route>
</Router>
<DebugPanel top right bottom>
<DevTools store={store} monitor={LogMonitor} />
</DebugPanel>
</div>
</Provider>,
document.getElementById('mount')
);
8 changes: 4 additions & 4 deletions examples/basic/components/App.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
const React = require('react');
const { Link } = require('react-router');
const { connect } = require('react-redux');
const { updatePath } = require('redux-simple-router');
const { pushPath } = require('redux-simple-router');

function App({ updatePath, children }) {
function App({ pushPath, children }) {
return (
<div>
<header>
Expand All @@ -16,7 +16,7 @@ function App({ updatePath, children }) {
<Link to="/bar">Bar</Link>
</header>
<div>
<button onClick={() => updatePath('/foo')}>Go to /foo</button>
<button onClick={() => pushPath('/foo')}>Go to /foo</button>
</div>
<div style={{marginTop: '1.5em'}}>{children}</div>
</div>
Expand All @@ -25,5 +25,5 @@ function App({ updatePath, children }) {

module.exports = connect(
null,
{ updatePath }
{ pushPath }
)(App);
4 changes: 4 additions & 0 deletions examples/basic/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@
"babel-loader": "^6.2.0",
"babel-preset-es2015": "^6.1.18",
"babel-preset-react": "^6.1.18",
"redux-devtools": "^2.1.5",
"webpack": "^1.12.6"
},
"scripts": {
"start": "webpack --watch"
}
}
5 changes: 5 additions & 0 deletions examples/basic/webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,9 @@ var fs = require('fs')
if (fs.existsSync(src)) {
// Use the latest src
module.exports.resolve = { alias: { 'redux-simple-router': src } }
module.exports.module.loaders.push({
test: /\.js$/,
loaders: ['babel'],
include: src
});
}
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"version": "0.0.10",
"description": "Ruthlessly simple bindings to keep react-router and redux in sync",
"main": "lib/index",
"jsnext:main": "src/index",
"repository": {
"type": "git",
"url": "https://github.com/jlongster/redux-simple-router.git"
Expand Down Expand Up @@ -53,6 +54,7 @@
"karma-webpack": "^1.7.0",
"mocha": "^2.3.4",
"redux": "^3.0.4",
"redux-devtools": "^2.1.5",
"webpack": "^1.12.9"
},
"dependencies": {
Expand Down
105 changes: 70 additions & 35 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,26 @@
const deepEqual = require('deep-equal');
import deepEqual from 'deep-equal';

// Constants

const UPDATE_PATH = "@@router/UPDATE_PATH";
const INIT_PATH = "@@router/INIT_PATH";
export const UPDATE_PATH = "@@router/UPDATE_PATH";
const SELECT_STATE = state => state.routing;

// Action creator
// Action creators

function pushPath(path, state, { avoidRouterUpdate = false } = {}) {
function initPath(path, state) {
return {
type: INIT_PATH,
payload: {
path: path,
state: state,
replace: false,
avoidRouterUpdate: true
}
};
}

export function pushPath(path, state, { avoidRouterUpdate = false } = {}) {
return {
type: UPDATE_PATH,
payload: {
Expand All @@ -19,7 +32,7 @@ function pushPath(path, state, { avoidRouterUpdate = false } = {}) {
};
}

function replacePath(path, state, { avoidRouterUpdate = false } = {}) {
export function replacePath(path, state, { avoidRouterUpdate = false } = {}) {
return {
type: UPDATE_PATH,
payload: {
Expand All @@ -33,15 +46,15 @@ function replacePath(path, state, { avoidRouterUpdate = false } = {}) {

// Reducer

const initialState = {
let initialState = {
changeId: 1,
path: undefined,
state: undefined,
replace: false
};

function update(state=initialState, { type, payload }) {
if(type === UPDATE_PATH) {
if(type === INIT_PATH || type === UPDATE_PATH) {
return Object.assign({}, state, {
path: payload.path,
changeId: state.changeId + (payload.avoidRouterUpdate ? 0 : 1),
Expand All @@ -55,12 +68,20 @@ function update(state=initialState, { type, payload }) {
// Syncing

function locationsAreEqual(a, b) {
return a.path === b.path && deepEqual(a.state, b.state);
return a != null && b != null && a.path === b.path && deepEqual(a.state, b.state);
}

function syncReduxAndRouter(history, store, selectRouterState = SELECT_STATE) {
export function syncReduxAndRouter(history, store, selectRouterState = SELECT_STATE) {
const getRouterState = () => selectRouterState(store.getState());
let lastChangeId = 0;

// To properly handle store updates we need to track the last route.
// This route contains a `changeId` which is updated on every
// `pushPath` and `replacePath`. If this id changes we always
// trigger a history update. However, if the id does not change, we
// check if the location has changed, and if it is we trigger a
// history update. It's possible for this to happen when something
// reloads the entire app state such as redux devtools.
let lastRoute = undefined;

if(!getRouterState()) {
throw new Error(
Expand All @@ -75,30 +96,50 @@ function syncReduxAndRouter(history, store, selectRouterState = SELECT_STATE) {
state: location.state
};

// Avoid dispatching an action if the store is already up-to-date,
// even if `history` wouldn't do anything if the location is the same
if(locationsAreEqual(getRouterState(), route)) return;

const updatePath = location.action === 'REPLACE'
? replacePath
: pushPath;

store.dispatch(updatePath(route.path, route.state, { avoidRouterUpdate: true }));
if (!lastRoute) {
// `initialState` *should* represent the current location when
// the app loads, but we cannot get the current location when it
// is defined. What happens is `history.listen` is called
// immediately when it is registered, and it updates the app
// state with an UPDATE_PATH action. This causes problem when
// users are listening to UPDATE_PATH actions just for
// *changes*, and with redux devtools because "revert" will use
// `initialState` and it won't revert to the original URL.
// Instead, we specialize the first route notification and do
// different things based on it.
initialState = {
changeId: 1,
path: route.path,
state: route.state,
replace: false
};

// Also set `lastRoute` so that the store subscriber doesn't
// trigger an unnecessary `pushState` on load
lastRoute = initialState;

store.dispatch(initPath(route.path, route.state));
} else if(!locationsAreEqual(getRouterState(), route)) {
// The above check avoids dispatching an action if the store is
// already up-to-date
const method = location.action === 'REPLACE' ? replacePath : pushPath;
store.dispatch(method(route.path, route.state, { avoidRouterUpdate: true }));
}
});

const unsubscribeStore = store.subscribe(() => {
const routing = getRouterState();

// Only update the router once per `pushPath` call. This is
// indicated by the `changeId` state; when that number changes, we
// should update the history.
if(lastChangeId === routing.changeId) return;
let routing = getRouterState();

lastChangeId = routing.changeId;
// Only trigger history update if this is a new change or the
// location has changed.
if(lastRoute.changeId !== routing.changeId ||
!locationsAreEqual(lastRoute, routing)) {

const method = routing.replace ? 'replaceState' : 'pushState';
lastRoute = routing;
const method = routing.replace ? 'replaceState' : 'pushState';
history[method](routing.state, routing.path);
}

history[method](routing.state, routing.path);
});

return function unsubscribe() {
Expand All @@ -107,10 +148,4 @@ function syncReduxAndRouter(history, store, selectRouterState = SELECT_STATE) {
};
}

module.exports = {
UPDATE_PATH,
pushPath,
replacePath,
syncReduxAndRouter,
routeReducer: update
};
export { update as routeReducer };
Loading