Save to local storage (#53)

* Save to local storage

* Restore on page load

* Warning when leave without save
This commit is contained in:
Paulo Menezes 2020-01-03 14:12:37 -03:00 committed by Christopher Chedeau
parent f2386eb131
commit 98b158a83d

View File

@ -13,6 +13,9 @@ type ExcaliburTextElement = ExcaliburElement & {
actualBoundingBoxAscent: number; actualBoundingBoxAscent: number;
}; };
const LOCAL_STORAGE_KEY = "excalibur";
const LOCAL_STORAGE_KEY_STATE = "excalibur-state";
var elements = Array.of<ExcaliburElement>(); var elements = Array.of<ExcaliburElement>();
// https://stackoverflow.com/a/6853926/232122 // https://stackoverflow.com/a/6853926/232122
@ -134,6 +137,8 @@ function renderScene(
// null indicates transparent bg // null indicates transparent bg
viewBackgroundColor: string | null viewBackgroundColor: string | null
) { ) {
if (!context) return;
const fillStyle = context.fillStyle; const fillStyle = context.fillStyle;
if (typeof viewBackgroundColor === "string") { if (typeof viewBackgroundColor === "string") {
context.fillStyle = viewBackgroundColor; 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 = { type AppState = {
draggingElement: ExcaliburElement | null; draggingElement: ExcaliburElement | null;
elementType: string; elementType: string;
@ -446,6 +473,11 @@ const ELEMENT_TRANSLATE_AMOUNT = 1;
class App extends React.Component<{}, AppState> { class App extends React.Component<{}, AppState> {
public componentDidMount() { public componentDidMount() {
document.addEventListener("keydown", this.onKeyDown, false); document.addEventListener("keydown", this.onKeyDown, false);
const savedState = restore();
if (savedState) {
this.setState(savedState);
}
} }
public componentWillUnmount() { public componentWillUnmount() {
@ -819,6 +851,7 @@ class App extends React.Component<{}, AppState> {
componentDidUpdate() { componentDidUpdate() {
renderScene(rc, context, this.state.viewBackgroundColor); renderScene(rc, context, this.state.viewBackgroundColor);
save(this.state);
} }
} }