summaryrefslogtreecommitdiff
path: root/assets/javascripts/util/undostack.js
blob: 040a4ebcbf6030a846b3f05d19c43cd4704bb82b (plain)
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
(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()
    this.debug && console.log("push", action.type)
  }
  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(actions){
  	if (actions.length) {
  		actions.forEach(this.registerOne.bind(this))
  	}
  	else {
  		this.registerOne(actions)
		}
  }
  UndoStack.prototype.registerOne = function(action){
		if (! action.redo) { action.redo = action.undo }
		this.types[ action.type ] = action
	}  
  if ('window' in this) {
    window.UndoStack = new UndoStack
  }
  else {
    module.exports = new UndoStack
  }

})()