Skip to content

Commit 3d18750

Browse files
committed
Fix HTML rendering to handle nil values without removing sibling elements; add tests for nil handling in node hierarchy (#15)
1 parent 0863ef2 commit 3d18750

2 files changed

Lines changed: 47 additions & 4 deletions

File tree

src/dompa/nodes.cljc

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@
3838
(let [value (nodes->html-fn (-> node :node/children))]
3939
(str html "<" node-name node-attrs ">" value "</" node-name ">"))))
4040

41-
:else "")))
41+
:else html)))
4242

4343
(defn traverse
4444
"Recursively traverses given tree of `nodes` with a `traverser-fn`
@@ -149,15 +149,18 @@
149149

150150
(defn- nodes-from-opt
151151
[opt]
152-
(cond (map? opt)
152+
(cond (nil? opt)
153+
nil
154+
155+
(map? opt)
153156
opt
154157

155158
(empty-seq? opt)
156159
nil
157160

158161
(list-of-many? opt)
159162
{:node/name :<>
160-
:node/children opt}
163+
:node/children (remove nil? opt)}
161164

162165
(list-of-one? opt)
163166
(first opt)
@@ -176,7 +179,9 @@
176179
children-opts (if attrs? (drop 2 opts) (rest opts))
177180
children-nodes (->> children-opts
178181
(map nodes-from-opt)
179-
flatten)]
182+
flatten
183+
(remove nil?)
184+
vec)]
180185
(cond-> {:node/name first-opt}
181186
attrs? (assoc :node/attrs attrs)
182187
(seq children-nodes) (assoc :node/children children-nodes))))

test/dompa/nodes_test.cljc

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,44 @@
130130
($ x))
131131
["l" "d"])])]))))))
132132

133+
(deftest nil-in-hierarchy-does-not-remove-siblings-test
134+
(testing "nil in a fragment should not remove sibling elements"
135+
(is (= "<div>one</div><div>two</div>"
136+
(nodes/->html
137+
[($ :<>
138+
($ :div "one")
139+
($ :div "two")
140+
nil)]))))
141+
142+
(testing "nil between siblings should not affect them"
143+
(is (= "<div>one</div><div>two</div>"
144+
(nodes/->html
145+
[($ :<>
146+
($ :div "one")
147+
nil
148+
($ :div "two"))]))))
149+
150+
(testing "multiple nils should not affect siblings"
151+
(is (= "<div>one</div><div>two</div><div>three</div>"
152+
(nodes/->html
153+
[($ :<>
154+
nil
155+
($ :div "one")
156+
nil
157+
($ :div "two")
158+
nil
159+
($ :div "three")
160+
nil)]))))
161+
162+
(testing "nil inside nested element should not affect parent siblings"
163+
(is (= "<div><span>hello</span></div><div>world</div>"
164+
(nodes/->html
165+
[($ :<>
166+
($ :div
167+
($ :span "hello")
168+
nil)
169+
($ :div "world"))])))))
170+
133171
(deftest traverse-test
134172
(let [traverser-fn (fn [node]
135173
(if (= :dompa/text (:node/name node))

0 commit comments

Comments
 (0)