From dfb7c2b7441e0caf83ca70863728ed834290f58b Mon Sep 17 00:00:00 2001 From: Enzo Ferey Date: Wed, 22 Jan 2020 21:32:43 +0100 Subject: [PATCH] Add app state to history (#309) * Add app state to history. * Pick missing state keys. * Fix bug. * Remove force update. --- src/history.ts | 13 +++++++++---- src/index.tsx | 30 +++++++++++++++++++++++++----- 2 files changed, 34 insertions(+), 9 deletions(-) diff --git a/src/history.ts b/src/history.ts index 34675264..30943ac5 100644 --- a/src/history.ts +++ b/src/history.ts @@ -1,3 +1,4 @@ +import { AppState } from "./types"; import { ExcalidrawElement } from "./element/types"; class SceneHistory { @@ -5,13 +6,17 @@ class SceneHistory { private stateHistory: string[] = []; private redoStack: string[] = []; - generateCurrentEntry(elements: readonly ExcalidrawElement[]) { - return JSON.stringify( - elements.map(({ shape, ...element }) => ({ + generateCurrentEntry( + appState: Partial, + elements: readonly ExcalidrawElement[] + ) { + return JSON.stringify({ + appState, + elements: elements.map(({ shape, ...element }) => ({ ...element, isSelected: false })) - ); + }); } pushEntry(newEntry: string) { diff --git a/src/index.tsx b/src/index.tsx index 9e414337..45b21349 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -115,6 +115,19 @@ export function viewportCoordsToSceneCoords( return { x, y }; } +function pickAppStatePropertiesForHistory( + appState: AppState +): Partial { + return { + exportBackground: appState.exportBackground, + currentItemStrokeColor: appState.currentItemStrokeColor, + currentItemBackgroundColor: appState.currentItemBackgroundColor, + currentItemFont: appState.currentItemFont, + viewBackgroundColor: appState.viewBackgroundColor, + name: appState.name + }; +} + export class App extends React.Component { canvas: HTMLCanvasElement | null = null; rc: RoughCanvas | null = null; @@ -312,21 +325,23 @@ export class App extends React.Component { } this.setState({ elementType: shape }); } else if (event[KEYS.META] && event.code === "KeyZ") { + event.preventDefault(); + if (event.shiftKey) { // Redo action const data = history.redoOnce(); if (data !== null) { - elements = data; + elements = data.elements; + this.setState(data.appState); } } else { // undo action const data = history.undoOnce(); if (data !== null) { - elements = data; + elements = data.elements; + this.setState(data.appState); } } - this.forceUpdate(); - event.preventDefault(); } }; @@ -1387,7 +1402,12 @@ export class App extends React.Component { }); this.saveDebounced(); if (history.isRecording()) { - history.pushEntry(history.generateCurrentEntry(elements)); + history.pushEntry( + history.generateCurrentEntry( + pickAppStatePropertiesForHistory(this.state), + elements + ) + ); } } }