Skip to content

Commit

Permalink
fix(code): avoid calling saving handler too often
Browse files Browse the repository at this point in the history
  • Loading branch information
andelf committed Mar 14, 2022
1 parent acc5a62 commit 5525305
Showing 1 changed file with 15 additions and 9 deletions.
24 changes: 15 additions & 9 deletions src/main/frontend/extensions/code.cljs
Original file line number Diff line number Diff line change
Expand Up @@ -150,9 +150,10 @@
(get (state/get-config)
:editor/extra-codemirror-options {}))

(defn- save-file-or-block-when-blur-or-esc!
(defn- save-file-or-block!
[editor textarea config state]
(.save editor)
(prn :saving-code)
(let [value (gobj/get textarea "value")
default-value (gobj/get textarea "defaultValue")]
(when (not= value default-value)
Expand All @@ -168,6 +169,7 @@
new-content (if (string/blank? value)
(str prefix surfix)
(str prefix value "\n" surfix))]
(prn :saving new-content)
(editor-handler/save-block-if-changed! block new-content))

(:file-path config)
Expand All @@ -187,6 +189,15 @@
:else
nil))))

;; Avoid reentrancy
(def *code-saving (atom false))
(defn save-file-or-block-when-blur-or-esc!
[editor textarea config state]
(when-not @*code-saving
(reset! *code-saving true)
(save-file-or-block! editor textarea config state)
(reset! *code-saving false)))

(defn- text->cm-mode
([text]
(text->cm-mode text :name))
Expand All @@ -206,8 +217,7 @@

(defn render!
[state]
(let [esc-pressed? (atom nil)
[config id attr _code theme] (:rum/args state)
(let [[config id attr _code theme] (:rum/args state)
default-open? (and (:editor/code-mode? @state/state)
(= (:block/uuid (state/get-edit-block))
(get-in config [:block :block/uuid])))
Expand All @@ -228,13 +238,10 @@
{:mode mode
:extraKeys #js {"Esc"
(fn [cm]
(reset! esc-pressed? true)
(save-file-or-block-when-blur-or-esc! cm textarea config state)
(when-let [block-id (:block/uuid config)]
(let [block (db/pull [:block/uuid block-id])]
(editor-handler/edit-block! block :max block-id)))
;; TODO: return "handled" or false doesn't always prevent event bubbles
(js/setTimeout #(reset! esc-pressed? false) 10))}})
(editor-handler/edit-block! block :max block-id))))}})
editor (when textarea
(from-textarea textarea (clj->js cm-options)))]
(when editor
Expand All @@ -248,8 +255,7 @@
(.on editor "blur" (fn [_cm e]
(when e (util/stop e))
(state/set-block-component-editing-mode! false)
(when-not @esc-pressed?
(save-file-or-block-when-blur-or-esc! editor textarea config state))))
(save-file-or-block-when-blur-or-esc! editor textarea config state)))
(.addEventListener element "mousedown"
(fn [e]
(state/clear-selection!)
Expand Down

0 comments on commit 5525305

Please sign in to comment.