Version 3.18.1
Show:

File: dom/js/selector-css2.js

  1. /**
  2. * The selector module provides helper methods allowing CSS2 Selectors to be used with DOM elements.
  3. * @module dom
  4. * @submodule selector-css2
  5. * @for Selector
  6. */
  7. /*
  8. * Provides helper methods for collecting and filtering DOM elements.
  9. */
  10. var PARENT_NODE = 'parentNode',
  11. TAG_NAME = 'tagName',
  12. ATTRIBUTES = 'attributes',
  13. COMBINATOR = 'combinator',
  14. PSEUDOS = 'pseudos',
  15. Selector = Y.Selector,
  16. SelectorCSS2 = {
  17. _reRegExpTokens: /([\^\$\?\[\]\*\+\-\.\(\)\|\\])/,
  18. SORT_RESULTS: true,
  19. // TODO: better detection, document specific
  20. _isXML: (function() {
  21. var isXML = (Y.config.doc.createElement('div').tagName !== 'DIV');
  22. return isXML;
  23. }()),
  24. /**
  25. * Mapping of shorthand tokens to corresponding attribute selector
  26. * @property shorthand
  27. * @type object
  28. */
  29. shorthand: {
  30. '\\#(-?[_a-z0-9]+[-\\w\\uE000]*)': '[id=$1]',
  31. '\\.(-?[_a-z]+[-\\w\\uE000]*)': '[className~=$1]'
  32. },
  33. /**
  34. * List of operators and corresponding boolean functions.
  35. * These functions are passed the attribute and the current node's value of the attribute.
  36. * @property operators
  37. * @type object
  38. */
  39. operators: {
  40. '': function(node, attr) { return Y.DOM.getAttribute(node, attr) !== ''; }, // Just test for existence of attribute
  41. '~=': '(?:^|\\s+){val}(?:\\s+|$)', // space-delimited
  42. '|=': '^{val}-?' // optional hyphen-delimited
  43. },
  44. pseudos: {
  45. 'first-child': function(node) {
  46. return Y.DOM._children(node[PARENT_NODE])[0] === node;
  47. }
  48. },
  49. _bruteQuery: function(selector, root, firstOnly) {
  50. var ret = [],
  51. nodes = [],
  52. visited,
  53. tokens = Selector._tokenize(selector),
  54. token = tokens[tokens.length - 1],
  55. rootDoc = Y.DOM._getDoc(root),
  56. child,
  57. id,
  58. className,
  59. tagName,
  60. isUniversal;
  61. if (token) {
  62. // prefilter nodes
  63. id = token.id;
  64. className = token.className;
  65. tagName = token.tagName || '*';
  66. if (root.getElementsByTagName) { // non-IE lacks DOM api on doc frags
  67. // try ID first, unless no root.all && root not in document
  68. // (root.all works off document, but not getElementById)
  69. if (id && (root.all || (root.nodeType === 9 || Y.DOM.inDoc(root)))) {
  70. nodes = Y.DOM.allById(id, root);
  71. // try className
  72. } else if (className) {
  73. nodes = root.getElementsByClassName(className);
  74. } else { // default to tagName
  75. nodes = root.getElementsByTagName(tagName);
  76. }
  77. } else { // brute getElementsByTagName()
  78. visited = [];
  79. child = root.firstChild;
  80. isUniversal = tagName === "*";
  81. while (child) {
  82. while (child) {
  83. // IE 6-7 considers comment nodes as element nodes, and gives them the tagName "!".
  84. // We can filter them out by checking if its tagName is > "@".
  85. // This also avoids a superflous nodeType === 1 check.
  86. if (child.tagName > "@" && (isUniversal || child.tagName === tagName)) {
  87. nodes.push(child);
  88. }
  89. // We may need to traverse back up the tree to find more unvisited subtrees.
  90. visited.push(child);
  91. child = child.firstChild;
  92. }
  93. // Find the most recently visited node who has a next sibling.
  94. while (visited.length > 0 && !child) {
  95. child = visited.pop().nextSibling;
  96. }
  97. }
  98. }
  99. if (nodes.length) {
  100. ret = Selector._filterNodes(nodes, tokens, firstOnly);
  101. }
  102. }
  103. return ret;
  104. },
  105. _filterNodes: function(nodes, tokens, firstOnly) {
  106. var i = 0,
  107. j,
  108. len = tokens.length,
  109. n = len - 1,
  110. result = [],
  111. node = nodes[0],
  112. tmpNode = node,
  113. getters = Y.Selector.getters,
  114. operator,
  115. combinator,
  116. token,
  117. path,
  118. pass,
  119. value,
  120. tests,
  121. test;
  122. for (i = 0; (tmpNode = node = nodes[i++]);) {
  123. n = len - 1;
  124. path = null;
  125. testLoop:
  126. while (tmpNode && tmpNode.tagName) {
  127. token = tokens[n];
  128. tests = token.tests;
  129. j = tests.length;
  130. if (j && !pass) {
  131. while ((test = tests[--j])) {
  132. operator = test[1];
  133. if (getters[test[0]]) {
  134. value = getters[test[0]](tmpNode, test[0]);
  135. } else {
  136. value = tmpNode[test[0]];
  137. if (test[0] === 'tagName' && !Selector._isXML) {
  138. value = value.toUpperCase();
  139. }
  140. if (typeof value != 'string' && value !== undefined && value.toString) {
  141. value = value.toString(); // coerce for comparison
  142. } else if (value === undefined && tmpNode.getAttribute) {
  143. // use getAttribute for non-standard attributes
  144. value = tmpNode.getAttribute(test[0], 2); // 2 === force string for IE
  145. }
  146. }
  147. if ((operator === '=' && value !== test[2]) || // fast path for equality
  148. (typeof operator !== 'string' && // protect against String.test monkey-patch (Moo)
  149. operator.test && !operator.test(value)) || // regex test
  150. (!operator.test && // protect against RegExp as function (webkit)
  151. typeof operator === 'function' && !operator(tmpNode, test[0], test[2]))) { // function test
  152. // skip non element nodes or non-matching tags
  153. if ((tmpNode = tmpNode[path])) {
  154. while (tmpNode &&
  155. (!tmpNode.tagName ||
  156. (token.tagName && token.tagName !== tmpNode.tagName))
  157. ) {
  158. tmpNode = tmpNode[path];
  159. }
  160. }
  161. continue testLoop;
  162. }
  163. }
  164. }
  165. n--; // move to next token
  166. // now that we've passed the test, move up the tree by combinator
  167. if (!pass && (combinator = token.combinator)) {
  168. path = combinator.axis;
  169. tmpNode = tmpNode[path];
  170. // skip non element nodes
  171. while (tmpNode && !tmpNode.tagName) {
  172. tmpNode = tmpNode[path];
  173. }
  174. if (combinator.direct) { // one pass only
  175. path = null;
  176. }
  177. } else { // success if we made it this far
  178. result.push(node);
  179. if (firstOnly) {
  180. return result;
  181. }
  182. break;
  183. }
  184. }
  185. }
  186. node = tmpNode = null;
  187. return result;
  188. },
  189. combinators: {
  190. ' ': {
  191. axis: 'parentNode'
  192. },
  193. '>': {
  194. axis: 'parentNode',
  195. direct: true
  196. },
  197. '+': {
  198. axis: 'previousSibling',
  199. direct: true
  200. }
  201. },
  202. _parsers: [
  203. {
  204. name: ATTRIBUTES,
  205. re: /^\uE003(-?[a-z]+[\w\-]*)+([~\|\^\$\*!=]=?)?['"]?([^\uE004'"]*)['"]?\uE004/i,
  206. fn: function(match, token) {
  207. var operator = match[2] || '',
  208. operators = Selector.operators,
  209. escVal = (match[3]) ? match[3].replace(/\\/g, '') : '',
  210. test;
  211. // add prefiltering for ID and CLASS
  212. if ((match[1] === 'id' && operator === '=') ||
  213. (match[1] === 'className' &&
  214. Y.config.doc.documentElement.getElementsByClassName &&
  215. (operator === '~=' || operator === '='))) {
  216. token.prefilter = match[1];
  217. match[3] = escVal;
  218. // escape all but ID for prefilter, which may run through QSA (via Dom.allById)
  219. token[match[1]] = (match[1] === 'id') ? match[3] : escVal;
  220. }
  221. // add tests
  222. if (operator in operators) {
  223. test = operators[operator];
  224. if (typeof test === 'string') {
  225. match[3] = escVal.replace(Selector._reRegExpTokens, '\\$1');
  226. test = new RegExp(test.replace('{val}', match[3]));
  227. }
  228. match[2] = test;
  229. }
  230. if (!token.last || token.prefilter !== match[1]) {
  231. return match.slice(1);
  232. }
  233. }
  234. },
  235. {
  236. name: TAG_NAME,
  237. re: /^((?:-?[_a-z]+[\w-]*)|\*)/i,
  238. fn: function(match, token) {
  239. var tag = match[1];
  240. if (!Selector._isXML) {
  241. tag = tag.toUpperCase();
  242. }
  243. token.tagName = tag;
  244. if (tag !== '*' && (!token.last || token.prefilter)) {
  245. return [TAG_NAME, '=', tag];
  246. }
  247. if (!token.prefilter) {
  248. token.prefilter = 'tagName';
  249. }
  250. }
  251. },
  252. {
  253. name: COMBINATOR,
  254. re: /^\s*([>+~]|\s)\s*/,
  255. fn: function(match, token) {
  256. }
  257. },
  258. {
  259. name: PSEUDOS,
  260. re: /^:([\-\w]+)(?:\uE005['"]?([^\uE005]*)['"]?\uE006)*/i,
  261. fn: function(match, token) {
  262. var test = Selector[PSEUDOS][match[1]];
  263. if (test) { // reorder match array and unescape special chars for tests
  264. if (match[2]) {
  265. match[2] = match[2].replace(/\\/g, '');
  266. }
  267. return [match[2], test];
  268. } else { // selector token not supported (possibly missing CSS3 module)
  269. return false;
  270. }
  271. }
  272. }
  273. ],
  274. _getToken: function(token) {
  275. return {
  276. tagName: null,
  277. id: null,
  278. className: null,
  279. attributes: {},
  280. combinator: null,
  281. tests: []
  282. };
  283. },
  284. /*
  285. Break selector into token units per simple selector.
  286. Combinator is attached to the previous token.
  287. */
  288. _tokenize: function(selector) {
  289. selector = selector || '';
  290. selector = Selector._parseSelector(Y.Lang.trim(selector));
  291. var token = Selector._getToken(), // one token per simple selector (left selector holds combinator)
  292. query = selector, // original query for debug report
  293. tokens = [], // array of tokens
  294. found = false, // whether or not any matches were found this pass
  295. match, // the regex match
  296. test,
  297. i, parser;
  298. /*
  299. Search for selector patterns, store, and strip them from the selector string
  300. until no patterns match (invalid selector) or we run out of chars.
  301. Multiple attributes and pseudos are allowed, in any order.
  302. for example:
  303. 'form:first-child[type=button]:not(button)[lang|=en]'
  304. */
  305. outer:
  306. do {
  307. found = false; // reset after full pass
  308. for (i = 0; (parser = Selector._parsers[i++]);) {
  309. if ( (match = parser.re.exec(selector)) ) { // note assignment
  310. if (parser.name !== COMBINATOR ) {
  311. token.selector = selector;
  312. }
  313. selector = selector.replace(match[0], ''); // strip current match from selector
  314. if (!selector.length) {
  315. token.last = true;
  316. }
  317. if (Selector._attrFilters[match[1]]) { // convert class to className, etc.
  318. match[1] = Selector._attrFilters[match[1]];
  319. }
  320. test = parser.fn(match, token);
  321. if (test === false) { // selector not supported
  322. found = false;
  323. break outer;
  324. } else if (test) {
  325. token.tests.push(test);
  326. }
  327. if (!selector.length || parser.name === COMBINATOR) {
  328. tokens.push(token);
  329. token = Selector._getToken(token);
  330. if (parser.name === COMBINATOR) {
  331. token.combinator = Y.Selector.combinators[match[1]];
  332. }
  333. }
  334. found = true;
  335. }
  336. }
  337. } while (found && selector.length);
  338. if (!found || selector.length) { // not fully parsed
  339. Y.log('query: ' + query + ' contains unsupported token in: ' + selector, 'warn', 'Selector');
  340. tokens = [];
  341. }
  342. return tokens;
  343. },
  344. _replaceMarkers: function(selector) {
  345. selector = selector.replace(/\[/g, '\uE003');
  346. selector = selector.replace(/\]/g, '\uE004');
  347. selector = selector.replace(/\(/g, '\uE005');
  348. selector = selector.replace(/\)/g, '\uE006');
  349. return selector;
  350. },
  351. _replaceShorthand: function(selector) {
  352. var shorthand = Y.Selector.shorthand,
  353. re;
  354. for (re in shorthand) {
  355. if (shorthand.hasOwnProperty(re)) {
  356. selector = selector.replace(new RegExp(re, 'gi'), shorthand[re]);
  357. }
  358. }
  359. return selector;
  360. },
  361. _parseSelector: function(selector) {
  362. var replaced = Y.Selector._replaceSelector(selector),
  363. selector = replaced.selector;
  364. // replace shorthand (".foo, #bar") after pseudos and attrs
  365. // to avoid replacing unescaped chars
  366. selector = Y.Selector._replaceShorthand(selector);
  367. selector = Y.Selector._restore('attr', selector, replaced.attrs);
  368. selector = Y.Selector._restore('pseudo', selector, replaced.pseudos);
  369. // replace braces and parens before restoring escaped chars
  370. // to avoid replacing ecaped markers
  371. selector = Y.Selector._replaceMarkers(selector);
  372. selector = Y.Selector._restore('esc', selector, replaced.esc);
  373. return selector;
  374. },
  375. _attrFilters: {
  376. 'class': 'className',
  377. 'for': 'htmlFor'
  378. },
  379. getters: {
  380. href: function(node, attr) {
  381. return Y.DOM.getAttribute(node, attr);
  382. },
  383. id: function(node, attr) {
  384. return Y.DOM.getId(node);
  385. }
  386. }
  387. };
  388. Y.mix(Y.Selector, SelectorCSS2, true);
  389. Y.Selector.getters.src = Y.Selector.getters.rel = Y.Selector.getters.href;
  390. // IE wants class with native queries
  391. if (Y.Selector.useNative && Y.config.doc.querySelector) {
  392. Y.Selector.shorthand['\\.(-?[_a-z]+[-\\w]*)'] = '[class~=$1]';
  393. }