Normalize actions in lifted state as per #134

This commit is contained in:
Dan Abramov 2015-10-17 03:53:43 +03:00
parent 1540777302
commit 4249b3a991
5 changed files with 102 additions and 76 deletions

View File

@ -16,9 +16,9 @@
}, },
"homepage": "https://github.com/gaearon/redux-devtools#readme", "homepage": "https://github.com/gaearon/redux-devtools#readme",
"dependencies": { "dependencies": {
"react": "^0.14.0-rc1", "react": "^0.14.0",
"react-dom": "^0.14.0-rc1", "react-dom": "^0.14.0",
"react-redux": "^3.0.0", "react-redux": "^4.0.0",
"redux": "^3.0.0", "redux": "^3.0.0",
"redux-thunk": "^1.0.0" "redux-thunk": "^1.0.0"
}, },
@ -27,8 +27,8 @@
"babel-loader": "^5.1.4", "babel-loader": "^5.1.4",
"node-libs-browser": "^0.5.2", "node-libs-browser": "^0.5.2",
"react-hot-loader": "^1.3.0", "react-hot-loader": "^1.3.0",
"redux-devtools": "^3.0.0-beta-1", "redux-devtools": "^3.0.0-beta-2",
"redux-devtools-log-monitor": "^1.0.0-beta-1", "redux-devtools-log-monitor": "^1.0.0-beta-2",
"redux-devtools-dock-monitor": "^1.0.0-beta-1", "redux-devtools-dock-monitor": "^1.0.0-beta-1",
"webpack": "^1.9.11", "webpack": "^1.9.11",
"webpack-dev-server": "^1.9.0" "webpack-dev-server": "^1.9.0"

View File

