summaryrefslogtreecommitdiff
path: root/src/dompa/templates.cljc
blob: 21ce8f913f58c030cf4814a8755affac1c9a02a4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
(ns dompa.templates
  (:require [dompa.nodes :as nodes]))

(defmacro defhtml
  [name & args-and-elements]
  (let [[args & elements] args-and-elements]
    `(defn ~name ~args
       (nodes/->html (vector ~@elements)))))

(defn ->flat-xf []
  (fn [rf]
    (letfn [(step [result input]
              (if (sequential? input)
                (reduce step result input)
                (rf result input)))]
      (fn
        ([] (rf))
        ([result] (rf result))
        ([result input] (step result input))))))

(defn ->flat [children]
  (into [] (->flat-xf) children))

(defmacro $
  [name & opts]
  `(if (string? ~name)
     {:node/name  :dompa/text
      :node/value (str ~name ~@opts)}
     (let [opts# (list ~@opts)
           first-opt# (first opts#)
           attrs?# (and (map? first-opt#)
                        (not (contains? first-opt# :node/name)))
           attrs# (if attrs?# first-opt# {})
           children# (if attrs?# (rest opts#) opts#)]
       (cond-> {:node/name ~name}
               attrs?# (assoc :node/attrs attrs#)
               (seq children#) (assoc :node/children (->flat children#))))))

(defhtml test-page []
  (let [n 123]
    ($ :<>
      ($ :div
        ($ "hello world" n))
      ($ "hello")
      ($ :div))))

(test-page)