ComponentQuery.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  1. /**
  2. * Provides searching of Components within Ext.ComponentManager (globally) or a specific
  3. * Ext.container.Container on the document with a similar syntax to a CSS selector.
  4. *
  5. * Components can be retrieved by using their {@link Ext.Component xtype}
  6. *
  7. * - `component`
  8. * - `gridpanel`
  9. *
  10. * Matching by xtype matches inherited types, so in the following code, the previous field
  11. * *of any type which inherits from `TextField`* will be found:
  12. *
  13. * prevField = myField.previousNode('textfield');
  14. *
  15. * To match only the exact type, pass the "shallow" flag (See {@link Ext.AbstractComponent#isXType AbstractComponent's isXType method})
  16. *
  17. * prevTextField = myField.previousNode('textfield(true)');
  18. *
  19. * An itemId or id must be prefixed with a #
  20. *
  21. * - `#myContainer`
  22. *
  23. * Attributes must be wrapped in brackets
  24. *
  25. * - `component[autoScroll]`
  26. * - `panel[title="Test"]`
  27. *
  28. * Member expressions from candidate Components may be tested. If the expression returns a *truthy* value,
  29. * the candidate Component will be included in the query:
  30. *
  31. * var disabledFields = myFormPanel.query("{isDisabled()}");
  32. *
  33. * Pseudo classes may be used to filter results in the same way as in {@link Ext.DomQuery DomQuery}:
  34. *
  35. * // Function receives array and returns a filtered array.
  36. * Ext.ComponentQuery.pseudos.invalid = function(items) {
  37. * var i = 0, l = items.length, c, result = [];
  38. * for (; i < l; i++) {
  39. * if (!(c = items[i]).isValid()) {
  40. * result.push(c);
  41. * }
  42. * }
  43. * return result;
  44. * };
  45. *
  46. * var invalidFields = myFormPanel.query('field:invalid');
  47. * if (invalidFields.length) {
  48. * invalidFields[0].getEl().scrollIntoView(myFormPanel.body);
  49. * for (var i = 0, l = invalidFields.length; i < l; i++) {
  50. * invalidFields[i].getEl().frame("red");
  51. * }
  52. * }
  53. *
  54. * Default pseudos include:
  55. *
  56. * - not
  57. * - first
  58. * - last
  59. *
  60. * Queries return an array of components.
  61. * Here are some example queries.
  62. *
  63. * // retrieve all Ext.Panels in the document by xtype
  64. * var panelsArray = Ext.ComponentQuery.query('panel');
  65. *
  66. * // retrieve all Ext.Panels within the container with an id myCt
  67. * var panelsWithinmyCt = Ext.ComponentQuery.query('#myCt panel');
  68. *
  69. * // retrieve all direct children which are Ext.Panels within myCt
  70. * var directChildPanel = Ext.ComponentQuery.query('#myCt > panel');
  71. *
  72. * // retrieve all grids and trees
  73. * var gridsAndTrees = Ext.ComponentQuery.query('gridpanel, treepanel');
  74. *
  75. * For easy access to queries based from a particular Container see the {@link Ext.container.Container#query},
  76. * {@link Ext.container.Container#down} and {@link Ext.container.Container#child} methods. Also see
  77. * {@link Ext.Component#up}.
  78. */
  79. Ext.define('Ext.ComponentQuery', {
  80. singleton: true,
  81. requires: ['Ext.ComponentManager']
  82. }, function() {
  83. var cq = this,
  84. // A function source code pattern with a placeholder which accepts an expression which yields a truth value when applied
  85. // as a member on each item in the passed array.
  86. filterFnPattern = [
  87. 'var r = [],',
  88. 'i = 0,',
  89. 'it = items,',
  90. 'l = it.length,',
  91. 'c;',
  92. 'for (; i < l; i++) {',
  93. 'c = it[i];',
  94. 'if (c.{0}) {',
  95. 'r.push(c);',
  96. '}',
  97. '}',
  98. 'return r;'
  99. ].join(''),
  100. filterItems = function(items, operation) {
  101. // Argument list for the operation is [ itemsArray, operationArg1, operationArg2...]
  102. // The operation's method loops over each item in the candidate array and
  103. // returns an array of items which match its criteria
  104. return operation.method.apply(this, [ items ].concat(operation.args));
  105. },
  106. getItems = function(items, mode) {
  107. var result = [],
  108. i = 0,
  109. length = items.length,
  110. candidate,
  111. deep = mode !== '>';
  112. for (; i < length; i++) {
  113. candidate = items[i];
  114. if (candidate.getRefItems) {
  115. result = result.concat(candidate.getRefItems(deep));
  116. }
  117. }
  118. return result;
  119. },
  120. getAncestors = function(items) {
  121. var result = [],
  122. i = 0,
  123. length = items.length,
  124. candidate;
  125. for (; i < length; i++) {
  126. candidate = items[i];
  127. while (!!(candidate = (candidate.ownerCt || candidate.floatParent))) {
  128. result.push(candidate);
  129. }
  130. }
  131. return result;
  132. },
  133. // Filters the passed candidate array and returns only items which match the passed xtype
  134. filterByXType = function(items, xtype, shallow) {
  135. if (xtype === '*') {
  136. return items.slice();
  137. }
  138. else {
  139. var result = [],
  140. i = 0,
  141. length = items.length,
  142. candidate;
  143. for (; i < length; i++) {
  144. candidate = items[i];
  145. if (candidate.isXType(xtype, shallow)) {
  146. result.push(candidate);
  147. }
  148. }
  149. return result;
  150. }
  151. },
  152. // Filters the passed candidate array and returns only items which have the passed className
  153. filterByClassName = function(items, className) {
  154. var EA = Ext.Array,
  155. result = [],
  156. i = 0,
  157. length = items.length,
  158. candidate;
  159. for (; i < length; i++) {
  160. candidate = items[i];
  161. if (candidate.hasCls(className)) {
  162. result.push(candidate);
  163. }
  164. }
  165. return result;
  166. },
  167. // Filters the passed candidate array and returns only items which have the specified property match
  168. filterByAttribute = function(items, property, operator, value) {
  169. var result = [],
  170. i = 0,
  171. length = items.length,
  172. candidate;
  173. for (; i < length; i++) {
  174. candidate = items[i];
  175. if (!value ? !!candidate[property] : (String(candidate[property]) === value)) {
  176. result.push(candidate);
  177. }
  178. }
  179. return result;
  180. },
  181. // Filters the passed candidate array and returns only items which have the specified itemId or id
  182. filterById = function(items, id) {
  183. var result = [],
  184. i = 0,
  185. length = items.length,
  186. candidate;
  187. for (; i < length; i++) {
  188. candidate = items[i];
  189. if (candidate.getItemId() === id) {
  190. result.push(candidate);
  191. }
  192. }
  193. return result;
  194. },
  195. // Filters the passed candidate array and returns only items which the named pseudo class matcher filters in
  196. filterByPseudo = function(items, name, value) {
  197. return cq.pseudos[name](items, value);
  198. },
  199. // Determines leading mode
  200. // > for direct child, and ^ to switch to ownerCt axis
  201. modeRe = /^(\s?([>\^])\s?|\s|$)/,
  202. // Matches a token with possibly (true|false) appended for the "shallow" parameter
  203. tokenRe = /^(#)?([\w\-]+|\*)(?:\((true|false)\))?/,
  204. matchers = [{
  205. // Checks for .xtype with possibly (true|false) appended for the "shallow" parameter
  206. re: /^\.([\w\-]+)(?:\((true|false)\))?/,
  207. method: filterByXType
  208. },{
  209. // checks for [attribute=value]
  210. re: /^(?:[\[](?:@)?([\w\-]+)\s?(?:(=|.=)\s?['"]?(.*?)["']?)?[\]])/,
  211. method: filterByAttribute
  212. }, {
  213. // checks for #cmpItemId
  214. re: /^#([\w\-]+)/,
  215. method: filterById
  216. }, {
  217. // checks for :<pseudo_class>(<selector>)
  218. re: /^\:([\w\-]+)(?:\(((?:\{[^\}]+\})|(?:(?!\{)[^\s>\/]*?(?!\})))\))?/,
  219. method: filterByPseudo
  220. }, {
  221. // checks for {<member_expression>}
  222. re: /^(?:\{([^\}]+)\})/,
  223. method: filterFnPattern
  224. }];
  225. // Internal class Ext.ComponentQuery.Query
  226. cq.Query = Ext.extend(Object, {
  227. constructor: function(cfg) {
  228. cfg = cfg || {};
  229. Ext.apply(this, cfg);
  230. },
  231. // Executes this Query upon the selected root.
  232. // The root provides the initial source of candidate Component matches which are progressively
  233. // filtered by iterating through this Query's operations cache.
  234. // If no root is provided, all registered Components are searched via the ComponentManager.
  235. // root may be a Container who's descendant Components are filtered
  236. // root may be a Component with an implementation of getRefItems which provides some nested Components such as the
  237. // docked items within a Panel.
  238. // root may be an array of candidate Components to filter using this Query.
  239. execute : function(root) {
  240. var operations = this.operations,
  241. i = 0,
  242. length = operations.length,
  243. operation,
  244. workingItems;
  245. // no root, use all Components in the document
  246. if (!root) {
  247. workingItems = Ext.ComponentManager.all.getArray();
  248. }
  249. // Root is a candidate Array
  250. else if (Ext.isArray(root)) {
  251. workingItems = root;
  252. }
  253. // Root is a MixedCollection
  254. else if (root.isMixedCollection) {
  255. workingItems = root.items;
  256. }
  257. // We are going to loop over our operations and take care of them
  258. // one by one.
  259. for (; i < length; i++) {
  260. operation = operations[i];
  261. // The mode operation requires some custom handling.
  262. // All other operations essentially filter down our current
  263. // working items, while mode replaces our current working
  264. // items by getting children from each one of our current
  265. // working items. The type of mode determines the type of
  266. // children we get. (e.g. > only gets direct children)
  267. if (operation.mode === '^') {
  268. workingItems = getAncestors(workingItems || [root]);
  269. }
  270. else if (operation.mode) {
  271. workingItems = getItems(workingItems || [root], operation.mode);
  272. }
  273. else {
  274. workingItems = filterItems(workingItems || getItems([root]), operation);
  275. }
  276. // If this is the last operation, it means our current working
  277. // items are the final matched items. Thus return them!
  278. if (i === length -1) {
  279. return workingItems;
  280. }
  281. }
  282. return [];
  283. },
  284. is: function(component) {
  285. var operations = this.operations,
  286. components = Ext.isArray(component) ? component : [component],
  287. originalLength = components.length,
  288. lastOperation = operations[operations.length-1],
  289. ln, i;
  290. components = filterItems(components, lastOperation);
  291. if (components.length === originalLength) {
  292. if (operations.length > 1) {
  293. for (i = 0, ln = components.length; i < ln; i++) {
  294. if (Ext.Array.indexOf(this.execute(), components[i]) === -1) {
  295. return false;
  296. }
  297. }
  298. }
  299. return true;
  300. }
  301. return false;
  302. }
  303. });
  304. Ext.apply(this, {
  305. // private cache of selectors and matching ComponentQuery.Query objects
  306. cache: {},
  307. // private cache of pseudo class filter functions
  308. pseudos: {
  309. not: function(components, selector){
  310. var CQ = Ext.ComponentQuery,
  311. i = 0,
  312. length = components.length,
  313. results = [],
  314. index = -1,
  315. component;
  316. for(; i < length; ++i) {
  317. component = components[i];
  318. if (!CQ.is(component, selector)) {
  319. results[++index] = component;
  320. }
  321. }
  322. return results;
  323. },
  324. first: function(components) {
  325. var ret = [];
  326. if (components.length > 0) {
  327. ret.push(components[0]);
  328. }
  329. return ret;
  330. },
  331. last: function(components) {
  332. var len = components.length,
  333. ret = [];
  334. if (len > 0) {
  335. ret.push(components[len - 1]);
  336. }
  337. return ret;
  338. }
  339. },
  340. /**
  341. * Returns an array of matched Components from within the passed root object.
  342. *
  343. * This method filters returned Components in a similar way to how CSS selector based DOM
  344. * queries work using a textual selector string.
  345. *
  346. * See class summary for details.
  347. *
  348. * @param {String} selector The selector string to filter returned Components
  349. * @param {Ext.container.Container} root The Container within which to perform the query.
  350. * If omitted, all Components within the document are included in the search.
  351. *
  352. * This parameter may also be an array of Components to filter according to the selector.</p>
  353. * @returns {Ext.Component[]} The matched Components.
  354. *
  355. * @member Ext.ComponentQuery
  356. */
  357. query: function(selector, root) {
  358. var selectors = selector.split(','),
  359. length = selectors.length,
  360. i = 0,
  361. results = [],
  362. noDupResults = [],
  363. dupMatcher = {},
  364. query, resultsLn, cmp;
  365. for (; i < length; i++) {
  366. selector = Ext.String.trim(selectors[i]);
  367. query = this.cache[selector] || (this.cache[selector] = this.parse(selector));
  368. results = results.concat(query.execute(root));
  369. }
  370. // multiple selectors, potential to find duplicates
  371. // lets filter them out.
  372. if (length > 1) {
  373. resultsLn = results.length;
  374. for (i = 0; i < resultsLn; i++) {
  375. cmp = results[i];
  376. if (!dupMatcher[cmp.id]) {
  377. noDupResults.push(cmp);
  378. dupMatcher[cmp.id] = true;
  379. }
  380. }
  381. results = noDupResults;
  382. }
  383. return results;
  384. },
  385. /**
  386. * Tests whether the passed Component matches the selector string.
  387. * @param {Ext.Component} component The Component to test
  388. * @param {String} selector The selector string to test against.
  389. * @return {Boolean} True if the Component matches the selector.
  390. * @member Ext.ComponentQuery
  391. */
  392. is: function(component, selector) {
  393. if (!selector) {
  394. return true;
  395. }
  396. var selectors = selector.split(','),
  397. length = selectors.length,
  398. i = 0,
  399. query;
  400. for (; i < length; i++) {
  401. selector = Ext.String.trim(selectors[i]);
  402. query = this.cache[selector] || (this.cache[selector] = this.parse(selector));
  403. if (query.is(component)) {
  404. return true;
  405. }
  406. }
  407. return false;
  408. },
  409. parse: function(selector) {
  410. var operations = [],
  411. length = matchers.length,
  412. lastSelector,
  413. tokenMatch,
  414. matchedChar,
  415. modeMatch,
  416. selectorMatch,
  417. i, matcher, method;
  418. // We are going to parse the beginning of the selector over and
  419. // over again, slicing off the selector any portions we converted into an
  420. // operation, until it is an empty string.
  421. while (selector && lastSelector !== selector) {
  422. lastSelector = selector;
  423. // First we check if we are dealing with a token like #, * or an xtype
  424. tokenMatch = selector.match(tokenRe);
  425. if (tokenMatch) {
  426. matchedChar = tokenMatch[1];
  427. // If the token is prefixed with a # we push a filterById operation to our stack
  428. if (matchedChar === '#') {
  429. operations.push({
  430. method: filterById,
  431. args: [Ext.String.trim(tokenMatch[2])]
  432. });
  433. }
  434. // If the token is prefixed with a . we push a filterByClassName operation to our stack
  435. // FIXME: Not enabled yet. just needs \. adding to the tokenRe prefix
  436. else if (matchedChar === '.') {
  437. operations.push({
  438. method: filterByClassName,
  439. args: [Ext.String.trim(tokenMatch[2])]
  440. });
  441. }
  442. // If the token is a * or an xtype string, we push a filterByXType
  443. // operation to the stack.
  444. else {
  445. operations.push({
  446. method: filterByXType,
  447. args: [Ext.String.trim(tokenMatch[2]), Boolean(tokenMatch[3])]
  448. });
  449. }
  450. // Now we slice of the part we just converted into an operation
  451. selector = selector.replace(tokenMatch[0], '');
  452. }
  453. // If the next part of the query is not a space or > or ^, it means we
  454. // are going to check for more things that our current selection
  455. // has to comply to.
  456. while (!(modeMatch = selector.match(modeRe))) {
  457. // Lets loop over each type of matcher and execute it
  458. // on our current selector.
  459. for (i = 0; selector && i < length; i++) {
  460. matcher = matchers[i];
  461. selectorMatch = selector.match(matcher.re);
  462. method = matcher.method;
  463. // If we have a match, add an operation with the method
  464. // associated with this matcher, and pass the regular
  465. // expression matches are arguments to the operation.
  466. if (selectorMatch) {
  467. operations.push({
  468. method: Ext.isString(matcher.method)
  469. // Turn a string method into a function by formatting the string with our selector matche expression
  470. // A new method is created for different match expressions, eg {id=='textfield-1024'}
  471. // Every expression may be different in different selectors.
  472. ? Ext.functionFactory('items', Ext.String.format.apply(Ext.String, [method].concat(selectorMatch.slice(1))))
  473. : matcher.method,
  474. args: selectorMatch.slice(1)
  475. });
  476. selector = selector.replace(selectorMatch[0], '');
  477. break; // Break on match
  478. }
  479. // Exhausted all matches: It's an error
  480. if (i === (length - 1)) {
  481. Ext.Error.raise('Invalid ComponentQuery selector: "' + arguments[0] + '"');
  482. }
  483. }
  484. }
  485. // Now we are going to check for a mode change. This means a space
  486. // or a > to determine if we are going to select all the children
  487. // of the currently matched items, or a ^ if we are going to use the
  488. // ownerCt axis as the candidate source.
  489. if (modeMatch[1]) { // Assignment, and test for truthiness!
  490. operations.push({
  491. mode: modeMatch[2]||modeMatch[1]
  492. });
  493. selector = selector.replace(modeMatch[0], '');
  494. }
  495. }
  496. // Now that we have all our operations in an array, we are going
  497. // to create a new Query using these operations.
  498. return new cq.Query({
  499. operations: operations
  500. });
  501. }
  502. });
  503. });