Browse Source

fix(editor): pasted template had chaotic orders

rcmerci 4 years ago
parent
commit
4d2c5f05a6

+ 7 - 2
src/main/frontend/handler/editor.cljs

@@ -1862,8 +1862,13 @@
           block-uuid (:block/uuid block)
           including-parent? (not (false? (:including-parent (:block/properties block))))
           blocks (if including-parent? (db/get-block-and-children repo block-uuid) (db/get-block-children repo block-uuid))
-          level-blocks-map (blocks-with-level blocks)
-          tree (blocks-vec->tree (vals level-blocks-map))]
+          level-blocks (vals (blocks-with-level blocks))
+          grouped-blocks (group-by #(= db-id (:db/id %)) level-blocks)
+          root-block (or (first (get grouped-blocks true)) (assoc (db/pull db-id) :level 0))
+          blocks-exclude-root (get grouped-blocks false)
+          sorted-blocks (tree/sort-blocks blocks-exclude-root root-block)
+          result-blocks (if including-parent? sorted-blocks (drop 1 sorted-blocks))
+          tree (blocks-vec->tree result-blocks)]
       (paste-block-tree-at-point tree [:template :including-parent]
                                  (fn [content]
                                    (->> content

+ 16 - 0
src/main/frontend/modules/outliner/tree.cljs

@@ -76,3 +76,19 @@
       (let [root-block (some #(when (= (:db/id %) (:db/id root)) %) @blocks)
             root-block (with-children-and-refs root-block result)]
         [root-block]))))
+
+(defn sort-blocks-aux
+  [parents parent-groups]
+  (mapv (fn [parent]
+          (let [parent-id {:db/id (:db/id parent)}
+                children (db/sort-by-left (get @parent-groups parent-id) parent)
+                _ (swap! parent-groups #(dissoc % parent-id))
+                sorted-nested-children (when (not-empty children) (sort-blocks-aux children parent-groups))]
+                    (if sorted-nested-children [parent sorted-nested-children] [parent])))
+        parents))
+
+(defn sort-blocks
+  "sort blocks by parent & left"
+  [blocks-exclude-root root]
+  (let [parent-groups (atom (group-by #(:block/parent %) blocks-exclude-root))]
+    (flatten (concat (sort-blocks-aux [root] parent-groups) (vals @parent-groups)))))