redux-undo

higher order reducer to add undo/redo functionality to redux state containe...

README

redux undo/redo

NPM version (>=1.0) NPM Downloads Coverage Status Dependencies js-standard-style GitHub license

_simple undo/redo functionality for redux state containers_
https://i.imgur.com/M2KR4uo.gif

Protip: Check out the todos-with-undo example or the redux-undo-boilerplate to quickly get started withredux-undo.

Switching from 0.x to 1.0: Make sure to update your programs to the latest History API.

Help wanted: We are looking for volunteers to maintain this project, if you are interested, feel free to contact me at me@omnidan.net


This README is about the new 1.0 branch of redux-undo, if you are using
or plan on using 0.6, check out [the 0.6 branch](https://github.com/omnidan/redux-undo/tree/0.6)


Note on Imports


If you use Redux Undo in CommonJS environment, don’t forget to add .default to your import.

  1. ```diff
  2. - var ReduxUndo = require('redux-undo')
  3. + var ReduxUndo = require('redux-undo').default
  4. ```

If your environment support es modules just go by:

  1. ``` js
  2. import ReduxUndo from 'redux-undo';
  3. ```

We are also supporting UMD build:

  1. ``` js
  2. var ReduxUndo = window.ReduxUndo.default;
  3. ```

once again .default is required.

Installation


  1. ```
  2. npm install --save redux-undo
  3. ```


API


  1. ``` js
  2. import undoable from 'redux-undo';
  3. undoable(reducer)
  4. undoable(reducer, config)
  5. ```


Making your reducers undoable


redux-undo is a reducer enhancer (higher-order reducer). It provides the undoable function, which
takes an existing reducer and a configuration object and enhances your existing
reducer with undo functionality.

Note: If you were accessing state.counter before, you have to access
state.present.counter after wrapping your reducer with undoable.

To install, firstly import redux-undo:

  1. ``` js
  2. // Redux utility functions
  3. import { combineReducers } from 'redux';
  4. // redux-undo higher-order reducer
  5. import undoable from 'redux-undo';
  6. ```

Then, add undoable to your reducer(s) like this:

  1. ``` js
  2. combineReducers({
  3.   counter: undoable(counter)
  4. })
  5. ```

A configuration can be passed like this:

  1. ``` js
  2. combineReducers({
  3.   counter: undoable(counter, {
  4.     limit: 10 // set a limit for the size of the history
  5.   })
  6. })
  7. ```

Apply redux-undo magic to specific slice of your state.

When you expose an undo redo history action to your app users, you will not want those action
to apply on your whole redux state.
Lets see this with naive document editor state.

  1. ``` js
  2. const rootReducer = combineReducers({
  3.   ui: uiReducer,
  4.   document: documentReducer,
  5. })
  6. ```

wrapping the documentReducer with undoable higher order reducer

  1. ``` js
  2. const rootReducer = combineReducers({
  3.   ui: uiReducer,
  4.   document: undoable(documentReducer),
  5. })
  6. ```
will provide only the document mountpoint of your state with an history.

an even more advanced usage would be to have many different mountpoint of your redux state, managed
under redux-undo.
  1. ``` js
  2. const rootReducer = combineReducers({
  3.   ui: uiReducer,
  4.   document: undoable(documentReducer, {
  5.     undoType: 'DOCUMENT_UNDO',
  6.     redoType: 'DOCUMENT_REDO',
  7.     // here you will want to configure specific redux-undo action type  
  8.   }),
  9.   anotherDocument: undoable(documentReducer, {
  10.     undoType: 'ANOTHERDOCUMENT_UNDO',
  11.     redoType: 'ANOTHERDOCUMENT_REDO',
  12.     // here you will want to configure specific redux-undo action type  
  13.   }),
  14. })
  15. ```
Don't forget to configure specific redux-undo action type for each of your mount point if you don't
want to see your different history to undo/redo in sync.

History API


Wrapping your reducer with undoable makes the state look like this:

  1. ``` js
  2. {
  3.   past: [...pastStatesHere...],
  4.   present: {...currentStateHere...},
  5.   future: [...futureStatesHere...]
  6. }
  7. ```

Now you can get your current state like this: state.present

And you can access all past states (e.g. to show a history) like this: state.past

Note: Your reducer still receives the current state, a.k.a. state.present. Therefore, you would not have to update an existing reducer to add undo functionality.


Undo/Redo Actions


Firstly, import the undo/redo action creators:

  1. ``` js
  2. import { ActionCreators } from 'redux-undo';
  3. ```

Then, you can use store.dispatch() and the undo/redo action creators to
perform undo/redo operations on your state:

  1. ``` js
  2. store.dispatch(ActionCreators.undo()) // undo the last action
  3. store.dispatch(ActionCreators.redo()) // redo the last action

  4. store.dispatch(ActionCreators.jump(-2)) // undo 2 steps
  5. store.dispatch(ActionCreators.jump(5)) // redo 5 steps

  6. store.dispatch(ActionCreators.jumpToPast(index)) // jump to requested index in the past[] array
  7. store.dispatch(ActionCreators.jumpToFuture(index)) // jump to requested index in the future[] array

  8. store.dispatch(ActionCreators.clearHistory()) // Remove all items from past[] and future[] arrays
  9. ```


Configuration


A configuration object can be passed to undoable() like this (values shown
are default values):

  1. ``` js
  2. undoable(reducer, {
  3.   limit: false, // set to a number to turn on a limit for the history

  4.   filter: () => true, // see `Filtering Actions`
  5.   groupBy: () => null, // see `Grouping Actions`

  6.   undoType: ActionTypes.UNDO, // define a custom action type for this undo action
  7.   redoType: ActionTypes.REDO, // define a custom action type for this redo action

  8.   jumpType: ActionTypes.JUMP, // define custom action type for this jump action

  9.   jumpToPastType: ActionTypes.JUMP_TO_PAST, // define custom action type for this jumpToPast action
  10.   jumpToFutureType: ActionTypes.JUMP_TO_FUTURE, // define custom action type for this jumpToFuture action

  11.   clearHistoryType: ActionTypes.CLEAR_HISTORY, // define custom action type for this clearHistory action
  12.   // you can also pass an array of strings to define several action types that would clear the history
  13.   // beware: those actions will not be passed down to the wrapped reducers

  14.   initTypes: ['@@redux-undo/INIT'], // history will be (re)set upon init action type
  15.   // beware: those actions will not be passed down to the wrapped reducers

  16.   debug: false, // set to `true` to turn on debugging
  17.   ignoreInitialState: false, // prevent user from undoing to the beginning, ex: client-side hydration

  18.   neverSkipReducer: false, // prevent undoable from skipping the reducer on undo/redo and clearHistoryType actions
  19.   syncFilter: false // set to `true` to synchronize the `_latestUnfiltered` state with `present` when an excluded action is dispatched
  20. })
  21. ```

Note: If you want to use just the initTypes functionality, but not import
the whole redux-undo library, use redux-recycle!

Initial State and History


You can use your redux store to set an initial history for your undoable reducers:

  1. ``` js

  2. import { createStore } from 'redux';

  3. const initialHistory = {
  4.   past: [0, 1, 2, 3],
  5.   present: 4,
  6.   future: [5, 6, 7]
  7. }

  8. // Alternatively use the helper:
  9. // import { newHistory } from 'redux-undo';
  10. // const initialHistory = newHistory([0, 1, 2, 3], 4, [5, 6, 7]);

  11. const store = createStore(undoable(counter), initialHistory);

  12. ```

Or just set the current state like you're used to with Redux. Redux-undo will create the history for you:

  1. ``` js

  2. import { createStore } from 'redux';

  3. const store = createStore(undoable(counter), {foo: 'bar'});

  4. // will make the state look like this:
  5. {
  6.   past: [],
  7.   present: {foo: 'bar'},
  8.   future: []
  9. }

  10. ```

Grouping Actions


If you want to group your actions together into single undo/redo steps, you
can add a groupBy function to undoable. redux-undo provides
groupByActionTypes as a basic groupBy function:

  1. ``` js
  2. import undoable, { groupByActionTypes } from 'redux-undo';

  3. undoable(reducer, { groupBy: groupByActionTypes(SOME_ACTION) })
  4. // or with arrays
  5. undoable(reducer, { groupBy: groupByActionTypes([SOME_ACTION]) })
  6. ```

In these cases, consecutive SOME_ACTION actions will be considered a single
step in the undo/redo history.

Custom groupBy Function


If you want to implement custom grouping behaviour, pass in your own function
with the signature (action, currentState, previousHistory). If the return
value is not null, then the new state will be grouped by that return value.
If the next state is grouped into the same group as the previous state, then
the two states will be grouped together in one step.

If the return value is null, then redux-undo will not group the next state
with the previous state.

The groupByActionTypes function essentially returns the following:
If a grouped action type (SOME_ACTION), the action type of the action (SOME_ACTION).
If not a grouped action type (any other action type), null.

When groupBy groups a state change, the associated group will be saved
alongside past, present, and future so that it may be referenced by the
next state change.

After an undo/redo/jump occurs, the current group gets reset to null so that
the undo/redo history is remembered.

Filtering Actions


If you don't want to include every action in the undo/redo history, you can add
a filter function to undoable. This is useful for, for example, excluding
actions that were not triggered by the user.

redux-undo provides you with the includeAction and excludeAction helpers
for basic filtering. They should be imported like this:

  1. ``` js
  2. import undoable, { includeAction, excludeAction } from 'redux-undo';
  3. ```

Now you can use the helper functions:

  1. ``` js
  2. undoable(reducer, { filter: includeAction(SOME_ACTION) })
  3. undoable(reducer, { filter: excludeAction(SOME_ACTION) })

  4. // they even support Arrays:

  5. undoable(reducer, { filter: includeAction([SOME_ACTION, SOME_OTHER_ACTION]) })
  6. undoable(reducer, { filter: excludeAction([SOME_ACTION, SOME_OTHER_ACTION]) })
  7. ```

Note: Since [beta4](https://github.com/omnidan/redux-undo/releases/tag/beta4),
          only actions resulting in a new state are recorded. This means the
          (now deprecated) distinctState() filter is auto-applied.

Custom Filters


If you want to create your own filter, pass in a function with the signature
(action, currentState, previousHistory). For example:

  1. ``` js
  2. undoable(reducer, {
  3.   filter: function filterActions(action, currentState, previousHistory) {
  4.     return action.type === SOME_ACTION; // only add to history if action is SOME_ACTION
  5.   }
  6. })

  7. // The entire `history` state is available to your filter, so you can make
  8. // decisions based on past or future states:

  9. undoable(reducer, {
  10.   filter: function filterState(action, currentState, previousHistory) {
  11.     let { past, present, future } = previousHistory;
  12.     return future.length === 0; // only add to history if future is empty
  13.   }
  14. })
  15. ```

Combining Filters


You can also use our helper to combine filters.

  1. ``` js
  2. import undoable, {combineFilters} from 'redux-undo'

  3. function isActionSelfExcluded(action) {
  4.   return action.wouldLikeToBeInHistory
  5. }

  6. function areWeRecording(action, state) {
  7.   return state.recording
  8. }

  9. undoable(reducer, {
  10.   filter: combineFilters(isActionSelfExcluded, areWeRecording)
  11. })
  12. ```

Ignoring Actions


When implementing a filter function, it only prevents the old state from being
stored in the history. filter does not prevent the present state from being
updated.

If you want to ignore an action completely, as in, not even update the present
state, you can make use of redux-ignore.

It can be used like this:

  1. ``` js
  2. import { ignoreActions } from 'redux-ignore'

  3. ignoreActions(
  4.   undoable(reducer),
  5.   [IGNORED_ACTION, ANOTHER_IGNORED_ACTION]
  6. )

  7. // or define your own function:

  8. ignoreActions(
  9.   undoable(reducer),
  10.   (action) => action.type === SOME_ACTION // only add to history if action is SOME_ACTION
  11. )
  12. ```


What is this magic? How does it work?


Have a read of the Implementing Undo History recipe in the Redux documents, which explains in detail how redux-undo works.


Chat / Support


If you have a question or just want to discuss something with other redux-undo users/maintainers, chat with the community on discord (discord.gg/GbHZTmd33n)!

Also, look at the documentation over at redux-undo.js.org.

Sponsors


- Thanks to @tomaAlex (https://woggo.ro/) for sponsoring my projects!

License


MIT, see LICENSE.md for more information.