datascript.cljc 3.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. (ns frontend.modules.outliner.datascript
  2. #?(:clj (:require [clojure.core :as core]))
  3. #?(:cljs (:require-macros [frontend.modules.outliner.datascript]))
  4. #?(:cljs (:require [datascript.core :as d]
  5. [frontend.db.conn :as conn]
  6. [frontend.modules.outliner.pipeline :as pipelines]
  7. [frontend.modules.editor.undo-redo :as undo-redo]
  8. [frontend.state :as state]
  9. [frontend.config :as config]
  10. [logseq.graph-parser.util :as gp-util]
  11. [lambdaisland.glogi :as log]
  12. [frontend.search :as search])))
  13. #?(:cljs
  14. (defn new-outliner-txs-state [] (atom [])))
  15. #?(:cljs
  16. (defn outliner-txs-state?
  17. [state]
  18. (and
  19. (instance? cljs.core/Atom state)
  20. (coll? @state))))
  21. #?(:cljs
  22. (defn after-transact-pipelines
  23. [repo {:keys [_db-before _db-after _tx-data _tempids tx-meta] :as tx-report}]
  24. (when-not config/test?
  25. (pipelines/invoke-hooks tx-report)
  26. (when (:outliner/transact? tx-meta)
  27. (undo-redo/listen-outliner-operation tx-report))
  28. (search/sync-search-indice! repo tx-report))))
  29. #?(:cljs
  30. (defn- remove-nil-from-transaction
  31. [txs]
  32. (some->> (gp-util/remove-nils txs)
  33. (map (fn [x]
  34. (if (map? x)
  35. (update-vals x (fn [v]
  36. (if (vector? v)
  37. (remove nil? v)
  38. v)))
  39. x))))))
  40. #?(:cljs
  41. (defn transact!
  42. [txs opts]
  43. (let [txs (remove-nil-from-transaction txs)
  44. txs (map (fn [m] (if (map? m)
  45. (dissoc m
  46. :block/children :block/meta :block/top? :block/bottom? :block/anchor
  47. :block/title :block/body :block/level :block/container :db/other-tx)
  48. m)) txs)]
  49. (when (and (seq txs)
  50. (not (:skip-transact? opts)))
  51. ;; (frontend.util/pprint txs)
  52. (try
  53. (let [repo (get opts :repo (state/get-current-repo))
  54. conn (conn/get-db repo false)
  55. editor-cursor (state/get-current-edit-block-and-position)
  56. meta (merge opts {:editor-cursor editor-cursor})
  57. rs (d/transact! conn txs (assoc meta :outliner/transact? true))]
  58. (when true ; TODO: add debug flag
  59. (let [eids (distinct (mapv first (:tx-data rs)))
  60. left&parent-list (->>
  61. (d/q '[:find ?e ?l ?p
  62. :in $ [?e ...]
  63. :where
  64. [?e :block/left ?l]
  65. [?e :block/parent ?p]] @conn eids)
  66. (vec)
  67. (map next))]
  68. (assert (= (count left&parent-list) (count (distinct left&parent-list))) eids)))
  69. rs)
  70. (catch js/Error e
  71. (log/error :exception e)
  72. (throw e)))))))