Make history actions immutable

This commit is contained in:
Gasim Gasimzada 2020-01-09 12:51:36 +04:00
parent 642a11e380
commit ccb886730b
2 changed files with 21 additions and 10 deletions

View file

@ -22,14 +22,15 @@ class SceneHistory {
this.stateHistory.push(newEntry); this.stateHistory.push(newEntry);
} }
restoreEntry(elements: ExcalidrawElement[], entry: string) { restoreEntry(entry: string) {
const newElements = JSON.parse(entry);
elements.splice(0, elements.length);
newElements.forEach((newElement: ExcalidrawElement) => {
elements.push(newElement);
});
// When restoring, we shouldn't add an history entry otherwise we'll be stuck with it and can't go back // When restoring, we shouldn't add an history entry otherwise we'll be stuck with it and can't go back
this.skipRecording(); this.skipRecording();
try {
return JSON.parse(entry);
} catch {
return null;
}
} }
clearRedoStack() { clearRedoStack() {
@ -40,9 +41,11 @@ class SceneHistory {
const currentEntry = this.generateCurrentEntry(elements); const currentEntry = this.generateCurrentEntry(elements);
const entryToRestore = this.redoStack.pop(); const entryToRestore = this.redoStack.pop();
if (entryToRestore !== undefined) { if (entryToRestore !== undefined) {
this.restoreEntry(elements, entryToRestore);
this.stateHistory.push(currentEntry); this.stateHistory.push(currentEntry);
return this.restoreEntry(entryToRestore);
} }
return null;
} }
undoOnce(elements: ExcalidrawElement[]) { undoOnce(elements: ExcalidrawElement[]) {
@ -54,9 +57,11 @@ class SceneHistory {
entryToRestore = this.stateHistory.pop(); entryToRestore = this.stateHistory.pop();
} }
if (entryToRestore !== undefined) { if (entryToRestore !== undefined) {
this.restoreEntry(elements, entryToRestore);
this.redoStack.push(currentEntry); this.redoStack.push(currentEntry);
return this.restoreEntry(entryToRestore);
} }
return null;
} }
isRecording() { isRecording() {

View file

@ -214,10 +214,16 @@ export class App extends React.Component<{}, AppState> {
} else if (event[META_KEY] && event.code === "KeyZ") { } else if (event[META_KEY] && event.code === "KeyZ") {
if (event.shiftKey) { if (event.shiftKey) {
// Redo action // Redo action
history.redoOnce(elements); const data = history.redoOnce(elements);
if (data !== null) {
elements = data;
}
} else { } else {
// undo action // undo action
history.undoOnce(elements); const data = history.undoOnce(elements);
if (data !== null) {
elements = data;
}
} }
this.forceUpdate(); this.forceUpdate();
event.preventDefault(); event.preventDefault();