feat(plugin): add save_focused_code_editor

This commit is contained in:
Tienson Qin
2022-12-14 11:05:11 +08:00
parent 32b83cb3b5
commit 4a93d27f40
4 changed files with 68 additions and 48 deletions

View File

@@ -131,6 +131,7 @@
[frontend.extensions.calc :as calc]
[frontend.handler.editor :as editor-handler]
[frontend.handler.file :as file-handler]
[frontend.handler.code :as code-handler]
[frontend.state :as state]
[logseq.graph-parser.utf8 :as utf8]
[frontend.util :as util]
@@ -153,47 +154,6 @@
(get (state/get-config)
:editor/extra-codemirror-options {}))
(defn- save-file-or-block!
[editor textarea config state]
(.save editor)
(let [value (gobj/get textarea "value")
default-value (gobj/get textarea "defaultValue")]
(when (not= value default-value)
(cond
(:block/uuid config)
(let [block (db/pull [:block/uuid (:block/uuid config)])
content (:block/content block)
{:keys [start_pos end_pos]} (:pos_meta @(:code-options state))
offset (if (:block/pre-block? block) 0 2)
raw-content (utf8/encode content) ;; NOTE: :pos_meta is based on byte position
prefix (utf8/decode (.slice raw-content 0 (- start_pos offset)))
surfix (utf8/decode (.slice raw-content (- end_pos offset)))
new-content (if (string/blank? value)
(str prefix surfix)
(str prefix value "\n" surfix))]
(state/set-edit-content! (state/get-edit-input-id) new-content)
(editor-handler/save-block-if-changed! block new-content))
(:file-path config)
(let [path (:file-path config)
content (or (db/get-file path) "")]
(when (and
(not (string/blank? value))
(not= (string/trim value) (string/trim content)))
(file-handler/alter-file (state/get-current-repo)
path
(str (string/trim value) "\n")
{:re-render-root? true})))
:else
nil))))
(defn- save-file-or-block-when-blur-or-esc!
[editor textarea config state]
(state/set-state! :editor/skip-saving-current-block? true)
(state/set-block-component-editing-mode! false)
(save-file-or-block! editor textarea config state))
(defn- text->cm-mode
([text]
(text->cm-mode text :name))
@@ -236,7 +196,7 @@
:extraKeys #js {"Esc" (fn [cm]
;; Avoid reentrancy
(gobj/set cm "escPressed" true)
(save-file-or-block-when-blur-or-esc! cm textarea config state)
(code-handler/save-code-editor!)
(when-let [block-id (:block/uuid config)]
(let [block (db/pull [:block/uuid block-id])]
(editor-handler/edit-block! block :max block-id))))}}
@@ -259,10 +219,15 @@
(when (or
(= :file (state/get-current-route))
(not (gobj/get cm "escPressed")))
(save-file-or-block-when-blur-or-esc! editor textarea config state))
(state/set-block-component-editing-mode! false)))
(code-handler/save-code-editor!))
(state/set-block-component-editing-mode! false)
(state/set-state! :editor/code-block-context nil)))
(.on editor "focus" (fn [_e]
(state/set-block-component-editing-mode! true)))
(state/set-block-component-editing-mode! true)
(state/set-state! :editor/code-block-context
{:editor editor
:config config
:state state})))
(.addEventListener element "mousedown"
(fn [e]
(util/stop e)