Skip to content

Instantly share code, notes, and snippets.

@Jared314
Last active December 14, 2015 04:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Jared314/5028617 to your computer and use it in GitHub Desktop.
Save Jared314/5028617 to your computer and use it in GitHub Desktop.
Basic CSS3 Selector to Clojure Enlive vector format converter
;[org.jodd/jodd-lagarto "3.4.2"]
;(:import [jodd.csselly CSSelly CssSelector Combinator Selector$Type])
(defn format-attr-selector [x]
(case (.getName x)
"id" (str "#" (.getValue x))
"class" (str "." (.getValue x))
""))
(defn format-selector [x]
(condp #(= %1 (.getType %2)) x
Selector$Type/ATTRIBUTE (format-attr-selector x)
Selector$Type/PSEUDO_CLASS ""
Selector$Type/PSEUDO_FUNCTION ""
""))
(defn parse-selector [x]
(let [count (.selectorsCount x)
combinator (.getCombinator x)
useCombinator (and (not (nil? combinator)) (not= combinator Combinator/DESCENDANT))
sel (keyword (apply str
(conj (map #(format-selector (.getSelector x %)) (range 0 count))
(.getElement x))))]
(if useCombinator
[sel (keyword (.getSign combinator))]
[sel])))
(defn parse-css [x]
(let [sel (.parse (CSSelly. x))]
(vec (flatten (map parse-selector sel)))))
(parse-css "body > *") ; => [:body :> :*]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment