浏览代码

Save to local storage (#53)

* Save to local storage

* Restore on page load

* Warning when leave without save
Paulo Menezes 5 年之前
父节点
当前提交
98b158a83d
共有 1 个文件被更改,包括 33 次插入0 次删除
  1. 33 0
      src/index.tsx

+ 33 - 0
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<ExcaliburElement>();
 
 // 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);
   }
 }