file.cljs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. (ns frontend.modules.outliner.file
  2. (:require [clojure.core.async :as async]
  3. [clojure.string :as string]
  4. [frontend.config :as config]
  5. [frontend.db :as db]
  6. [frontend.db.model :as model]
  7. [frontend.handler.notification :as notification]
  8. [frontend.modules.file.core :as file]
  9. [frontend.modules.outliner.tree :as tree]
  10. [frontend.util :as util]
  11. [goog.object :as gobj]
  12. [lambdaisland.glogi :as log]
  13. [frontend.state :as state]))
  14. (defonce write-chan (async/chan 100))
  15. (defonce write-chan-batch-buf (atom []))
  16. (def batch-write-interval 1000)
  17. (defn writes-finished?
  18. []
  19. (empty? @write-chan-batch-buf))
  20. (defn do-write-file!
  21. [repo page-db-id]
  22. (let [page-block (db/pull repo '[*] page-db-id)
  23. page-db-id (:db/id page-block)
  24. blocks (model/get-page-blocks-no-cache repo (:block/name page-block))]
  25. (when-not (and (= 1 (count blocks))
  26. (string/blank? (:block/content (first blocks)))
  27. (nil? (:block/file page-block)))
  28. (let [tree (tree/blocks->vec-tree repo blocks (:block/name page-block))]
  29. (if page-block
  30. (file/save-tree page-block tree)
  31. (js/console.error (str "can't find page id: " page-db-id)))))))
  32. (defn write-files!
  33. [pages]
  34. (when (seq pages)
  35. (when-not config/publishing?
  36. (doseq [[repo page-id] (set pages)]
  37. (try (do-write-file! repo page-id)
  38. (catch js/Error e
  39. (notification/show!
  40. [:div
  41. [:p "Write file failed, please copy the changes to other editors in case of losing data."]
  42. "Error: " (str (gobj/get e "stack"))]
  43. :error)
  44. (log/error :file/write-file-error {:error e})))))))
  45. (defn sync-to-file
  46. [{page-db-id :db/id}]
  47. (if (nil? page-db-id)
  48. (notification/show!
  49. "Write file failed, can't find the current page!"
  50. :error)
  51. (when-let [repo (state/get-current-repo)]
  52. (async/put! write-chan [repo page-db-id]))))
  53. (util/batch write-chan
  54. batch-write-interval
  55. write-files!
  56. write-chan-batch-buf)