1
0

css-selector-parser.js 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. /*
  2. * Copyright (c) Felix Böhm
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
  6. *
  7. * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  8. *
  9. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  10. *
  11. * THIS IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS,
  12. * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  13. */
  14. // Modified by Gildas Lormeau
  15. /* global CSS */
  16. this.cssWhat = this.cssWhat || (() => {
  17. "use strict";
  18. const re_name = /^(?:\\.|[\w\-\u00c0-\uFFFF])+/,
  19. re_escape = /\\([\da-f]{1,6}\s?|(\s)|.)/ig,
  20. //modified version of https://github.com/jquery/sizzle/blob/master/src/sizzle.js#L87
  21. re_attr = /^\s*((?:\\.|[\w\u00c0-\uFFFF-])+)\s*(?:(\S?)=\s*(?:(['"])([^]*?)\3|(#?(?:\\.|[\w\u00c0-\uFFFF-])*)|)|)\s*(i)?\]/;
  22. const actionTypes = {
  23. __proto__: null,
  24. "undefined": "exists",
  25. "": "equals",
  26. "~": "element",
  27. "^": "start",
  28. "$": "end",
  29. "*": "any",
  30. "!": "not",
  31. "|": "hyphen"
  32. };
  33. const simpleSelectors = {
  34. __proto__: null,
  35. ">": "child",
  36. "~": "sibling",
  37. "+": "adjacent"
  38. };
  39. const attribSelectors = {
  40. __proto__: null,
  41. "#": ["id", "equals"],
  42. ".": ["class", "element"]
  43. };
  44. //pseudos, whose data-property is parsed as well
  45. const unpackPseudos = {
  46. __proto__: null,
  47. "has": true,
  48. "not": true,
  49. "matches": true
  50. };
  51. const stripQuotesFromPseudos = {
  52. __proto__: null,
  53. "contains": true,
  54. "icontains": true
  55. };
  56. const quotes = {
  57. __proto__: null,
  58. "\"": true,
  59. "'": true
  60. };
  61. const pseudoElements = [
  62. "after", "before", "cue", "first-letter", "first-line", "selection", "slotted"
  63. ];
  64. const stringify = (() => {
  65. const actionTypes = {
  66. "equals": "",
  67. "element": "~",
  68. "start": "^",
  69. "end": "$",
  70. "any": "*",
  71. "not": "!",
  72. "hyphen": "|"
  73. };
  74. const simpleSelectors = {
  75. __proto__: null,
  76. child: " > ",
  77. sibling: " ~ ",
  78. adjacent: " + ",
  79. descendant: " ",
  80. universal: "*"
  81. };
  82. function stringify(token) {
  83. let value = "";
  84. token.forEach(token => value += stringifySubselector(token) + ",");
  85. return value.substring(0, value.length - 1);
  86. }
  87. function stringifySubselector(token) {
  88. let value = "";
  89. token.forEach(token => value += stringifyToken(token));
  90. return value;
  91. }
  92. function stringifyToken(token) {
  93. if (token.type in simpleSelectors) return simpleSelectors[token.type];
  94. if (token.type == "tag") return escapeName(token.name);
  95. if (token.type == "attribute") {
  96. if (token.action == "exists") return "[" + escapeName(token.name) + "]";
  97. if (token.expandedSelector && token.name == "id" && token.action == "equals" && !token.ignoreCase) return "#" + escapeName(token.value);
  98. if (token.expandedSelector && token.name == "class" && token.action == "element" && !token.ignoreCase) return "." + escapeName(token.value);
  99. return "[" +
  100. escapeName(token.name) + actionTypes[token.action] + "=\"" +
  101. escapeName(token.value) + "\"" + (token.ignoreCase ? "i" : "") + "]";
  102. }
  103. if (token.type == "pseudo") {
  104. if (token.data == null) return ":" + escapeName(token.name);
  105. if (typeof token.data == "string") return ":" + escapeName(token.name) + "(" + token.data + ")";
  106. return ":" + escapeName(token.name) + "(" + stringify(token.data) + ")";
  107. }
  108. if (token.type == "pseudo-element") {
  109. return "::" + escapeName(token.name);
  110. }
  111. }
  112. function escapeName(str) {
  113. return CSS.escape(str);
  114. }
  115. return stringify;
  116. })();
  117. return {
  118. parse,
  119. stringify
  120. };
  121. // unescape function taken from https://github.com/jquery/sizzle/blob/master/src/sizzle.js#L139
  122. function funescape(_, escaped, escapedWhitespace) {
  123. const high = "0x" + escaped - 0x10000;
  124. // NaN means non-codepoint
  125. // Support: Firefox
  126. // Workaround erroneous numeric interpretation of +"0x"
  127. return high != high || escapedWhitespace ?
  128. escaped :
  129. // BMP codepoint
  130. high < 0 ?
  131. String.fromCharCode(high + 0x10000) :
  132. // Supplemental Plane codepoint (surrogate pair)
  133. String.fromCharCode(high >> 10 | 0xD800, high & 0x3FF | 0xDC00);
  134. }
  135. function unescapeCSS(str) {
  136. return str.replace(re_escape, funescape);
  137. }
  138. function isWhitespace(c) {
  139. return c == " " || c == "\n" || c == "\t" || c == "\f" || c == "\r";
  140. }
  141. function parse(selector, options) {
  142. const subselects = [];
  143. selector = parseSelector(subselects, selector + "", options);
  144. if (selector != "") {
  145. throw new SyntaxError("Unmatched selector: " + selector);
  146. }
  147. return subselects;
  148. }
  149. function parseSelector(subselects, selector, options) {
  150. let tokens = [], sawWS = false, data, firstChar, name, quot;
  151. stripWhitespace(0);
  152. while (selector != "") {
  153. firstChar = selector.charAt(0);
  154. if (isWhitespace(firstChar)) {
  155. sawWS = true;
  156. stripWhitespace(1);
  157. } else if (firstChar in simpleSelectors) {
  158. tokens.push({ type: simpleSelectors[firstChar] });
  159. sawWS = false;
  160. stripWhitespace(1);
  161. } else if (firstChar == ",") {
  162. if (tokens.length == 0) {
  163. throw new SyntaxError("empty sub-selector");
  164. }
  165. subselects.push(tokens);
  166. tokens = [];
  167. sawWS = false;
  168. stripWhitespace(1);
  169. } else {
  170. if (sawWS) {
  171. if (tokens.length > 0) {
  172. tokens.push({ type: "descendant" });
  173. }
  174. sawWS = false;
  175. }
  176. if (firstChar == "*") {
  177. selector = selector.substr(1);
  178. tokens.push({ type: "universal" });
  179. } else if (firstChar in attribSelectors) {
  180. selector = selector.substr(1);
  181. tokens.push({
  182. expandedSelector: true,
  183. type: "attribute",
  184. name: attribSelectors[firstChar][0],
  185. action: attribSelectors[firstChar][1],
  186. value: getName(),
  187. ignoreCase: false
  188. });
  189. } else if (firstChar == "[") {
  190. selector = selector.substr(1);
  191. data = selector.match(re_attr);
  192. if (!data) {
  193. throw new SyntaxError("Malformed attribute selector: " + selector);
  194. }
  195. selector = selector.substr(data[0].length);
  196. name = unescapeCSS(data[1]);
  197. if (
  198. !options || (
  199. "lowerCaseAttributeNames" in options ?
  200. options.lowerCaseAttributeNames :
  201. !options.xmlMode
  202. )
  203. ) {
  204. name = name.toLowerCase();
  205. }
  206. tokens.push({
  207. type: "attribute",
  208. name: name,
  209. action: actionTypes[data[2]],
  210. value: unescapeCSS(data[4] || data[5] || ""),
  211. ignoreCase: !!data[6]
  212. });
  213. } else if (firstChar == ":") {
  214. if (selector.charAt(1) == ":") {
  215. selector = selector.substr(2);
  216. tokens.push({ type: "pseudo-element", name: getName().toLowerCase() });
  217. continue;
  218. }
  219. selector = selector.substr(1);
  220. name = getName().toLowerCase();
  221. data = null;
  222. if (selector.charAt(0) == "(") {
  223. if (name in unpackPseudos) {
  224. quot = selector.charAt(1);
  225. const quoted = quot in quotes;
  226. selector = selector.substr(quoted + 1);
  227. data = [];
  228. selector = parseSelector(data, selector, options);
  229. if (quoted) {
  230. if (selector.charAt(0) != quot) {
  231. throw new SyntaxError("unmatched quotes in :" + name);
  232. } else {
  233. selector = selector.substr(1);
  234. }
  235. }
  236. if (selector.charAt(0) != ")") {
  237. throw new SyntaxError("missing closing parenthesis in :" + name + " " + selector);
  238. }
  239. selector = selector.substr(1);
  240. } else {
  241. let pos = 1, counter = 1;
  242. for (; counter > 0 && pos < selector.length; pos++) {
  243. if (selector.charAt(pos) == "(" && !isEscaped(pos)) counter++;
  244. else if (selector.charAt(pos) == ")" && !isEscaped(pos)) counter--;
  245. }
  246. if (counter) {
  247. throw new SyntaxError("parenthesis not matched");
  248. }
  249. data = selector.substr(1, pos - 2);
  250. selector = selector.substr(pos);
  251. if (name in stripQuotesFromPseudos) {
  252. quot = data.charAt(0);
  253. if (quot == data.slice(-1) && quot in quotes) {
  254. data = data.slice(1, -1);
  255. }
  256. data = unescapeCSS(data);
  257. }
  258. }
  259. }
  260. tokens.push({ type: pseudoElements.indexOf(name) == -1 ? "pseudo" : "pseudo-element", name: name, data: data });
  261. } else if (re_name.test(selector)) {
  262. name = getName();
  263. if (!options || ("lowerCaseTags" in options ? options.lowerCaseTags : !options.xmlMode)) {
  264. name = name.toLowerCase();
  265. }
  266. tokens.push({ type: "tag", name: name });
  267. } else {
  268. if (tokens.length && tokens[tokens.length - 1].type == "descendant") {
  269. tokens.pop();
  270. }
  271. addToken(subselects, tokens);
  272. return selector;
  273. }
  274. }
  275. }
  276. addToken(subselects, tokens);
  277. return selector;
  278. function getName() {
  279. const sub = selector.match(re_name)[0];
  280. selector = selector.substr(sub.length);
  281. return unescapeCSS(sub);
  282. }
  283. function stripWhitespace(start) {
  284. while (isWhitespace(selector.charAt(start))) start++;
  285. selector = selector.substr(start);
  286. }
  287. function isEscaped(pos) {
  288. let slashCount = 0;
  289. while (selector.charAt(--pos) == "\\") slashCount++;
  290. return (slashCount & 1) == 1;
  291. }
  292. }
  293. function addToken(subselects, tokens) {
  294. if (subselects.length > 0 && tokens.length == 0) {
  295. throw new SyntaxError("empty sub-selector");
  296. }
  297. subselects.push(tokens);
  298. }
  299. })();