Skip to content

Commit

Permalink
move text bounds to element
Browse files Browse the repository at this point in the history
  • Loading branch information
sprocketc committed Oct 30, 2023
1 parent 2a85d58 commit 724188e
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 28 deletions.
25 changes: 25 additions & 0 deletions src/renderer/tools/element.cljs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,31 @@
(history/finalize (str "Create " (name (:tag temp-element))))
(assoc :cursor "crosshair"))))

(defn get-bounds
"Experimental way of getting the bounds of uknown or complicated elements
using the getBBox method.
https://developer.mozilla.org/en-US/docs/Web/API/SVGGraphicsElement/getBBox"
[element]
(let [bounds (.getBBox element)
x1 (.-x bounds)
y1 (.-y bounds)
x2 (+ x1 (.-width bounds))
y2 (+ y1 (.-height bounds))]
[x1 y1 x2 y2]))

(defmethod tools/bounds ::tools/element
[{:keys [tag attrs content]}]
(when-let [frame (.getElementById js/document "frame")]
(when-let [svg (.getElementById (.. frame -contentWindow -document) "canvas")]
(let [element (js/document.createElementNS "http://www.w3.org/2000/svg" (name tag))]
(doseq [[key value] attrs]
(.setAttributeNS element nil (name key) value))
(.appendChild svg element)
(set! (.-innerHTML element) (if (empty? content) "\u00a0" content))
(let [bounds (get-bounds element)]
(.remove element)
bounds)))))

(defmethod tools/mouse-up :default
[db event element]
(if-not (and (= (:button event) 2)
Expand Down
29 changes: 1 addition & 28 deletions src/renderer/tools/text.cljs
Original file line number Diff line number Diff line change
Expand Up @@ -126,31 +126,4 @@
content
(js/parseFloat (:x attrs))
(js/parseFloat (:y attrs))
(js/parseFloat (or (:font-size attrs) 16))))

(defn get-bounds
"Experimental way of getting the bounds of uknown or complicated elements
using the getBBox method.
https://developer.mozilla.org/en-US/docs/Web/API/SVGGraphicsElement/getBBox"
[element textLength]
(let [bounds (.getBBox element)
x1 (.-x bounds)
y1 (.-y bounds)
x2 (+ x1 (if (zero? textLength) (.-width bounds) textLength))
y2 (+ y1 (.-height bounds))]
[x1 y1 x2 y2]))

(defmethod tools/bounds :text
[{:keys [attrs content]}]
(when-let [frame (.getElementById js/document "frame")]
(when-let [svg (.getElementById (.. frame -contentWindow -document) "canvas")]
(let [text-tag (js/document.createElementNS "http://www.w3.org/2000/svg" "text")]
(doseq [[key value] attrs]
(.setAttributeNS text-tag nil (name key) value))
(.appendChild svg text-tag)
(set! (.-innerHTML text-tag) (if (empty? content) "\u00a0" content))
(let [{:keys [textLength]} attrs
textLength (units/unit->px textLength)
bounds (get-bounds text-tag textLength)]
(.remove text-tag)
bounds)))))
(js/parseFloat (or (:font-size attrs) 16))))

0 comments on commit 724188e

Please sign in to comment.