diff --git a/src/index.tsx b/src/index.tsx index 6bbb9180..5af8f7ce 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -13,6 +13,9 @@ type ExcaliburTextElement = ExcaliburElement & { actualBoundingBoxAscent: number; }; +const LOCAL_STORAGE_KEY = "excalibur"; +const LOCAL_STORAGE_KEY_STATE = "excalibur-state"; + var elements = Array.of(); // https://stackoverflow.com/a/6853926/232122 @@ -134,6 +137,8 @@ function renderScene( // null indicates transparent bg viewBackgroundColor: string | null ) { + if (!context) return; + const fillStyle = context.fillStyle; if (typeof viewBackgroundColor === "string") { context.fillStyle = viewBackgroundColor; @@ -410,6 +415,28 @@ function deleteSelectedElements() { } } +function save(state: AppState) { + localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(elements)); + localStorage.setItem(LOCAL_STORAGE_KEY_STATE, JSON.stringify(state)); +} + +function restore() { + try { + const savedElements = localStorage.getItem(LOCAL_STORAGE_KEY); + const savedState = localStorage.getItem(LOCAL_STORAGE_KEY_STATE); + + if (savedElements) { + elements = JSON.parse(savedElements); + elements.forEach((element: ExcaliburElement) => generateDraw(element)); + } + + return savedState ? JSON.parse(savedState) : null; + } catch (e) { + elements = []; + return null; + } +} + type AppState = { draggingElement: ExcaliburElement | null; elementType: string; @@ -446,6 +473,11 @@ const ELEMENT_TRANSLATE_AMOUNT = 1; class App extends React.Component<{}, AppState> { public componentDidMount() { document.addEventListener("keydown", this.onKeyDown, false); + + const savedState = restore(); + if (savedState) { + this.setState(savedState); + } } public componentWillUnmount() { @@ -819,6 +851,7 @@ class App extends React.Component<{}, AppState> { componentDidUpdate() { renderScene(rc, context, this.state.viewBackgroundColor); + save(this.state); } }