homemanager-fe/src/modules/house-planner/history.ts

53 lines
1.3 KiB
TypeScript

import { History } from './interfaces';
export class HousePlannerCanvasHistory {
private history: History<unknown>[][] = [];
private unhistory: History<unknown>[][] = [];
private lastCommandWasUndo = false;
constructor() {}
appendToHistory(changes: History<any>[]) {
this.history.push(changes);
this.unhistory.length = 0;
}
undo() {
const lastChanges = this.history.pop();
if (!lastChanges) return;
if (!this.lastCommandWasUndo && this.unhistory.length) {
this.unhistory.length = 0;
}
this.lastCommandWasUndo = true;
let redo = [];
for (const change of lastChanges) {
if (!change.object) continue;
const preChange = (change.object as any)[change.property];
(change.object as any)[change.property] = change.value;
redo.push({
...change,
value: preChange as any,
});
}
this.unhistory.push(redo);
}
redo() {
const lastChanges = this.unhistory.pop();
if (!lastChanges) return;
this.lastCommandWasUndo = false;
let undo = [];
for (const change of lastChanges) {
if (!change.object) continue;
const preChange = (change.object as any)[change.property];
(change.object as any)[change.property] = change.value;
undo.push({
...change,
value: preChange as any,
});
}
this.history.push(undo);
}
}