changeset 462:2624bb55dbf6

Fix ordering of adding to history (after an action). Add functions for stepping through the history.
author Lucas Thompson <dev@lucas.im>
date Fri, 30 Jun 2017 13:59:21 +0100
parents 34db9d45663f
children c9c6b01e9b4f
files src/app/Session.ts
diffstat 1 files changed, 25 insertions(+), 5 deletions(-) [+]
line wrap: on
line diff
--- a/src/app/Session.ts	Fri Jun 30 13:58:45 2017 +0100
+++ b/src/app/Session.ts	Fri Jun 30 13:59:21 2017 +0100
@@ -64,22 +64,24 @@
 export class PersistentStack<T> {
   private stack: T[];
   private history: T[][];
+  private historyOffset: number;
 
   constructor() {
     this.stack = [];
-    this.history = [];
+    this.history = [[]];
+    this.historyOffset = 0;
   }
 
   shift(): T {
-    this.history.push([...this.stack]);
     const item = this.stack[0];
     this.stack = this.stack.slice(1);
+    this.history.push([...this.stack]);
     return item;
   }
 
   unshift(item: T): number {
+    this.stack = [item, ...this.stack];
     this.history.push([...this.stack]);
-    this.stack = [item, ...this.stack];
     return this.stack.length;
   }
 
@@ -98,12 +100,12 @@
   }
 
   set(index: number, value: T) {
-    this.history.push([...this.stack]);
     this.stack = [
       ...this.stack.slice(0, index),
       value,
       ...this.stack.slice(index + 1)
     ];
+    this.history.push([...this.stack]);
   }
 
   map<U>(transform: (value: T, index: number, array: T[]) => U): U[] {
@@ -119,13 +121,31 @@
   }
 
   remove(...indices: number[]) {
-    this.history.push([...this.stack]);
     this.stack = this.stack.reduce((acc, item, i) => {
       if (!indices.includes(i)) {
         acc.push(item);
       }
       return acc;
     }, [] as T[]);
+    this.history.push([...this.stack]);
+  }
+
+  stepBack(): void {
+    const latest = this.history.length - 1;
+    if (++this.historyOffset <= latest) {
+      this.stack = this.history[latest - this.historyOffset];
+    } else {
+      this.historyOffset = latest;
+    }
+  }
+
+  stepForward(): void {
+    const latest = this.history.length - 1;
+    if (--this.historyOffset >= 0) {
+      this.stack = this.history[latest - this.historyOffset];
+    } else {
+      this.historyOffset = 0;
+    }
   }
 
   toIterable(): Iterable<T> {