From 3d6c2f5e3f9a67d1adb839553ce5b74003b7ef96 Mon Sep 17 00:00:00 2001 From: "Howard M. Lewis Ship" Date: Thu, 18 Jun 2015 18:05:21 -0700 Subject: [PATCH] Implement nested Hiccup elements --- CHANGELOG.md | 4 +++ src/reagent/impl/template.cljs | 48 +++++++++++++++++++++++++++++----- 2 files changed, 45 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2743139..3931034 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,10 @@ # Changelog +## 0.5.1 + +- Hiccup syntax has been extended to allow nested elements to be defined using '>' as part of the keyword name. + ## 0.5.0 - React updated to 0.12.2 diff --git a/src/reagent/impl/template.cljs b/src/reagent/impl/template.cljs index fa2d8b0..e8456a3 100644 --- a/src/reagent/impl/template.cljs +++ b/src/reagent/impl/template.cljs @@ -226,17 +226,51 @@ jsprops)] (make-element argv comp p first-child))))))) +(defn- expand-tags + "Used to supported the extended Hiccup syntax for nested elements. In addition to the keyword + specifying tag, optional id, and optional class(es), the '>' character indicates a nested element. + + e.g. + + [:nav.navbar>div.container>div.navbar-header>a.navbar-brand {:href \"...\"} \"Home\"] + + is the same as: + + [:nav.navbar [:div.container [:div.navbar-header [:a.navbar-bran {:href \"...\"} \"Home\"]]]] + + tags - the original keyword split at '>' + hiccup-form - the original hiccup form (a keyword in the first position)" + [tags hiccup-form] + (loop [deepest? true + [tag & tag-queue] (reverse tags) + tail (rest hiccup-form)] + (if (nil? tag) + tail + (recur false + tag-queue + (if deepest? + (into [(keyword tag)] tail) + [(keyword tag) tail]))))) + (defn vec-to-elem [v] (assert (pos? (count v)) (str "Hiccup form should not be empty: " (pr-str v) (comp/comp-name))) - (let [tag (nth v 0)] - (assert (valid-tag? tag) - (str "Invalid Hiccup form: " - (pr-str v) (comp/comp-name))) - (if-some [ne (native-element tag v)] - ne - (reag-element tag v)))) + (let [tag (nth v 0) + tags (do + (assert (valid-tag? tag) + (str "Invalid Hiccup form: " + (pr-str v) (comp/comp-name))) + (if (keyword? tag) + (-> tag + name + (string/split #">") + vec)))] + (if (< 1 (count tags)) + (recur (expand-tags tags v)) + (if-some [ne (native-element tag v)] + ne + (reag-element tag v))))) (declare expand-seq) (declare expand-seq-check)