summaryrefslogtreecommitdiff
path: root/undo/undostack.js
diff options
context:
space:
mode:
Diffstat (limited to 'undo/undostack.js')
-rw-r--r--undo/undostack.js53
1 files changed, 53 insertions, 0 deletions
diff --git a/undo/undostack.js b/undo/undostack.js
new file mode 100644
index 0000000..5ba97e1
--- /dev/null
+++ b/undo/undostack.js
@@ -0,0 +1,53 @@
+(function(){
+
+ var UndoStack = function(){
+ this.debug = true
+ this.stack = []
+ this.types = {}
+ this.pointer = -1
+ }
+ UndoStack.prototype.push = function(action){
+ this.pointer++
+ this.stack[this.pointer] = action
+ this.purge()
+ }
+ UndoStack.prototype.purge = function(){
+ if (this.stack.length-1 == this.pointer) return
+ this.stack.length = this.pointer+1
+ }
+ UndoStack.prototype.undo = function(){
+ if (this.pointer == -1) return false
+ var action = this.stack[this.pointer]
+ this.debug && console.log("undo", action.type)
+ this.types[ action.type ].undo(action.undo)
+ this.pointer--
+ return this.pointer > -1
+ }
+ UndoStack.prototype.redo = function(){
+ if (this.pointer == this.stack.length-1) return false
+ this.pointer++
+ var action = this.stack[this.pointer]
+ this.debug && console.log("redo", action.type)
+ this.types[ action.type ].redo(action.redo)
+ return this.pointer < this.stack.length-1
+ }
+ UndoStack.prototype.register = function(actionType){
+ if (actionType.length) {
+ actionType.forEach(this.registerOne.bind(this))
+ }
+ else {
+ this.registerOne(actionType)
+ }
+ }
+ UndoStack.prototype.registerOne = function(actionType){
+ this.types[ actionType.type ] = actionType
+ }
+ if ('window' in this) {
+ window.UndoStack = new UndoStack
+ }
+ else {
+ module.exports = new UndoStack
+ }
+
+})()
+