@ -1,6 +1,6 @@
{ {
"name": "redux-devtools", "name": "redux-devtools",
"version": "3.0.0-beta-1", "version": "3.0.0-beta-2",
"description": "Redux DevTools with hot reloading and time travel", "description": "Redux DevTools with hot reloading and time travel",
"main": "lib/index.js", "main": "lib/index.js",
"scripts": { "scripts": {
@ -54,6 +54,7 @@
"react": "^0.14.0" "react": "^0.14.0"
}, },
"dependencies": { "dependencies": {
"lodash": "^3.10.1",
"react-redux": "^4.0.0", "react-redux": "^4.0.0",
"redux": "^3.0.0" "redux": "^3.0.0"
} }

View File

@ -1,3 +1,5 @@
import difference from 'lodash/array/difference';
export const ActionTypes = { export const ActionTypes = {
PERFORM_ACTION: 'PERFORM_ACTION', PERFORM_ACTION: 'PERFORM_ACTION',
RESET: 'RESET', RESET: 'RESET',
@ -33,8 +35,8 @@ export const ActionCreators = {
return { type: ActionTypes.SWEEP }; return { type: ActionTypes.SWEEP };
}, },
toggleAction(index) { toggleAction(id) {
return { type: ActionTypes.TOGGLE_ACTION, index }; return { type: ActionTypes.TOGGLE_ACTION, id };
}, },
jumpToState(index) { jumpToState(index) {
@ -48,16 +50,6 @@ export const ActionCreators = {
const INIT_ACTION = { type: '@@INIT' }; const INIT_ACTION = { type: '@@INIT' };
function toggle(obj, key) {
const clone = { ...obj };
if (clone[key]) {
delete clone[key];
} else {
clone[key] = true;
}
return clone;
}
/** /**
* Computes the next entry in the log by applying an action. * Computes the next entry in the log by applying an action.
*/ */
@ -87,17 +79,17 @@ function computeNextEntry(reducer, action, state, error) {
/** /**
* Runs the reducer on all actions to get a fresh computation log. * Runs the reducer on all actions to get a fresh computation log.
*/ */
function recomputeStates(reducer, committedState, stagedActions, skippedActions) { function recomputeStates(reducer, committedState, actionsById, stagedActionIds, skippedActionIds) {
const computedStates = []; const computedStates = [];
for (let i = 0; i < stagedActionIds.length; i++) {
for (let i = 0; i < stagedActions.length; i++) { const actionId = stagedActionIds[i];
const action = stagedActions[i]; const action = actionsById[actionId].action;
const previousEntry = computedStates[i - 1]; const previousEntry = computedStates[i - 1];
const previousState = previousEntry ? previousEntry.state : committedState; const previousState = previousEntry ? previousEntry.state : committedState;
const previousError = previousEntry ? previousEntry.error : undefined; const previousError = previousEntry ? previousEntry.error : undefined;
const shouldSkip = Boolean(skippedActions[i]); const shouldSkip = skippedActionIds.indexOf(actionId) > -1;
const entry = shouldSkip ? const entry = shouldSkip ?
previousEntry : previousEntry :
computeNextEntry(reducer, action, previousState, previousError); computeNextEntry(reducer, action, previousState, previousError);
@ -108,17 +100,28 @@ function recomputeStates(reducer, committedState, stagedActions, skippedActions)
return computedStates; return computedStates;
} }
/**
* Lifts an app's action into an action on the lifted store.
*/
function liftAction(action) {
return ActionCreators.performAction(action);
}
/** /**
* Creates a history state reducer from an app's reducer. * Creates a history state reducer from an app's reducer.
*/ */
function liftReducerWith(reducer, initialCommittedState, monitorReducer) { function liftReducerWith(reducer, initialCommittedState, monitorReducer) {
const initialLiftedState = { const initialLiftedState = {
monitorState: monitorReducer(undefined, {}),
nextActionId: 1,
actionsById: {
0: liftAction(INIT_ACTION)
},
stagedActionIds: [0],
skippedActionIds: [],
committedState: initialCommittedState, committedState: initialCommittedState,
stagedActions: [INIT_ACTION],
skippedActions: {},
currentStateIndex: 0, currentStateIndex: 0,
timestamps: [Date.now()], computedStates: undefined
monitorState: monitorReducer(undefined, {})
}; };
/** /**
@ -128,37 +131,58 @@ function liftReducerWith(reducer, initialCommittedState, monitorReducer) {
let shouldRecomputeStates = true; let shouldRecomputeStates = true;
let { let {
monitorState, monitorState,
actionsById,
nextActionId,
stagedActionIds,
skippedActionIds,
committedState, committedState,
stagedActions,
skippedActions,
computedStates,
currentStateIndex, currentStateIndex,
timestamps computedStates
} = liftedState; } = liftedState;
switch (liftedAction.type) { switch (liftedAction.type) {
case ActionTypes.RESET: case ActionTypes.RESET:
actionsById = {
0: liftAction(INIT_ACTION)
};
nextActionId = 1;
stagedActionIds = [0];
skippedActionIds = [];
committedState = initialCommittedState; committedState = initialCommittedState;
stagedActions = [INIT_ACTION];
skippedActions = {};
currentStateIndex = 0; currentStateIndex = 0;
timestamps = [liftedAction.timestamp];
break; break;
case ActionTypes.COMMIT: case ActionTypes.COMMIT:
actionsById = {
0: liftAction(INIT_ACTION)
};
nextActionId = 1;
stagedActionIds = [0];
skippedActionIds = [];
committedState = computedStates[currentStateIndex].state; committedState = computedStates[currentStateIndex].state;
stagedActions = [INIT_ACTION];
skippedActions = {};
currentStateIndex = 0; currentStateIndex = 0;
timestamps = [liftedAction.timestamp];
break; break;
case ActionTypes.ROLLBACK: case ActionTypes.ROLLBACK:
stagedActions = [INIT_ACTION]; actionsById = {
skippedActions = {}; 0: liftAction(INIT_ACTION)
};
nextActionId = 1;
stagedActionIds = [0];
skippedActionIds = [];
currentStateIndex = 0; currentStateIndex = 0;
timestamps = [liftedAction.timestamp];
break; break;
case ActionTypes.TOGGLE_ACTION: case ActionTypes.TOGGLE_ACTION:
skippedActions = toggle(skippedActions, liftedAction.index); const index = skippedActionIds.indexOf(liftedAction.id);
if (index === -1) {
skippedActionIds = [
liftedAction.id,
...skippedActionIds
];
} else {
skippedActionIds = [
...skippedActionIds.slice(0, index),
...skippedActionIds.slice(index + 1)
];
}
break; break;
case ActionTypes.JUMP_TO_STATE: case ActionTypes.JUMP_TO_STATE:
currentStateIndex = liftedAction.index; currentStateIndex = liftedAction.index;
@ -166,19 +190,20 @@ function liftReducerWith(reducer, initialCommittedState, monitorReducer) {
shouldRecomputeStates = false; shouldRecomputeStates = false;
break; break;
case ActionTypes.SWEEP: case ActionTypes.SWEEP:
stagedActions = stagedActions.filter((_, i) => !skippedActions[i]); stagedActionIds = difference(stagedActionIds, skippedActionIds);
timestamps = timestamps.filter((_, i) => !skippedActions[i]); skippedActionIds = [];
skippedActions = {}; currentStateIndex = Math.min(currentStateIndex, stagedActionIds.length - 1);
currentStateIndex = Math.min(currentStateIndex, stagedActions.length - 1);
break; break;
case ActionTypes.PERFORM_ACTION: case ActionTypes.PERFORM_ACTION:
if (currentStateIndex === stagedActions.length - 1) { if (currentStateIndex === stagedActionIds.length - 1) {
currentStateIndex++; currentStateIndex++;
} }
stagedActions = [...stagedActions, liftedAction.action]; const actionId = nextActionId++;
timestamps = [...timestamps, liftedAction.timestamp]; // Mutation! This is the hottest path, and we optimize on purpose.
// It is safe because we set a new key in a cache dictionary.
actionsById[actionId] = liftedAction;
stagedActionIds = [...stagedActionIds, actionId];
// Optimization: we know that the past has not changed. // Optimization: we know that the past has not changed.
shouldRecomputeStates = false; shouldRecomputeStates = false;
// Instead of recomputing the states, append the next one. // Instead of recomputing the states, append the next one.
@ -193,12 +218,14 @@ function liftReducerWith(reducer, initialCommittedState, monitorReducer) {
break; break;
case ActionTypes.IMPORT_STATE: case ActionTypes.IMPORT_STATE:
({ ({
stagedActions, monitorState,
skippedActions, actionsById,
computedStates, nextActionId,
stagedActionIds,
skippedActionIds,
committedState,
currentStateIndex, currentStateIndex,
timestamps, computedStates
monitorState
} = liftedAction.nextLiftedState); } = liftedAction.nextLiftedState);
break; break;
case '@@redux/INIT': case '@@redux/INIT':
@ -215,21 +242,23 @@ function liftReducerWith(reducer, initialCommittedState, monitorReducer) {
computedStates = recomputeStates( computedStates = recomputeStates(
reducer, reducer,
committedState, committedState,
stagedActions, actionsById,
skippedActions stagedActionIds,
skippedActionIds
); );
} }
monitorState = monitorReducer(monitorState, liftedAction); monitorState = monitorReducer(monitorState, liftedAction);
return { return {
monitorState,
actionsById,
nextActionId,
stagedActionIds,
skippedActionIds,
committedState, committedState,
stagedActions,
skippedActions,
computedStates,
currentStateIndex, currentStateIndex,
timestamps, computedStates
monitorState
}; };
}; };
} }
@ -243,13 +272,6 @@ function unliftState(liftedState) {
return state; return state;
} }
/**
* Lifts an app's action into an action on the lifted store.
*/
function liftAction(action) {
return ActionCreators.performAction(action);
}
/** /**
* Provides an app's view into the lifted store. * Provides an app's view into the lifted store.
*/ */

View File

@ -1,4 +1,6 @@
const identity = _ => _; import mapValues from 'lodash/object/mapValues';
import identity from 'lodash/utility/identity';
export default function persistState(sessionId, deserializeState = identity, deserializeAction = identity) { export default function persistState(sessionId, deserializeState = identity, deserializeAction = identity) {
if (!sessionId) { if (!sessionId) {
return next => (...args) => next(...args); return next => (...args) => next(...args);
@ -7,7 +9,10 @@ export default function persistState(sessionId, deserializeState = identity, des
function deserialize(state) { function deserialize(state) {
return { return {
...state, ...state,
stagedActions: state.stagedActions.map(deserializeAction), actionsById: mapValues(state.actionsById, liftedAction => ({
...liftedAction,
action: deserializeAction(liftedAction.action)
})),
committedState: deserializeState(state.committedState), committedState: deserializeState(state.committedState),
computedStates: state.computedStates.map(computedState => ({ computedStates: state.computedStates.map(computedState => ({
...computedState, ...computedState,

View File

@ -87,7 +87,7 @@ describe('instrument', () => {
}); });
it('should toggle an action', () => { it('should toggle an action', () => {
// stateIndex 0 = @@INIT // actionId 0 = @@INIT
store.dispatch({ type: 'INCREMENT' }); store.dispatch({ type: 'INCREMENT' });
store.dispatch({ type: 'DECREMENT' }); store.dispatch({ type: 'DECREMENT' });
store.dispatch({ type: 'INCREMENT' }); store.dispatch({ type: 'INCREMENT' });
@ -101,7 +101,7 @@ describe('instrument', () => {
}); });
it('should sweep disabled actions', () => { it('should sweep disabled actions', () => {
// stateIndex 0 = @@INIT // actionId 0 = @@INIT
store.dispatch({ type: 'INCREMENT' }); store.dispatch({ type: 'INCREMENT' });
store.dispatch({ type: 'DECREMENT' }); store.dispatch({ type: 'DECREMENT' });
store.dispatch({ type: 'INCREMENT' }); store.dispatch({ type: 'INCREMENT' });
@ -115,10 +115,8 @@ describe('instrument', () => {
expect(store.getState()).toBe(3); expect(store.getState()).toBe(3);
liftedStore.dispatch(ActionCreators.toggleAction(2)); liftedStore.dispatch(ActionCreators.toggleAction(2));
expect(store.getState()).toBe(2); // Now it has no effect because it's not staged
expect(store.getState()).toBe(3);
liftedStore.dispatch(ActionCreators.sweep());
expect(store.getState()).toBe(2);
}); });
it('should jump to state', () => { it('should jump to state', () => {