« get me outta code hell

mtui - Music Text User Interface - user-friendly command line music player
about summary refs log tree commit diff
path: root/undo-manager.js
diff options
context:
space:
mode:
Diffstat (limited to 'undo-manager.js')
-rw-r--r--undo-manager.js42
1 files changed, 42 insertions, 0 deletions
diff --git a/undo-manager.js b/undo-manager.js
new file mode 100644
index 0000000..4a042ad
--- /dev/null
+++ b/undo-manager.js
@@ -0,0 +1,42 @@
+class UndoManager {
+  constructor() {
+    this.actionStack = []
+    this.undoneStack = []
+  }
+
+  pushAction(action) {
+    this.undoneStack = []
+    this.actionStack.push(action)
+    action.activate()
+  }
+
+  undoLastAction() {
+    if (this.actionStack.length === 0) {
+      return
+    }
+
+    const action = this.actionStack.pop()
+    this.undoneStack.push(action)
+
+    action.undo()
+  }
+
+  redoLastUndoneAction() {
+    if (this.undoneStack.length === 0) {
+      return
+    }
+
+    const action = this.undoneStack.pop()
+    this.actionStack.push(action)
+    action.activate()
+  }
+
+  get safeToPushAction() {
+    // Is it safe to push a new action? That is, since pushing a new action
+    // clears the undone actions stack, will any undone actions be lost?
+
+    return this.undoStack.length === 0
+  }
+}
+
+module.exports = UndoManager