-
Notifications
You must be signed in to change notification settings - Fork 0
/
attrs.cljc
58 lines (47 loc) · 1.39 KB
/
attrs.cljc
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
48
49
50
51
52
53
54
55
56
57
58
(ns mayu.dom.to-string.attrs
(:require [clojure.string :as str]))
;; ported to from hiccup
;; https://github.com/weavejester/hiccup
(defprotocol AsString
(to-str [x] "Convert a value into a string."))
(extend-protocol AsString
#?(:clj java.lang.String :cljs string)
(to-str [s] s)
#?(:clj clojure.lang.Keyword :cljs cljs.core.Keyword)
(to-str [k] (name k))
nil
(to-str [_] ""))
(defn as-str
"Converts its arguments into a string using [[to-str]]."
[& xs]
(apply str (map to-str xs)))
(defn- escape-html
"Change special characters into HTML character entities."
[text]
(.. (as-str text)
(replace "&" "&")
(replace "<" "<")
(replace ">" ">")
(replace "\"" """)
(replace "'" "'")))
(defn- render-style-map [value]
(->> value
(map (fn [[k v]] (str (as-str k) ":" v ";")))
(sort)
(apply str)))
(defn- render-attr-value [value]
(cond
(map? value) (render-style-map value)
(sequential? value) (str/join " " value)
:else value))
(defn- xml-attribute [name value]
(str " " (as-str name) "=\"" (escape-html (render-attr-value value)) "\""))
(defn- render-attribute [[name value]]
(cond
(true? value) (str " " (as-str name))
(not value) ""
:else (xml-attribute name value)))
(defn render-attr-map
"Render a map of attributes."
[attrs]
(apply str (sort (map render-attribute attrs))))