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