Skip to content

Commit

Permalink
Prevent undo / redo if no past / future respectively
Browse files Browse the repository at this point in the history
  • Loading branch information
aduth committed Jul 28, 2017
1 parent 3c68e0f commit 3eaed9a
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
30 changes: 30 additions & 0 deletions editor/utils/test/undoable-reducer.js
Expand Up @@ -49,13 +49,43 @@ describe( 'undoableReducer', () => {
} );
} );

it( 'should not perform undo on empty past', () => {
const reducer = undoable( counter );

let state;
state = reducer( undefined, {} );
state = reducer( state, { type: 'INCREMENT' } );
state = reducer( state, { type: 'UNDO' } );

expect( state ).toEqual( {
past: [],
present: 0,
future: [ 1 ],
} );
} );

it( 'should perform redo', () => {
const reducer = undoable( counter );

let state;
state = reducer( undefined, {} );
state = reducer( state, { type: 'INCREMENT' } );
state = reducer( state, { type: 'UNDO' } );
state = reducer( state, { type: 'UNDO' } );

expect( state ).toEqual( {
past: [],
present: 0,
future: [ 1 ],
} );
} );

it( 'should not perform redo on empty future', () => {
const reducer = undoable( counter );

let state;
state = reducer( undefined, {} );
state = reducer( state, { type: 'INCREMENT' } );
state = reducer( state, { type: 'REDO' } );

expect( state ).toEqual( {
Expand Down
10 changes: 10 additions & 0 deletions editor/utils/undoable-reducer.js
Expand Up @@ -25,13 +25,23 @@ export function undoable( reducer, options = {} ) {

switch ( action.type ) {
case 'UNDO':
// Can't undo if no past
if ( ! past.length ) {
break;
}

return {
past: past.slice( 0, past.length - 1 ),
present: past[ past.length - 1 ],
future: [ present, ...future ],
};

case 'REDO':
// Can't redo if no future
if ( ! future.length ) {
break;
}

return {
past: [ ...past, present ],
present: future[ 0 ],
Expand Down

0 comments on commit 3eaed9a

Please sign in to comment.