-
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
Copy pathundo_manager.js
64 lines (58 loc) · 1.92 KB
/
undo_manager.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/**
* Copyright 2012-2017, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
// Modified from https://github.com/ArthurClemens/Javascript-Undo-Manager
// Copyright (c) 2010-2013 Arthur Clemens, [email protected]
module.exports = function UndoManager() {
var undoCommands = [],
index = -1,
isExecuting = false,
callback;
function execute(command, action) {
if(!command) return this;
isExecuting = true;
command[action]();
isExecuting = false;
return this;
}
return {
add: function(command) {
if(isExecuting) return this;
undoCommands.splice(index + 1, undoCommands.length - index);
undoCommands.push(command);
index = undoCommands.length - 1;
return this;
},
setCallback: function(callbackFunc) { callback = callbackFunc; },
undo: function() {
var command = undoCommands[index];
if(!command) return this;
execute(command, 'undo');
index -= 1;
if(callback) callback(command.undo);
return this;
},
redo: function() {
var command = undoCommands[index + 1];
if(!command) return this;
execute(command, 'redo');
index += 1;
if(callback) callback(command.redo);
return this;
},
clear: function() {
undoCommands = [];
index = -1;
},
hasUndo: function() { return index !== -1; },
hasRedo: function() { return index < (undoCommands.length - 1); },
getCommands: function() { return undoCommands; },
getPreviousCommand: function() { return undoCommands[index - 1]; },
getIndex: function() { return index; }
};
};