From e0d134d899471148a08a85ff2cccc3e27a381b90 Mon Sep 17 00:00:00 2001 From: Michiel Borkent Date: Fri, 11 Oct 2024 20:22:20 +0200 Subject: [PATCH] Less dynamic HTML css (#560) --- src/squint/compiler_common.cljc | 37 ++++++++++++++++++++------------- src/squint/html.js | 7 ++++--- test/squint/html_test.cljs | 2 +- 3 files changed, 27 insertions(+), 19 deletions(-) diff --git a/src/squint/compiler_common.cljc b/src/squint/compiler_common.cljc index 963f1d9d..42e7d350 100644 --- a/src/squint/compiler_common.cljc +++ b/src/squint/compiler_common.cljc @@ -140,12 +140,7 @@ (if html? "$" "") - (format (if (:html-attr env) - "squint_html.attr(%s)" - "%s" #_(if html? - "squint_html._safe(%s)" - "%s")) - expr))) + expr)) expr))) (defmethod emit ::number [expr env] @@ -1046,15 +1041,27 @@ break;}" body) (defn emit-css [v env] - (let [env (assoc env :html-attr true)] - (-> (reduce - (fn [acc [k v]] - (str acc - (emit k env) ":" - (emit v env) ";")) - "" - v) - (wrap-double-quotes)))) + (if (contains? v :&) + (let [rest-opts (dissoc v :&) + env (assoc env :js true) + cherry? (= :cherry *target*)] + (when-let [dyn (:has-dynamic-expr env)] + (reset! dyn true)) + (-> (format "${squint_html.css(%s,%s)}" + (emit (cond->> (get v :&) + cherry? (list `clj->js)) (dissoc env :jsx)) + (emit (cond->> rest-opts + cherry? (list `clj->js)) (dissoc env :jsx))) + (wrap-double-quotes))) + (let [env (assoc env :html-attr true)] + (-> (reduce + (fn [acc [k v]] + (str acc + (emit k env) ":" + (emit v env) ";")) + "" + v) + (wrap-double-quotes))))) (defn jsx-attrs [v env] (let [env (expr-env env) diff --git a/src/squint/html.js b/src/squint/html.js index 561e8d65..8abb1b0e 100644 --- a/src/squint/html.js +++ b/src/squint/html.js @@ -32,7 +32,8 @@ function safe(x) { return escapeHTML(x.toString()); } -function css(v) { +export function css(v, props) { + v = Object.assign(props, v); let ret = ""; if (v == null) return ret; let first = true; @@ -47,9 +48,9 @@ function css(v) { return ret; } -export function attr(v) { +function attr(v) { if (typeof(v) === 'object') { - return css(v); + return css({}, v); } else { return v; diff --git a/test/squint/html_test.cljs b/test/squint/html_test.cljs index fc2edbbd..e16d88bb 100644 --- a/test/squint/html_test.cljs +++ b/test/squint/html_test.cljs @@ -70,7 +70,7 @@ (deftest html-dynamic-css-test (t/async done (let [js (squint.compiler/compile-string - "(let [m {:color :green}] #html [:div {:style (assoc m :width \"200\")} \"Hello\"])" + "(let [m {:color :green} m (assoc m :width \"200\")] #html [:div {:style {:& m}} \"Hello\"])" {:repl true :elide-exports true :context :return}) js (str/replace "(async function() { %s } )()" "%s" js)] (-> (js/eval js)