Skip to content

Instantly share code, notes, and snippets.

@whamtet
Last active March 3, 2022 05:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save whamtet/6f8af62e69fd21dc8550092883ebd9ed to your computer and use it in GitHub Desktop.
Save whamtet/6f8af62e69fd21dc8550092883ebd9ed to your computer and use it in GitHub Desktop.
(ns app.render
(:require
[app.util :as util]
[clojure.string :as string]))
(defn flatten-list [x]
(filter (complement seq?)
(rest (tree-seq seq? seq x))))
(defn map->style [m]
(string/join "; "
(for [[k v] m]
(str (name k) ": " v))))
(defn- set-attrs [el attr]
(doseq [[k v] attr
:let [k (name k)
v (if (map? v) (map->style v) v)]]
(if (ifn? v)
(.addEventListener el (.replace k "on" "") v)
(.setAttribute el k v))))
(def r-pre #"[^.#]+")
(def r-id #"#([^.]+)")
(def r-class #"\.([^.]+)")
(defn- special-attrs [tag]
(util/filter-vals
{:id (second (re-find r-id tag))
:class (->> tag (re-seq r-class) (map second) (string/join " "))}))
(defn html [hiccup]
(if (vector? hiccup)
(let [[tag attr & children] (-> hiccup seq flatten-list)
tag (name tag)
[attr children] (if (map? attr)
[attr children]
[{} (conj children attr)])
attr (merge attr (special-attrs tag))
tag (re-find r-pre tag)
el (js/document.createElement tag)]
(set-attrs el attr)
(doseq [child children]
(.append el (html child)))
el)
hiccup))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment