Is my history correctly implemented as it is not working as expected #10401
Unanswered
aayushmaan-54
asked this question in
Q&A
Replies: 2 comments
-
i am using |
Beta Was this translation helpful? Give feedback.
0 replies
-
Split and Call, Reference Example: class Stack {
private arr: any[];
constructor() {
this.arr = [];
}
pop() {
return this.arr.pop();
}
push(item: any) {
this.arr.push(item);
}
size() {
return this.arr.length;
}
empty() {
return this.arr.length == 0;
}
top() {
return this.arr[this.arr.length - 1];
}
destroy() {
this.arr = [];
}
}
class UndoRedo<T = any> {
private uList: Stack;
private rList: Stack;
constructor() {
this.uList = new Stack();
this.rList = new Stack();
}
push(item: T) {
this.uList.push(item);
this.rList = new Stack();
}
undo() {
const item = this.uList.pop();
if (item == null) return null;
this.rList.push(item);
return item as T;
}
redo() {
const item = this.rList.pop();
if (item == null) return null;
this.uList.push(item);
return item as T;
}
pop(num = 1) {
return new Array(num).map(() => this.uList.pop()).filter((x) => x) as T[];
}
undoTop() {
return this.uList.top() as T | null;
}
redoTop() {
return this.rList.top() as T | null;
}
destroy() {
this.uList.destroy();
this.rList.destroy();
}
}
type UndoRedoItem = { type: string; data: any }
const canvas = new fabric.Canvas("myCanvas");
const undoRedo = new UndoRedo<UndoRedoItem>();
// user select
undoRedo.push({ type: "select", data: "a" })
undoRedo.push({ type: "select", data: "b" })
// user create / delete
undoRedo.push({ type: "create", data: { width: 10 } })
undoRedo.push({ type: "delete", data: { width: 10 } })
// undo [command + z]
const u = undoRedo.undo();
if (u?.type == "select") ...
// redo [command + shift + z]
const r = undoRedo.redo();
if (r?.type == "select") ...
// other: check
const u = undoRedo.undo();
const t = undoRedo.undoTop();
if (u?.type == "select" && t?.type == "create") ...
// other: abandon
const u = undoRedo.undo();
if (u?.type == "select") undoRedo.pop();
// say goodbye
undoRedo.destroy()
|
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
so i am making app like canva and in there i want to create undo, redo so is that correctly implemented?
Beta Was this translation helpful? Give feedback.
All reactions