Skip to content

Instantly share code, notes, and snippets.

@Olical
Created September 16, 2017 11:18
Show Gist options
  • Save Olical/f2b934873a49c0638ca673ab764a0131 to your computer and use it in GitHub Desktop.
Save Olical/f2b934873a49c0638ca673ab764a0131 to your computer and use it in GitHub Desktop.
Using clojure.spec to parse trees
(ns bonsai.tree
(:require #?(:clj [clojure.spec.alpha :as s]
:cljs [cljs.spec.alpha :as s])))
(s/def ::element (s/or :string string?
:element (s/cat :name keyword?
:attrs (s/? (s/map-of keyword? any?))
:children (s/* ::element))))
(s/conform ::element [:p])
;; =>
;; [:element {:name :p}]
(s/conform ::element [:p "hey!"])
;; =>
;; [:element {:name :p,
;; :children [[:string "hey!"]]}]
(s/conform ::element [:p {:on-click println} "hey!"])
;; =>
;; [:element {:name :p,
;; :attrs {:on-click #f
;; unction
;; [clojure.core/println]},
;; :children [[:string "hey!"]]}]
(s/conform ::element [:p
{:on-click println}
[:span "before"] "middle" [:span "after"]])
;; =>
;; [:element {:name :p,
;; :attrs {:on-click #function
;; [clojure.core/println]},
;; :children [[:element {:name :span,
;; :children [[:string "before"]]}]
;; [:string "middle"]
;; [:element {:name :span,
;; :children [[:string "after"]]}]]}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment