From 5149503b96d5839bcdf9f142563760d6446b11b8 Mon Sep 17 00:00:00 2001 From: Akil Harris Date: Wed, 15 Jul 2015 22:23:35 -0400 Subject: [PATCH] Uses CSSStyleDeclarations to get styles instead of parsing style string. --- src/cljs/domina.cljs | 32 +++++++++++++++----------------- test/cljs/domina/test.cljs | 8 ++++++++ 2 files changed, 23 insertions(+), 17 deletions(-) diff --git a/src/cljs/domina.cljs b/src/cljs/domina.cljs index e7a8efa..fe9bb9a 100644 --- a/src/cljs/domina.cljs +++ b/src/cljs/domina.cljs @@ -241,29 +241,27 @@ content) ;; We don't use the existing style/parseStyleAttributes because it camelcases everything. -;; This uses the same technique, however. (defn parse-style-attributes - "Parses a CSS style string and returns the properties as a map." + "Returns a map of a single css name/value pair." [style] - (reduce (fn [acc pair] - (let [[k v] (. pair split #"\s*:\s*")] - (if (and k v) - (assoc acc (keyword (. k (toLowerCase))) v) - acc))) - {} - (. style split #"\s*;\s*"))) + (let [length (.-length style)] + (apply merge (map + (fn [i] + (let [name (.item style i) + value (.getPropertyValue style name) + priority (.getPropertyPriority style name)] + (if (= "" priority) {(keyword name) value} {(keyword name) (str value " " priority)}))) + (range length))))) + (defn styles "Returns a map of the CSS styles/values. Assumes content will be a single node. Style names are returned as keywords." [content] - (let [style (attr content "style")] - (cond (string? style) - (parse-style-attributes style) - (nil? style) - {} - (. style -cssText) - (parse-style-attributes (. style -cssText)) - :else {}))) + (let [style (.-style (single-node content)) + length (.-length style)] + (cond + (pos? length) (parse-style-attributes style) + :else {}))) (defn attrs "Returns a map of the HTML attributes/values. Assumes content will be a single node. Attribute names are returned as keywords." diff --git a/test/cljs/domina/test.cljs b/test/cljs/domina/test.cljs index 0ebe5e1..7501753 100644 --- a/test/cljs/domina/test.cljs +++ b/test/cljs/domina/test.cljs @@ -428,6 +428,14 @@ (assert (= {} (styles (xpath "//div")))))) +(add-test "can get CSS styles with ':' in property from a single node." + #(do (reset) + (append! (xpath "//body") "
1
") + (set-style! (xpath "//div") "background-image" "url(http://www.some-site.com:8088/image.jpg)") + (set-style! (xpath "//div") "background-color" "black") + (assert (= {:background-image "url(http://www.some-site.com:8088/image.jpg)" :background-color "black"} + (styles (xpath "//div")))))) + (add-test "can get multiple HTML attributes from a single node." #(do (reset) (append! (xpath "//body") "
1
")