4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
5 <title>The source code</title>
6 <link href="../prettify/prettify.css" type="text/css" rel="stylesheet" />
7 <script type="text/javascript" src="../prettify/prettify.js"></script>
8 <style type="text/css">
9 .highlight { display: block; background-color: #ddd; }
11 <script type="text/javascript">
12 function highlight() {
13 document.getElementById(location.hash.replace(/#/, "")).className = "highlight";
17 <body onload="prettyPrint(); highlight();">
18 <pre class="prettyprint lang-js"><span id='Ext-ComponentQuery'>/**
19 </span> * @class Ext.ComponentQuery
22 * Provides searching of Components within Ext.ComponentManager (globally) or a specific
23 * Ext.container.Container on the document with a similar syntax to a CSS selector.
25 * Components can be retrieved by using their {@link Ext.Component xtype} with an optional . prefix
27 <li>component or .component</li>
28 <li>gridpanel or .gridpanel</li>
31 * An itemId or id must be prefixed with a #
33 <li>#myContainer</li>
37 * Attributes must be wrapped in brackets
39 <li>component[autoScroll]</li>
40 <li>panel[title="Test"]</li>
43 * Member expressions from candidate Components may be tested. If the expression returns a <i>truthy</i> value,
44 * the candidate Component will be included in the query:<pre><code>
45 var disabledFields = myFormPanel.query("{isDisabled()}");
46 </code></pre>
48 * Pseudo classes may be used to filter results in the same way as in {@link Ext.DomQuery DomQuery}:<code><pre>
49 // Function receives array and returns a filtered array.
50 Ext.ComponentQuery.pseudos.invalid = function(items) {
51 var i = 0, l = items.length, c, result = [];
52 for (; i < l; i++) {
53 if (!(c = items[i]).isValid()) {
60 var invalidFields = myFormPanel.query('field:invalid');
61 if (invalidFields.length) {
62 invalidFields[0].getEl().scrollIntoView(myFormPanel.body);
63 for (var i = 0, l = invalidFields.length; i < l; i++) {
64 invalidFields[i].getEl().frame("red");
67 </pre></code>
69 * Default pseudos include:<br />
73 * Queries return an array of components.
74 * Here are some example queries.
75 <pre><code>
76 // retrieve all Ext.Panels in the document by xtype
77 var panelsArray = Ext.ComponentQuery.query('panel');
79 // retrieve all Ext.Panels within the container with an id myCt
80 var panelsWithinmyCt = Ext.ComponentQuery.query('#myCt panel');
82 // retrieve all direct children which are Ext.Panels within myCt
83 var directChildPanel = Ext.ComponentQuery.query('#myCt > panel');
85 // retrieve all gridpanels and listviews
86 var gridsAndLists = Ext.ComponentQuery.query('gridpanel, listview');
87 </code></pre>
89 For easy access to queries based from a particular Container see the {@link Ext.container.Container#query},
90 {@link Ext.container.Container#down} and {@link Ext.container.Container#child} methods. Also see
91 {@link Ext.Component#up}.
94 Ext.define('Ext.ComponentQuery', {
96 uses: ['Ext.ComponentManager']
101 // A function source code pattern with a placeholder which accepts an expression which yields a truth value when applied
102 // as a member on each item in the passed array.
109 'for (; i < l; i++) {',
118 filterItems = function(items, operation) {
119 // Argument list for the operation is [ itemsArray, operationArg1, operationArg2...]
120 // The operation's method loops over each item in the candidate array and
121 // returns an array of items which match its criteria
122 return operation.method.apply(this, [ items ].concat(operation.args));
125 getItems = function(items, mode) {
128 length = items.length,
130 deep = mode !== '>';
132 for (; i < length; i++) {
133 candidate = items[i];
134 if (candidate.getRefItems) {
135 result = result.concat(candidate.getRefItems(deep));
141 getAncestors = function(items) {
144 length = items.length,
146 for (; i < length; i++) {
147 candidate = items[i];
148 while (!!(candidate = (candidate.ownerCt || candidate.floatParent))) {
149 result.push(candidate);
155 // Filters the passed candidate array and returns only items which match the passed xtype
156 filterByXType = function(items, xtype, shallow) {
158 return items.slice();
163 length = items.length,
165 for (; i < length; i++) {
166 candidate = items[i];
167 if (candidate.isXType(xtype, shallow)) {
168 result.push(candidate);
175 // Filters the passed candidate array and returns only items which have the passed className
176 filterByClassName = function(items, className) {
180 length = items.length,
182 for (; i < length; i++) {
183 candidate = items[i];
184 if (candidate.el ? candidate.el.hasCls(className) : EA.contains(candidate.initCls(), className)) {
185 result.push(candidate);
191 // Filters the passed candidate array and returns only items which have the specified property match
192 filterByAttribute = function(items, property, operator, value) {
195 length = items.length,
197 for (; i < length; i++) {
198 candidate = items[i];
199 if (!value ? !!candidate[property] : (String(candidate[property]) === value)) {
200 result.push(candidate);
206 // Filters the passed candidate array and returns only items which have the specified itemId or id
207 filterById = function(items, id) {
210 length = items.length,
212 for (; i < length; i++) {
213 candidate = items[i];
214 if (candidate.getItemId() === id) {
215 result.push(candidate);
221 // Filters the passed candidate array and returns only items which the named pseudo class matcher filters in
222 filterByPseudo = function(items, name, value) {
223 return cq.pseudos[name](items, value);
226 // Determines leading mode
227 // > for direct child, and ^ to switch to ownerCt axis
228 modeRe = /^(\s?([>\^])\s?|\s|$)/,
230 // Matches a token with possibly (true|false) appended for the "shallow" parameter
231 tokenRe = /^(#)?([\w\-]+|\*)(?:\((true|false)\))?/,
234 // Checks for .xtype with possibly (true|false) appended for the "shallow" parameter
235 re: /^\.([\w\-]+)(?:\((true|false)\))?/,
236 method: filterByXType
238 // checks for [attribute=value]
239 re: /^(?:[\[](?:@)?([\w\-]+)\s?(?:(=|.=)\s?['"]?(.*?)["']?)?[\]])/,
240 method: filterByAttribute
242 // checks for #cmpItemId
246 // checks for :<pseudo_class>(<selector>)
247 re: /^\:([\w\-]+)(?:\(((?:\{[^\}]+\})|(?:(?!\{)[^\s>\/]*?(?!\})))\))?/,
248 method: filterByPseudo
250 // checks for {<member_expression>}
251 re: /^(?:\{([^\}]+)\})/,
252 method: filterFnPattern
255 <span id='Ext-ComponentQuery-Query'> /**
256 </span> * @class Ext.ComponentQuery.Query
260 cq.Query = Ext.extend(Object, {
261 constructor: function(cfg) {
263 Ext.apply(this, cfg);
266 <span id='Ext-ComponentQuery-Query-method-execute'> /**
268 * Executes this Query upon the selected root.
269 * The root provides the initial source of candidate Component matches which are progressively
270 * filtered by iterating through this Query's operations cache.
271 * If no root is provided, all registered Components are searched via the ComponentManager.
272 * root may be a Container who's descendant Components are filtered
273 * root may be a Component with an implementation of getRefItems which provides some nested Components such as the
274 * docked items within a Panel.
275 * root may be an array of candidate Components to filter using this Query.
277 execute : function(root) {
278 var operations = this.operations,
280 length = operations.length,
284 // no root, use all Components in the document
286 workingItems = Ext.ComponentManager.all.getArray();
288 // Root is a candidate Array
289 else if (Ext.isArray(root)) {
293 // We are going to loop over our operations and take care of them
295 for (; i < length; i++) {
296 operation = operations[i];
298 // The mode operation requires some custom handling.
299 // All other operations essentially filter down our current
300 // working items, while mode replaces our current working
301 // items by getting children from each one of our current
302 // working items. The type of mode determines the type of
303 // children we get. (e.g. > only gets direct children)
304 if (operation.mode === '^') {
305 workingItems = getAncestors(workingItems || [root]);
307 else if (operation.mode) {
308 workingItems = getItems(workingItems || [root], operation.mode);
311 workingItems = filterItems(workingItems || getItems([root]), operation);
314 // If this is the last operation, it means our current working
315 // items are the final matched items. Thus return them!
316 if (i === length -1) {
323 is: function(component) {
324 var operations = this.operations,
325 components = Ext.isArray(component) ? component : [component],
326 originalLength = components.length,
327 lastOperation = operations[operations.length-1],
330 components = filterItems(components, lastOperation);
331 if (components.length === originalLength) {
332 if (operations.length > 1) {
333 for (i = 0, ln = components.length; i < ln; i++) {
334 if (Ext.Array.indexOf(this.execute(), components[i]) === -1) {
347 // private cache of selectors and matching ComponentQuery.Query objects
350 // private cache of pseudo class filter functions
352 not: function(components, selector){
353 var CQ = Ext.ComponentQuery,
355 length = components.length,
360 for(; i < length; ++i) {
361 component = components[i];
362 if (!CQ.is(component, selector)) {
363 results[++index] = component;
370 <span id='Ext-ComponentQuery-method-query'> /**
371 </span> * <p>Returns an array of matched Components from within the passed root object.</p>
372 * <p>This method filters returned Components in a similar way to how CSS selector based DOM
373 * queries work using a textual selector string.</p>
374 * <p>See class summary for details.</p>
375 * @param selector The selector string to filter returned Components
376 * @param root <p>The Container within which to perform the query. If omitted, all Components
377 * within the document are included in the search.</p>
378 * <p>This parameter may also be an array of Components to filter according to the selector.</p>
379 * @returns {Array} The matched Components.
380 * @member Ext.ComponentQuery
382 query: function(selector, root) {
383 var selectors = selector.split(','),
384 length = selectors.length,
389 query, resultsLn, cmp;
391 for (; i < length; i++) {
392 selector = Ext.String.trim(selectors[i]);
393 query = this.cache[selector];
395 this.cache[selector] = query = this.parse(selector);
397 results = results.concat(query.execute(root));
400 // multiple selectors, potential to find duplicates
401 // lets filter them out.
403 resultsLn = results.length;
404 for (i = 0; i < resultsLn; i++) {
406 if (!dupMatcher[cmp.id]) {
407 noDupResults.push(cmp);
408 dupMatcher[cmp.id] = true;
411 results = noDupResults;
416 <span id='Ext-ComponentQuery-method-is'> /**
417 </span> * Tests whether the passed Component matches the selector string.
418 * @param component The Component to test
419 * @param selector The selector string to test against.
420 * @return {Boolean} True if the Component matches the selector.
421 * @member Ext.ComponentQuery
423 is: function(component, selector) {
427 var query = this.cache[selector];
429 this.cache[selector] = query = this.parse(selector);
431 return query.is(component);
434 parse: function(selector) {
436 length = matchers.length,
444 // We are going to parse the beginning of the selector over and
445 // over again, slicing off the selector any portions we converted into an
446 // operation, until it is an empty string.
447 while (selector && lastSelector !== selector) {
448 lastSelector = selector;
450 // First we check if we are dealing with a token like #, * or an xtype
451 tokenMatch = selector.match(tokenRe);
454 matchedChar = tokenMatch[1];
456 // If the token is prefixed with a # we push a filterById operation to our stack
457 if (matchedChar === '#') {
460 args: [Ext.String.trim(tokenMatch[2])]
463 // If the token is prefixed with a . we push a filterByClassName operation to our stack
464 // FIXME: Not enabled yet. just needs \. adding to the tokenRe prefix
465 else if (matchedChar === '.') {
467 method: filterByClassName,
468 args: [Ext.String.trim(tokenMatch[2])]
471 // If the token is a * or an xtype string, we push a filterByXType
472 // operation to the stack.
475 method: filterByXType,
476 args: [Ext.String.trim(tokenMatch[2]), Boolean(tokenMatch[3])]
480 // Now we slice of the part we just converted into an operation
481 selector = selector.replace(tokenMatch[0], '');
484 // If the next part of the query is not a space or > or ^, it means we
485 // are going to check for more things that our current selection
487 while (!(modeMatch = selector.match(modeRe))) {
488 // Lets loop over each type of matcher and execute it
489 // on our current selector.
490 for (i = 0; selector && i < length; i++) {
491 matcher = matchers[i];
492 selectorMatch = selector.match(matcher.re);
493 method = matcher.method;
495 // If we have a match, add an operation with the method
496 // associated with this matcher, and pass the regular
497 // expression matches are arguments to the operation.
500 method: Ext.isString(matcher.method)
501 // Turn a string method into a function by formatting the string with our selector matche expression
502 // A new method is created for different match expressions, eg {id=='textfield-1024'}
503 // Every expression may be different in different selectors.
504 ? Ext.functionFactory('items', Ext.String.format.apply(Ext.String, [method].concat(selectorMatch.slice(1))))
506 args: selectorMatch.slice(1)
508 selector = selector.replace(selectorMatch[0], '');
509 break; // Break on match
512 // Exhausted all matches: It's an error
513 if (i === (length - 1)) {
514 Ext.Error.raise('Invalid ComponentQuery selector: "' + arguments[0] + '"');
520 // Now we are going to check for a mode change. This means a space
521 // or a > to determine if we are going to select all the children
522 // of the currently matched items, or a ^ if we are going to use the
523 // ownerCt axis as the candidate source.
524 if (modeMatch[1]) { // Assignment, and test for truthiness!
526 mode: modeMatch[2]||modeMatch[1]
528 selector = selector.replace(modeMatch[0], '');
532 // Now that we have all our operations in an array, we are going
533 // to create a new Query using these operations.
534 return new cq.Query({
535 operations: operations