code.cljs 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. (ns frontend.handler.code
  2. "Codemirror editor related."
  3. (:require [clojure.string :as string]
  4. [frontend.config :as config]
  5. [frontend.db :as db]
  6. [frontend.handler.editor :as editor-handler]
  7. [frontend.handler.file :as file-handler]
  8. [frontend.state :as state]
  9. [goog.object :as gobj]
  10. [logseq.graph-parser.utf8 :as utf8]
  11. [logseq.common.path :as path]))
  12. (defn save-code-editor!
  13. []
  14. (let [{:keys [config state editor]} (get @state/state :editor/code-block-context)]
  15. (state/set-state! :editor/skip-saving-current-block? true)
  16. (state/set-block-component-editing-mode! false)
  17. (when editor
  18. (.save editor)
  19. (let [textarea (.getTextArea editor)
  20. value (gobj/get textarea "value")
  21. default-value (gobj/get textarea "defaultValue")]
  22. (when (not= value default-value)
  23. (cond
  24. ;; save block content
  25. (:block/uuid config)
  26. (let [block (db/pull [:block/uuid (:block/uuid config)])
  27. content (:block/content block)
  28. {:keys [start_pos end_pos]} (:pos_meta @(:code-options state))
  29. offset (if (:block/pre-block? block) 0 2)
  30. raw-content (utf8/encode content) ;; NOTE: :pos_meta is based on byte position
  31. prefix (utf8/decode (.slice raw-content 0 (- start_pos offset)))
  32. surfix (utf8/decode (.slice raw-content (- end_pos offset)))
  33. new-content (if (string/blank? value)
  34. (str prefix surfix)
  35. (str prefix value "\n" surfix))]
  36. (state/set-edit-content! (state/get-edit-input-id) new-content)
  37. (editor-handler/save-block-if-changed! block new-content))
  38. (not-empty (:file-path config))
  39. (let [path (:file-path config)
  40. repo (state/get-current-repo)
  41. repo-dir (config/get-repo-dir repo)
  42. rpath (path/trim-dir-prefix repo-dir path)
  43. ;; old-content (db/get-file rpath)
  44. _ (prn ::calc rpath)]
  45. (if rpath
  46. ;; in-db file
  47. (let [old-content (db/get-file rpath)]
  48. (when (and
  49. (not (string/blank? value))
  50. (not= (string/trim value) (string/trim old-content)))
  51. (file-handler/alter-file (state/get-current-repo)
  52. rpath
  53. (str (string/trim value) "\n")
  54. {:re-render-root? true})))
  55. ;; global file
  56. (file-handler/alter-global-file path (str (string/trim value) "\n"))))
  57. :else
  58. nil))))))