forked from jzaefferer/undo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
undo.js
127 lines (113 loc) · 2.48 KB
/
undo.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
/*
* Undo.js - A undo/redo framework for JavaScript
*
* http://jzaefferer.github.com/undo
*
* Copyright (c) 2011 Jörn Zaefferer
*
* MIT licensed.
*/
(function() {
// based on Backbone.js' inherits
var ctor = function(){};
var inherits = function(parent, protoProps) {
var child;
if (protoProps && protoProps.hasOwnProperty('constructor')) {
child = protoProps.constructor;
} else {
child = function(){ return parent.apply(this, arguments); };
}
ctor.prototype = parent.prototype;
child.prototype = new ctor();
if (protoProps) extend(child.prototype, protoProps);
child.prototype.constructor = child;
child.__super__ = parent.prototype;
return child;
};
function extend(target, ref) {
var name, value;
for ( name in ref ) {
value = ref[name];
if (value !== undefined) {
target[ name ] = value;
}
}
return target;
};
var Undo = {
version: '0.1.15'
};
Undo.Stack = function() {
this.commands = [];
this.stackPosition = -1;
this.savePosition = -1;
};
extend(Undo.Stack.prototype, {
execute: function(command) {
this._clearRedo();
command.execute();
this.commands.push(command);
this.stackPosition++;
this.changed();
},
undo: function() {
this.commands[this.stackPosition].undo();
this.stackPosition--;
this.changed();
},
canUndo: function() {
return this.stackPosition >= 0;
},
redo: function() {
this.stackPosition++;
this.commands[this.stackPosition].redo();
this.changed();
},
canRedo: function() {
return this.stackPosition < this.commands.length - 1;
},
save: function() {
this.savePosition = this.stackPosition;
this.changed();
},
dirty: function() {
return this.stackPosition != this.savePosition;
},
_clearRedo: function() {
// TODO there's probably a more efficient way for this
this.commands = this.commands.slice(0, this.stackPosition + 1);
},
changed: function() {
// do nothing, override
}
});
Undo.Command = function(name) {
this.name = name;
}
var up = new Error("override me!");
extend(Undo.Command.prototype, {
execute: function() {
throw up;
},
undo: function() {
throw up;
},
redo: function() {
this.execute();
}
});
Undo.Command.extend = function(protoProps) {
var child = inherits(this, protoProps);
child.extend = Undo.Command.extend;
return child;
};
// AMD support
if (typeof define === "function" && define.amd) {
// Define as an anonymous module
define(Undo);
} else if(typeof module != "undefined" && module.exports){
module.exports = Undo
}else {
this.Undo = Undo;
}
}).call(this);