lianghongjie 1 year ago
parent
commit
c26ad0c100
2 changed files with 32 additions and 15 deletions
  1. 12 2
      src/modules/editor/actions/edit.ts
  2. 20 13
      src/modules/editor/stores/index.ts

+ 12 - 2
src/modules/editor/actions/edit.ts

@@ -1,3 +1,4 @@
+import { Exception, queenApi } from "queenjs";
 import { EditorModule } from "..";
 import { ICompKeys } from "../typings";
 
@@ -34,7 +35,16 @@ export const editActions = EditorModule.action({
     this.store.moveComp(selIndex, targetIndex);
   },
   // 保存项目
-  saveDesign() {
-    this.https.saveDesign(this.store.designData);
+  async saveDesign() {
+    try {
+      queenApi.showLoading("保存中");
+      this.store.clearUnusedComps();
+      await this.https.saveDesign(this.store.designData);
+      queenApi.messageSuccess("保存成功");
+    } catch (error: any) {
+      throw Exception.error(error.toString());
+    } finally {
+      queenApi.hideLoading();
+    }
   },
 });

+ 20 - 13
src/modules/editor/stores/index.ts

@@ -67,8 +67,8 @@ export const store = EditorModule.store({
       }
 
       if (deleteOK) {
-        const comp = this.helper.findComp(compId);
-        const ids = flatCompChildIds(comp?.children || {});
+        const comp = this.helper.findComp(compId) as DesignComp;
+        const ids = this.helper.getCompChildIds(comp);
         [compId, ...ids].forEach((id) => {
           delete compMap[id];
         });
@@ -79,16 +79,23 @@ export const store = EditorModule.store({
       const [selComp] = content.splice(selIndex, 1);
       content.splice(targetIndex, 0, selComp);
     },
+    clearUnusedComps() {
+      const used = new Set<string>();
+      const getUsedIds = (ids: string[]) => {
+        ids.forEach((id) => {
+          const comp = this.helper.findComp(id);
+          if (!comp) return;
+          used.add(id);
+          getUsedIds(this.helper.getCompChildIds(comp));
+        });
+        return used;
+      };
+      getUsedIds(this.store.designData.content);
+      Object.keys(this.store.designData.compMap).forEach((compId) => {
+        if (!used.has(compId)) {
+          delete this.store.designData.compMap[compId];
+        }
+      });
+    },
   },
 });
-
-function flatCompChildIds(obj: object, ids: string[] = []) {
-  Object.values(obj).forEach((item) => {
-    if (item instanceof Object) {
-      flatCompChildIds(item, ids);
-    } else if (typeof item === "string") {
-      ids.push(item);
-    }
-  });
-  return ids;
-}