|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +//Modified from https://github.com/ArthurClemens/Javascript-Undo-Manager |
| 4 | +//Copyright (c) 2010-2013 Arthur Clemens, [email protected] |
| 5 | +module.exports = function UndoManager() { |
| 6 | + var undoCommands = [], |
| 7 | + index = -1, |
| 8 | + isExecuting = false, |
| 9 | + callback; |
| 10 | + |
| 11 | + function execute(command, action){ |
| 12 | + if(!command) return this; |
| 13 | + |
| 14 | + isExecuting = true; |
| 15 | + command[action](); |
| 16 | + isExecuting = false; |
| 17 | + |
| 18 | + return this; |
| 19 | + } |
| 20 | + |
| 21 | + return { |
| 22 | + add: function(command){ |
| 23 | + if(isExecuting) return this; |
| 24 | + undoCommands.splice(index + 1, undoCommands.length - index); |
| 25 | + undoCommands.push(command); |
| 26 | + index = undoCommands.length - 1; |
| 27 | + return this; |
| 28 | + }, |
| 29 | + setCallback: function(callbackFunc){ callback = callbackFunc; }, |
| 30 | + undo: function(){ |
| 31 | + var command = undoCommands[index]; |
| 32 | + if(!command) return this; |
| 33 | + execute(command, 'undo'); |
| 34 | + index -= 1; |
| 35 | + if(callback) callback(command.undo); |
| 36 | + return this; |
| 37 | + }, |
| 38 | + redo: function(){ |
| 39 | + var command = undoCommands[index + 1]; |
| 40 | + if(!command) return this; |
| 41 | + execute(command, 'redo'); |
| 42 | + index += 1; |
| 43 | + if(callback) callback(command.redo); |
| 44 | + return this; |
| 45 | + }, |
| 46 | + clear: function(){ |
| 47 | + undoCommands = []; |
| 48 | + index = -1; |
| 49 | + }, |
| 50 | + hasUndo: function(){ return index !== -1; }, |
| 51 | + hasRedo: function(){ return index < (undoCommands.length - 1); }, |
| 52 | + getCommands: function(){ return undoCommands; }, |
| 53 | + getPreviousCommand: function(){ return undoCommands[index-1]; }, |
| 54 | + getIndex: function(){ return index; } |
| 55 | + }; |
| 56 | +}; |
0 commit comments