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