this repo has no description
at main 38 lines 1.2 kB view raw
1// A generic undo manager that stores state snapshots. 2export class UndoManager<T> { 3 private undoStack: T[] = []; 4 private redoStack: T[] = []; 5 private currentState: T; 6 constructor(initialState: T) { 7 this.currentState = this.deepCopy(initialState); 8 } 9 private deepCopy(state: T): T { 10 return JSON.parse(JSON.stringify(state)) as T; 11 } 12 execute(newState: T) { 13 this.undoStack.push(this.deepCopy(this.currentState)); 14 this.currentState = this.deepCopy(newState); 15 this.redoStack = []; // clear redo on new action 16 } 17 undo(): T | null { 18 if (!this.undoStack.length) return null; 19 this.redoStack.push(this.deepCopy(this.currentState)); 20 this.currentState = this.undoStack.pop()!; 21 return this.deepCopy(this.currentState); 22 } 23 redo(): T | null { 24 if (!this.redoStack.length) return null; 25 this.undoStack.push(this.deepCopy(this.currentState)); 26 this.currentState = this.redoStack.pop()!; 27 return this.deepCopy(this.currentState); 28 } 29 getState(): T { 30 return this.deepCopy(this.currentState); 31 } 32 canUndo(): boolean { 33 return this.undoStack.length > 0; 34 } 35 canRedo(): boolean { 36 return this.redoStack.length > 0; 37 } 38}