From 9cd88d59e45b530e483490804503e6b47030fd4d Mon Sep 17 00:00:00 2001 From: Jules Laplace Date: Fri, 8 Aug 2014 18:56:41 -0400 Subject: undo stack --- public/assets/javascripts/rectangles/util/undo.js | 42 +++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 public/assets/javascripts/rectangles/util/undo.js (limited to 'public/assets/javascripts/rectangles/util/undo.js') diff --git a/public/assets/javascripts/rectangles/util/undo.js b/public/assets/javascripts/rectangles/util/undo.js new file mode 100644 index 0000000..3700817 --- /dev/null +++ b/public/assets/javascripts/rectangles/util/undo.js @@ -0,0 +1,42 @@ +(function(){ + + var UndoStack = function(){ + 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.types[ action.type ].undo(action) + 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.types[ action.type ].redo(action) + return this.pointer < this.stack.length-1 + } + UndoStack.prototype.register = function(actionType){ + this.types[ actionType.type ] = actionType + } + + if ('window' in this) { + window.UndoStack = new UndoStack + } + else { + module.exports = new UndoStack + } + +})() -- cgit v1.2.3-70-g09d2