From 723a202faa4cca02dfdd575d85a8a3adeb23625a Mon Sep 17 00:00:00 2001 From: Tienson Qin Date: Thu, 20 Jan 2022 12:44:40 +0800 Subject: [PATCH] fix: caret-range should include newlines --- src/main/frontend/util.cljc | 31 +++++++++++++++++++++++++------ 1 file changed, 25 insertions(+), 6 deletions(-) diff --git a/src/main/frontend/util.cljc b/src/main/frontend/util.cljc index e85727f26..38cb2210b 100644 --- a/src/main/frontend/util.cljc +++ b/src/main/frontend/util.cljc @@ -337,6 +337,16 @@ (apply f args)) threshold))))))) +(defn nth-safe [c i] + (if (or (< i 0) (>= i (count c))) + nil + (nth c i))) + +#?(:cljs + (extend-type js/NodeList + ISeqable + (-seq [array] (array-seq array 0)))) + ;; Caret #?(:cljs (defn caret-range [node] @@ -355,7 +365,21 @@ (.setEnd pre-caret-range (gobj/get range "endContainer") (gobj/get range "endOffset")) - (.toString pre-caret-range)))) + (let [contents (.cloneContents pre-caret-range) + html (some-> (first (.-childNodes contents)) + (gobj/get "innerHTML") + str) + ;; FIXME: this depends on the dom structure, + ;; need a converter from html to text includes newlines + br-ended? (or + ;; first line with a new line + (string/ends-with? html "
") + ;; multiple lines with a new line + (string/ends-with? html "
")) + value (.toString pre-caret-range)] + (if br-ended? + (str value "\n") + value))))) (when-let [selection (gobj/get doc "selection")] (when (not= "Control" (gobj/get selection "type")) (let [text-range (.createRange selection) @@ -997,11 +1021,6 @@ (when section (gdom/getElement section "id")))))) -(defn nth-safe [c i] - (if (or (< i 0) (>= i (count c))) - nil - (nth c i))) - #?(:cljs (defn get-prev-block-non-collapsed [block]