From 3d18750f03a50e87816cfa234f866cf4cc8f05e9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Asko=20N=C3=B5mm?= Date: Sat, 10 Jan 2026 15:26:52 +0200 Subject: [PATCH] Fix HTML rendering to handle nil values without removing sibling elements; add tests for nil handling in node hierarchy (#15) --- src/dompa/nodes.cljc | 13 +++++++++---- test/dompa/nodes_test.cljc | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 4 deletions(-) diff --git a/src/dompa/nodes.cljc b/src/dompa/nodes.cljc index eef65d3..e717690 100644 --- a/src/dompa/nodes.cljc +++ b/src/dompa/nodes.cljc @@ -38,7 +38,7 @@ (let [value (nodes->html-fn (-> node :node/children))] (str html "<" node-name node-attrs ">" value "")))) - :else ""))) + :else html))) (defn traverse "Recursively traverses given tree of `nodes` with a `traverser-fn` @@ -149,7 +149,10 @@ (defn- nodes-from-opt [opt] - (cond (map? opt) + (cond (nil? opt) + nil + + (map? opt) opt (empty-seq? opt) @@ -157,7 +160,7 @@ (list-of-many? opt) {:node/name :<> - :node/children opt} + :node/children (remove nil? opt)} (list-of-one? opt) (first opt) @@ -176,7 +179,9 @@ children-opts (if attrs? (drop 2 opts) (rest opts)) children-nodes (->> children-opts (map nodes-from-opt) - flatten)] + flatten + (remove nil?) + vec)] (cond-> {:node/name first-opt} attrs? (assoc :node/attrs attrs) (seq children-nodes) (assoc :node/children children-nodes)))) diff --git a/test/dompa/nodes_test.cljc b/test/dompa/nodes_test.cljc index b1c7b0f..da9b7db 100644 --- a/test/dompa/nodes_test.cljc +++ b/test/dompa/nodes_test.cljc @@ -130,6 +130,44 @@ ($ x)) ["l" "d"])])])))))) +(deftest nil-in-hierarchy-does-not-remove-siblings-test + (testing "nil in a fragment should not remove sibling elements" + (is (= "
one
two
" + (nodes/->html + [($ :<> + ($ :div "one") + ($ :div "two") + nil)])))) + + (testing "nil between siblings should not affect them" + (is (= "
one
two
" + (nodes/->html + [($ :<> + ($ :div "one") + nil + ($ :div "two"))])))) + + (testing "multiple nils should not affect siblings" + (is (= "
one
two
three
" + (nodes/->html + [($ :<> + nil + ($ :div "one") + nil + ($ :div "two") + nil + ($ :div "three") + nil)])))) + + (testing "nil inside nested element should not affect parent siblings" + (is (= "
hello
world
" + (nodes/->html + [($ :<> + ($ :div + ($ :span "hello") + nil) + ($ :div "world"))]))))) + (deftest traverse-test (let [traverser-fn (fn [node] (if (= :dompa/text (:node/name node))