add fragment to interpreter

This commit is contained in:
roman01la
2021-03-05 18:11:46 +02:00
parent e93c85444e
commit 604d3d5f6c
5 changed files with 27 additions and 10 deletions

View File

@ -52,12 +52,6 @@
(declare to-js to-js-map)
(defn fragment?
"Returns true if `tag` is the fragment tag \"*\" or \"<>\", otherwise false."
[tag]
(or (= (name tag) "*")
(= (name tag) "<>")))
(defmulti compile-attr (fn [name value] name))
(defmethod compile-attr :class [_ value]

View File

@ -39,13 +39,20 @@
(attributes attrs)
(interpret-seq content))))
(defn fragment [[type attrs & children]]
(let [[attrs children] (if (map? attrs)
[(attributes attrs) (interpret-seq children)]
[nil (interpret-seq (into [attrs] children))])]
(create-element js/React.Fragment attrs children)))
(defn- interpret-vec
"Interpret the vector `x` as an HTML element or a the children of an
element."
[x]
(if (util/element? x)
(element x)
(interpret-seq x)))
(cond
(util/fragment? (nth x 0 nil)) (fragment x)
(util/element? x) (element x)
:else (interpret-seq x)))
(defn interpret [v]
(cond

View File

@ -46,6 +46,12 @@
(update :style camel-case-keys)))
m))
(defn fragment?
"Returns true if `tag` is the fragment tag \"*\" or \"<>\", otherwise false."
[tag]
(or (= (name tag) "*")
(= (name tag) "<>")))
(defn element?
"Return true if `x` is an HTML element. True when `x` is a vector
and the first element is a keyword, e.g. `[:div]` or `[:div [:span \"x\"]`."

View File

@ -434,7 +434,7 @@
[attrs & children]
(let [[attrs children] (if (map? attrs)
[attrs children]
[nil (concat [attrs] children)])]
[nil (into [attrs] children)])]
(if-not (:ns &env)
`(list ~@children)
`(.createElement js/React

View File

@ -78,3 +78,13 @@
(is (= "div" (.. c2 -type)))
(is (= "!Pixel Scout" (.. c2 -props -children)))))
(deftest test-fragment
(let [el (interpret [:<> 1 2])]
(is (= js/React.Fragment (.. el -type)))
(is (= 1 (aget (.. el -props -children) 0)))
(is (= 2 (aget (.. el -props -children) 1))))
(let [el (interpret [:<> {:key 11} 1 2])]
(is (= js/React.Fragment (.. el -type)))
(is (= "11" (.-key el)))
(is (= 1 (aget (.. el -props -children) 0)))
(is (= 2 (aget (.. el -props -children) 1)))))