plumatic / dommy

A tiny ClojureScript DOM manipulation and event library
759 stars 74 forks source link

Selector strings need escaping #44

Open favila opened 11 years ago

favila commented 11 years ago

Query selectors must use css syntax, which means things like semicolons and backslashes need a backslash to precede them.

Example where this causes failure:

(sel "#:0.inp")

This will produce a SYNTAX_ERR (== DOM Exception 12). The crazy-looking ":0.inp" is the typical format of ids produced by goog.ui.Component/makeId which are regularly inserted into id attributes of dom elements (which is how it bit me).

An at least partial fix is to use an escaping function like this (cljs):

(def requires-css-escaping #"(?:^[^a-zA-Z]|[\u0000-\u002c\u002e\u002f\u003a-\u0040\u005b-\u005e\u0060\u007b-\u009f])")
(defn escape-css-char [c] (str \\ (.. c (charCodeAt 0) (toString 16)) \space))

(defn css-escape [s] (clojure.string/replace s requires-css-escaping escape-css-char))

And then patch dommy.core/selector:

(defn selector [data]
  (cond
   (coll? data) (clojure.string/join " " (map selector data))
   (string? data) (name data)
   (keyword? data) (if-let [prefix (some #{\# \.} (aget (name data) 0))]
                             (str prefix (css-escape (subs (name data) 1))
                             (css-escape (name data)))

I think dommy.macros/selector will need a similar transformation.

However you can only safely use this on keywords since strings may use css characters for their intended meaning. This argues for making "css-escape" or "selector-escape" a public function users can use.