Encapsulate undo and redo actions within history

This commit is contained in:
Gasim Gasimzada 2020-01-06 21:38:32 +04:00
parent 01a922bf20
commit 9eeb4b10af
2 changed files with 25 additions and 14 deletions

View file

@ -34,6 +34,29 @@ class SceneHistory {
this.skipRecording(); this.skipRecording();
} }
redoOnce(elements: ExcalidrawElement[]) {
const currentEntry = this.generateCurrentEntry(elements);
const entryToRestore = this.redoStack.pop();
if (entryToRestore !== undefined) {
this.restoreEntry(elements, entryToRestore);
this.stateHistory.push(currentEntry);
}
}
undoOnce(elements: ExcalidrawElement[]) {
const currentEntry = this.generateCurrentEntry(elements);
let entryToRestore = this.stateHistory.pop();
// If nothing was changed since last, take the previous one
if (currentEntry === entryToRestore) {
entryToRestore = this.stateHistory.pop();
}
if (entryToRestore !== undefined) {
this.restoreEntry(elements, entryToRestore);
this.redoStack.push(currentEntry);
}
}
isRecording() { isRecording() {
return this.recording; return this.recording;
} }

View file

@ -206,22 +206,10 @@ class App extends React.Component<{}, AppState> {
const currentEntry = history.generateCurrentEntry(elements); const currentEntry = history.generateCurrentEntry(elements);
if (event.shiftKey) { if (event.shiftKey) {
// Redo action // Redo action
const entryToRestore = history.redoStack.pop(); history.redoOnce(elements);
if (entryToRestore !== undefined) {
history.restoreEntry(elements, entryToRestore);
history.stateHistory.push(currentEntry);
}
} else { } else {
// undo action // undo action
let lastEntry = history.stateHistory.pop(); history.undoOnce(elements);
// If nothing was changed since last, take the previous one
if (currentEntry === lastEntry) {
lastEntry = history.stateHistory.pop();
}
if (lastEntry !== undefined) {
history.restoreEntry(elements, lastEntry);
history.redoStack.push(currentEntry);
}
} }
this.forceUpdate(); this.forceUpdate();
event.preventDefault(); event.preventDefault();