code.cljs 3.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. [frontend.handler.db-based.editor :as db-editor-handler]))
  13. (defn save-code-editor!
  14. []
  15. (let [{:keys [config state editor]} (get @state/state :editor/code-block-context)]
  16. (state/set-state! :editor/skip-saving-current-block? true)
  17. (state/set-block-component-editing-mode! false)
  18. (when editor
  19. (.save editor)
  20. (let [textarea (.getTextArea editor)
  21. ds (.-dataset textarea)
  22. value (gobj/get textarea "value")
  23. default-value (or (.-v ds) (gobj/get textarea "defaultValue"))
  24. repo (state/get-current-repo)]
  25. (when (not= value default-value)
  26. ;; update default value for the editor initial state
  27. (set! ds -v value)
  28. (cond
  29. ;; save block content
  30. (:block/uuid config)
  31. (let [block (db/pull [:block/uuid (:block/uuid config)])
  32. content (:block/content block)
  33. {:keys [start_pos end_pos]} (:pos_meta @(:code-options state))
  34. offset (if (:block/pre-block? block) 0 2)
  35. raw-content (utf8/encode content) ;; NOTE: :pos_meta is based on byte position
  36. prefix (utf8/decode (.slice raw-content 0 (- start_pos offset)))
  37. surfix (utf8/decode (.slice raw-content (- end_pos offset)))
  38. new-content (if (string/blank? value)
  39. (str prefix surfix)
  40. (str prefix value "\n" surfix))]
  41. (state/set-edit-content! (state/get-edit-input-id) new-content)
  42. (editor-handler/save-block-if-changed! block new-content))
  43. (and (not-empty (:file-path config))
  44. (config/db-based-graph? repo))
  45. (db-editor-handler/save-file! (:file-path config) value)
  46. (not-empty (:file-path config))
  47. (let [path (:file-path config)
  48. repo-dir (config/get-repo-dir repo)
  49. rpath (when (string/starts-with? path repo-dir)
  50. (path/trim-dir-prefix repo-dir path))]
  51. (if rpath
  52. ;; in-db file
  53. (let [db-content (db/get-file rpath)
  54. not-in-db? (nil? db-content)
  55. old-content (or db-content "")
  56. contents-matched? (= (string/trim value) (string/trim old-content))]
  57. (when (or
  58. (and not-in-db? (not-empty value))
  59. (not contents-matched?))
  60. (file-handler/alter-file (state/get-current-repo)
  61. rpath
  62. (str (string/trim value) "\n")
  63. {:re-render-root? true})))
  64. ;; global file
  65. (file-handler/alter-global-file path (str (string/trim value) "\n") {})))
  66. :else
  67. nil))))))