From ed4cf4e38921b349131c6f6a25129f08d6247013 Mon Sep 17 00:00:00 2001 From: Dan Holmsand Date: Tue, 11 Feb 2014 11:36:58 +0100 Subject: [PATCH] Allow component functions to be anything that satisfies ifn? --- src/reagent/impl/component.cljs | 20 ++++++++++++++------ src/reagent/impl/template.cljs | 2 +- test/testcloact.cljs | 8 ++++++++ 3 files changed, 23 insertions(+), 7 deletions(-) diff --git a/src/reagent/impl/component.cljs b/src/reagent/impl/component.cljs index 6107e61..69dfe8b 100644 --- a/src/reagent/impl/component.cljs +++ b/src/reagent/impl/component.cljs @@ -56,7 +56,7 @@ (defn do-render [C] (binding [*current-component* C] (let [f (aget C cljs-render) - _ (assert (fn? f)) + _ (assert (ifn? f)) p (js-props C) res (if (nil? (aget C "componentFunction")) (f C) @@ -71,7 +71,7 @@ (apply f (subvec argv 1)))))] (if (vector? res) (tmpl/as-component res (aget p cljs-level)) - (if (fn? res) + (if (ifn? res) (do (aset C cljs-render res) (do-render C)) @@ -129,7 +129,7 @@ nil)) (defn default-wrapper [f] - (if (fn? f) + (if (ifn? f) (fn [& args] (this-as C (apply f C args))) f)) @@ -142,7 +142,7 @@ (aset "__reactDontBind" true)) (let [wrap (custom-wrapper key f)] (when (and wrap f) - (assert (fn? f) + (assert (ifn? f) (str "Expected function in " name key " but got " f))) (or wrap (default-wrapper f))))) @@ -168,7 +168,9 @@ (defn wrap-funs [fun-map] (let [render-fun (or (:componentFunction fun-map) (:render fun-map)) - _ (assert (ifn? render-fun)) + _ (assert (ifn? render-fun) + (str "Render must be a function, not " + (pr-str render-fun))) name (or (:displayName fun-map) (.-displayName render-fun) (.-name render-fun)) @@ -179,12 +181,18 @@ (into {} (for [[k v] fmap] [k (get-wrapper k v name')])))) +(defn map-to-js [m] + (reduce-kv (fn [o k v] + (doto o + (aset (name k) v))) + #js {} m)) + (defn cljsify [body] (-> body camelify-map-keys add-obligatory wrap-funs - clj->js)) + map-to-js)) (defn create-class [body] diff --git a/src/reagent/impl/template.cljs b/src/reagent/impl/template.cljs index 7446eff..47dcb2d 100644 --- a/src/reagent/impl/template.cljs +++ b/src/reagent/impl/template.cljs @@ -209,7 +209,7 @@ (assert (pos? (count v)) "Hiccup form should not be empty") (assert (let [tag (v 0)] (or (keyword? tag) - (fn? tag))) + (ifn? tag))) (str "Invalid Hiccup form: " (pr-str v))) (let [props (get v 1) c (as-class (v 0)) diff --git a/test/testcloact.cljs b/test/testcloact.cljs index 9a572c1..831c582 100644 --- a/test/testcloact.cljs +++ b/test/testcloact.cljs @@ -276,3 +276,11 @@ (is (re-find #"id=.foo" (as-string [:div#bar {:id "foo"}])) "Dynamic id overwrites static")) + +(deftest ifn-component [] + (let [comp {:foo [:div "foodiv"] + :bar [:div "bardiv"]}] + (is (re-find #"foodiv" + (as-string [:div [comp :foo]]))) + (is (re-find #"bardiv" + (as-string [:div [comp :bar]])))))