Upgrade to ExtJS 3.0.3 - Released 10/11/2009
[extjs.git] / src / widgets / Container.js
1 /*!
2  * Ext JS Library 3.0.3
3  * Copyright(c) 2006-2009 Ext JS, LLC
4  * licensing@extjs.com
5  * http://www.extjs.com/license
6  */
7 /**\r
8  * @class Ext.Container\r
9  * @extends Ext.BoxComponent\r
10  * <p>Base class for any {@link Ext.BoxComponent} that may contain other Components. Containers handle the\r
11  * basic behavior of containing items, namely adding, inserting and removing items.</p>\r
12  *\r
13  * <p>The most commonly used Container classes are {@link Ext.Panel}, {@link Ext.Window} and {@link Ext.TabPanel}.\r
14  * If you do not need the capabilities offered by the aforementioned classes you can create a lightweight\r
15  * Container to be encapsulated by an HTML element to your specifications by using the\r
16  * <tt><b>{@link Ext.Component#autoEl autoEl}</b></tt> config option. This is a useful technique when creating\r
17  * embedded {@link Ext.layout.ColumnLayout column} layouts inside {@link Ext.form.FormPanel FormPanels}\r
18  * for example.</p>\r
19  *\r
20  * <p>The code below illustrates both how to explicitly create a Container, and how to implicitly\r
21  * create one using the <b><tt>'container'</tt></b> xtype:<pre><code>\r
22 // explicitly create a Container\r
23 var embeddedColumns = new Ext.Container({\r
24     autoEl: 'div',  // This is the default\r
25     layout: 'column',\r
26     defaults: {\r
27         // implicitly create Container by specifying xtype\r
28         xtype: 'container',\r
29         autoEl: 'div', // This is the default.\r
30         layout: 'form',\r
31         columnWidth: 0.5,\r
32         style: {\r
33             padding: '10px'\r
34         }\r
35     },\r
36 //  The two items below will be Ext.Containers, each encapsulated by a &lt;DIV> element.\r
37     items: [{\r
38         items: {\r
39             xtype: 'datefield',\r
40             name: 'startDate',\r
41             fieldLabel: 'Start date'\r
42         }\r
43     }, {\r
44         items: {\r
45             xtype: 'datefield',\r
46             name: 'endDate',\r
47             fieldLabel: 'End date'\r
48         }\r
49     }]\r
50 });</code></pre></p>\r
51  *\r
52  * <p><u><b>Layout</b></u></p>\r
53  * <p>Container classes delegate the rendering of child Components to a layout\r
54  * manager class which must be configured into the Container using the\r
55  * <code><b>{@link #layout}</b></code> configuration property.</p>\r
56  * <p>When either specifying child <code>{@link #items}</code> of a Container,\r
57  * or dynamically {@link #add adding} Components to a Container, remember to\r
58  * consider how you wish the Container to arrange those child elements, and\r
59  * whether those child elements need to be sized using one of Ext's built-in\r
60  * <b><code>{@link #layout}</code></b> schemes. By default, Containers use the\r
61  * {@link Ext.layout.ContainerLayout ContainerLayout} scheme which only\r
62  * renders child components, appending them one after the other inside the\r
63  * Container, and <b>does not apply any sizing</b> at all.</p>\r
64  * <p>A common mistake is when a developer neglects to specify a\r
65  * <b><code>{@link #layout}</code></b> (e.g. widgets like GridPanels or\r
66  * TreePanels are added to Containers for which no <tt><b>{@link #layout}</b></tt>\r
67  * has been specified). If a Container is left to use the default\r
68  * {@link Ext.layout.ContainerLayout ContainerLayout} scheme, none of its\r
69  * child components will be resized, or changed in any way when the Container\r
70  * is resized.</p>\r
71  * <p>Certain layout managers allow dynamic addition of child components.\r
72  * Those that do include {@link Ext.layout.CardLayout},\r
73  * {@link Ext.layout.AnchorLayout}, {@link Ext.layout.FormLayout}, and\r
74  * {@link Ext.layout.TableLayout}. For example:<pre><code>\r
75 //  Create the GridPanel.\r
76 var myNewGrid = new Ext.grid.GridPanel({\r
77     store: myStore,\r
78     columns: myColumnModel,\r
79     title: 'Results', // the title becomes the title of the tab\r
80 });\r
81 \r
82 myTabPanel.add(myNewGrid); // {@link Ext.TabPanel} implicitly uses {@link Ext.layout.CardLayout CardLayout}\r
83 myTabPanel.{@link Ext.TabPanel#setActiveTab setActiveTab}(myNewGrid);\r
84  * </code></pre></p>\r
85  * <p>The example above adds a newly created GridPanel to a TabPanel. Note that\r
86  * a TabPanel uses {@link Ext.layout.CardLayout} as its layout manager which\r
87  * means all its child items are sized to {@link Ext.layout.FitLayout fit}\r
88  * exactly into its client area.\r
89  * <p><b><u>Overnesting is a common problem</u></b>.\r
90  * An example of overnesting occurs when a GridPanel is added to a TabPanel\r
91  * by wrapping the GridPanel <i>inside</i> a wrapping Panel (that has no\r
92  * <tt><b>{@link #layout}</b></tt> specified) and then add that wrapping Panel\r
93  * to the TabPanel. The point to realize is that a GridPanel <b>is</b> a\r
94  * Component which can be added directly to a Container. If the wrapping Panel\r
95  * has no <tt><b>{@link #layout}</b></tt> configuration, then the overnested\r
96  * GridPanel will not be sized as expected.<p>\r
97  *\r
98  * <p><u><b>Adding via remote configuration</b></u></p>\r
99  *\r
100  * <p>A server side script can be used to add Components which are generated dynamically on the server.\r
101  * An example of adding a GridPanel to a TabPanel where the GridPanel is generated by the server\r
102  * based on certain parameters:\r
103  * </p><pre><code>\r
104 // execute an Ajax request to invoke server side script:\r
105 Ext.Ajax.request({\r
106     url: 'gen-invoice-grid.php',\r
107     // send additional parameters to instruct server script\r
108     params: {\r
109         startDate: Ext.getCmp('start-date').getValue(),\r
110         endDate: Ext.getCmp('end-date').getValue()\r
111     },\r
112     // process the response object to add it to the TabPanel:\r
113     success: function(xhr) {\r
114         var newComponent = eval(xhr.responseText); // see discussion below\r
115         myTabPanel.add(newComponent); // add the component to the TabPanel\r
116         myTabPanel.setActiveTab(newComponent);\r
117     },\r
118     failure: function() {\r
119         Ext.Msg.alert("Grid create failed", "Server communication failure");\r
120     }\r
121 });\r
122 </code></pre>\r
123  * <p>The server script needs to return an executable Javascript statement which, when processed\r
124  * using <tt>eval()</tt>, will return either a config object with an {@link Ext.Component#xtype xtype},\r
125  * or an instantiated Component. The server might return this for example:</p><pre><code>\r
126 (function() {\r
127     function formatDate(value){\r
128         return value ? value.dateFormat('M d, Y') : '';\r
129     };\r
130 \r
131     var store = new Ext.data.Store({\r
132         url: 'get-invoice-data.php',\r
133         baseParams: {\r
134             startDate: '01/01/2008',\r
135             endDate: '01/31/2008'\r
136         },\r
137         reader: new Ext.data.JsonReader({\r
138             record: 'transaction',\r
139             idProperty: 'id',\r
140             totalRecords: 'total'\r
141         }, [\r
142            'customer',\r
143            'invNo',\r
144            {name: 'date', type: 'date', dateFormat: 'm/d/Y'},\r
145            {name: 'value', type: 'float'}\r
146         ])\r
147     });\r
148 \r
149     var grid = new Ext.grid.GridPanel({\r
150         title: 'Invoice Report',\r
151         bbar: new Ext.PagingToolbar(store),\r
152         store: store,\r
153         columns: [\r
154             {header: "Customer", width: 250, dataIndex: 'customer', sortable: true},\r
155             {header: "Invoice Number", width: 120, dataIndex: 'invNo', sortable: true},\r
156             {header: "Invoice Date", width: 100, dataIndex: 'date', renderer: formatDate, sortable: true},\r
157             {header: "Value", width: 120, dataIndex: 'value', renderer: 'usMoney', sortable: true}\r
158         ],\r
159     });\r
160     store.load();\r
161     return grid;  // return instantiated component\r
162 })();\r
163 </code></pre>\r
164  * <p>When the above code fragment is passed through the <tt>eval</tt> function in the success handler\r
165  * of the Ajax request, the code is executed by the Javascript processor, and the anonymous function\r
166  * runs, and returns the instantiated grid component.</p>\r
167  * <p>Note: since the code above is <i>generated</i> by a server script, the <tt>baseParams</tt> for\r
168  * the Store, the metadata to allow generation of the Record layout, and the ColumnModel\r
169  * can all be generated into the code since these are all known on the server.</p>\r
170  *\r
171  * @xtype container\r
172  */\r
173 Ext.Container = Ext.extend(Ext.BoxComponent, {\r
174     /**\r
175      * @cfg {Boolean} monitorResize\r
176      * True to automatically monitor window resize events to handle anything that is sensitive to the current size\r
177      * of the viewport.  This value is typically managed by the chosen <code>{@link #layout}</code> and should not need\r
178      * to be set manually.\r
179      */\r
180     /**\r
181      * @cfg {String/Object} layout\r
182      * <p><b>*Important</b>: In order for child items to be correctly sized and\r
183      * positioned, typically a layout manager <b>must</b> be specified through\r
184      * the <code>layout</code> configuration option.</p>\r
185      * <br><p>The sizing and positioning of child {@link items} is the responsibility of\r
186      * the Container's layout manager which creates and manages the type of layout\r
187      * you have in mind.  For example:</p><pre><code>\r
188 new Ext.Window({\r
189     width:300, height: 300,\r
190     layout: 'fit', // explicitly set layout manager: override the default (layout:'auto')\r
191     items: [{\r
192         title: 'Panel inside a Window'\r
193     }]\r
194 }).show();\r
195      * </code></pre>\r
196      * <p>If the {@link #layout} configuration is not explicitly specified for\r
197      * a general purpose container (e.g. Container or Panel) the\r
198      * {@link Ext.layout.ContainerLayout default layout manager} will be used\r
199      * which does nothing but render child components sequentially into the\r
200      * Container (no sizing or positioning will be performed in this situation).\r
201      * Some container classes implicitly specify a default layout\r
202      * (e.g. FormPanel specifies <code>layout:'form'</code>). Other specific\r
203      * purpose classes internally specify/manage their internal layout (e.g.\r
204      * GridPanel, TabPanel, TreePanel, Toolbar, Menu, etc.).</p>\r
205      * <br><p><b><code>layout</code></b> may be specified as either as an Object or\r
206      * as a String:</p><div><ul class="mdetail-params">\r
207      *\r
208      * <li><u>Specify as an Object</u></li>\r
209      * <div><ul class="mdetail-params">\r
210      * <li>Example usage:</li>\r
211 <pre><code>\r
212 layout: {\r
213     type: 'vbox',\r
214     padding: '5',\r
215     align: 'left'\r
216 }\r
217 </code></pre>\r
218      *\r
219      * <li><tt><b>type</b></tt></li>\r
220      * <br/><p>The layout type to be used for this container.  If not specified,\r
221      * a default {@link Ext.layout.ContainerLayout} will be created and used.</p>\r
222      * <br/><p>Valid layout <tt>type</tt> values are:</p>\r
223      * <div class="sub-desc"><ul class="mdetail-params">\r
224      * <li><tt><b>{@link Ext.layout.AbsoluteLayout absolute}</b></tt></li>\r
225      * <li><tt><b>{@link Ext.layout.AccordionLayout accordion}</b></tt></li>\r
226      * <li><tt><b>{@link Ext.layout.AnchorLayout anchor}</b></tt></li>\r
227      * <li><tt><b>{@link Ext.layout.ContainerLayout auto}</b></tt> &nbsp;&nbsp;&nbsp; <b>Default</b></li>\r
228      * <li><tt><b>{@link Ext.layout.BorderLayout border}</b></tt></li>\r
229      * <li><tt><b>{@link Ext.layout.CardLayout card}</b></tt></li>\r
230      * <li><tt><b>{@link Ext.layout.ColumnLayout column}</b></tt></li>\r
231      * <li><tt><b>{@link Ext.layout.FitLayout fit}</b></tt></li>\r
232      * <li><tt><b>{@link Ext.layout.FormLayout form}</b></tt></li>\r
233      * <li><tt><b>{@link Ext.layout.HBoxLayout hbox}</b></tt></li>\r
234      * <li><tt><b>{@link Ext.layout.MenuLayout menu}</b></tt></li>\r
235      * <li><tt><b>{@link Ext.layout.TableLayout table}</b></tt></li>\r
236      * <li><tt><b>{@link Ext.layout.ToolbarLayout toolbar}</b></tt></li>\r
237      * <li><tt><b>{@link Ext.layout.VBoxLayout vbox}</b></tt></li>\r
238      * </ul></div>\r
239      *\r
240      * <li>Layout specific configuration properties</li>\r
241      * <br/><p>Additional layout specific configuration properties may also be\r
242      * specified. For complete details regarding the valid config options for\r
243      * each layout type, see the layout class corresponding to the <tt>type</tt>\r
244      * specified.</p>\r
245      *\r
246      * </ul></div>\r
247      *\r
248      * <li><u>Specify as a String</u></li>\r
249      * <div><ul class="mdetail-params">\r
250      * <li>Example usage:</li>\r
251 <pre><code>\r
252 layout: 'vbox',\r
253 layoutConfig: {\r
254     padding: '5',\r
255     align: 'left'\r
256 }\r
257 </code></pre>\r
258      * <li><tt><b>layout</b></tt></li>\r
259      * <br/><p>The layout <tt>type</tt> to be used for this container (see list\r
260      * of valid layout type values above).</p><br/>\r
261      * <li><tt><b>{@link #layoutConfig}</b></tt></li>\r
262      * <br/><p>Additional layout specific configuration properties. For complete\r
263      * details regarding the valid config options for each layout type, see the\r
264      * layout class corresponding to the <tt>layout</tt> specified.</p>\r
265      * </ul></div></ul></div>\r
266      */\r
267     /**\r
268      * @cfg {Object} layoutConfig\r
269      * This is a config object containing properties specific to the chosen\r
270      * <b><code>{@link #layout}</code></b> if <b><code>{@link #layout}</code></b>\r
271      * has been specified as a <i>string</i>.</p>\r
272      */\r
273     /**\r
274      * @cfg {Boolean/Number} bufferResize\r
275      * When set to true (50 milliseconds) or a number of milliseconds, the layout assigned for this container will buffer\r
276      * the frequency it calculates and does a re-layout of components. This is useful for heavy containers or containers\r
277      * with a large quantity of sub-components for which frequent layout calls would be expensive. Defaults to <tt>50</tt>.\r
278      */\r
279     bufferResize: 50,\r
280 \r
281     /**\r
282      * @cfg {String/Number} activeItem\r
283      * A string component id or the numeric index of the component that should be initially activated within the\r
284      * container's layout on render.  For example, activeItem: 'item-1' or activeItem: 0 (index 0 = the first\r
285      * item in the container's collection).  activeItem only applies to layout styles that can display\r
286      * items one at a time (like {@link Ext.layout.AccordionLayout}, {@link Ext.layout.CardLayout} and\r
287      * {@link Ext.layout.FitLayout}).  Related to {@link Ext.layout.ContainerLayout#activeItem}.\r
288      */\r
289     /**\r
290      * @cfg {Object/Array} items\r
291      * <pre><b>** IMPORTANT</b>: be sure to <b>{@link #layout specify a <code>layout</code>} if needed ! **</b></pre>\r
292      * <p>A single item, or an array of child Components to be added to this container,\r
293      * for example:</p>\r
294      * <pre><code>\r
295 // specifying a single item\r
296 items: {...},\r
297 layout: 'fit',    // specify a layout!\r
298 \r
299 // specifying multiple items\r
300 items: [{...}, {...}],\r
301 layout: 'anchor', // specify a layout!\r
302      * </code></pre>\r
303      * <p>Each item may be:</p>\r
304      * <div><ul class="mdetail-params">\r
305      * <li>any type of object based on {@link Ext.Component}</li>\r
306      * <li>a fully instanciated object or</li>\r
307      * <li>an object literal that:</li>\r
308      * <div><ul class="mdetail-params">\r
309      * <li>has a specified <code>{@link Ext.Component#xtype xtype}</code></li>\r
310      * <li>the {@link Ext.Component#xtype} specified is associated with the Component\r
311      * desired and should be chosen from one of the available xtypes as listed\r
312      * in {@link Ext.Component}.</li>\r
313      * <li>If an <code>{@link Ext.Component#xtype xtype}</code> is not explicitly\r
314      * specified, the {@link #defaultType} for that Container is used.</li>\r
315      * <li>will be "lazily instanciated", avoiding the overhead of constructing a fully\r
316      * instanciated Component object</li>\r
317      * </ul></div></ul></div>\r
318      * <p><b>Notes</b>:</p>\r
319      * <div><ul class="mdetail-params">\r
320      * <li>Ext uses lazy rendering. Child Components will only be rendered\r
321      * should it become necessary. Items are automatically laid out when they are first\r
322      * shown (no sizing is done while hidden), or in response to a {@link #doLayout} call.</li>\r
323      * <li>Do not specify <code>{@link Ext.Panel#contentEl contentEl}</code>/\r
324      * <code>{@link Ext.Panel#html html}</code> with <code>items</code>.</li>\r
325      * </ul></div>\r
326      */\r
327     /**\r
328      * @cfg {Object} defaults\r
329      * <p>A config object that will be applied to all components added to this container either via the {@link #items}\r
330      * config or via the {@link #add} or {@link #insert} methods.  The <tt>defaults</tt> config can contain any\r
331      * number of name/value property pairs to be added to each item, and should be valid for the types of items\r
332      * being added to the container.  For example, to automatically apply padding to the body of each of a set of\r
333      * contained {@link Ext.Panel} items, you could pass: <tt>defaults: {bodyStyle:'padding:15px'}</tt>.</p><br/>\r
334      * <p><b>Note</b>: <tt>defaults</tt> will not be applied to config objects if the option is already specified.\r
335      * For example:</p><pre><code>\r
336 defaults: {               // defaults are applied to items, not the container\r
337     autoScroll:true\r
338 },\r
339 items: [\r
340     {\r
341         xtype: 'panel',   // defaults <b>do not</b> have precedence over\r
342         id: 'panel1',     // options in config objects, so the defaults\r
343         autoScroll: false // will not be applied here, panel1 will be autoScroll:false\r
344     },\r
345     new Ext.Panel({       // defaults <b>do</b> have precedence over options\r
346         id: 'panel2',     // options in components, so the defaults\r
347         autoScroll: false // will be applied here, panel2 will be autoScroll:true.\r
348     })\r
349 ]\r
350      * </code></pre>\r
351      */\r
352 \r
353 \r
354     /** @cfg {Boolean} autoDestroy\r
355      * If true the container will automatically destroy any contained component that is removed from it, else\r
356      * destruction must be handled manually (defaults to true).\r
357      */\r
358     autoDestroy : true,\r
359 \r
360     /** @cfg {Boolean} forceLayout\r
361      * If true the container will force a layout initially even if hidden or collapsed. This option\r
362      * is useful for forcing forms to render in collapsed or hidden containers. (defaults to false).\r
363      */\r
364     forceLayout: false,\r
365 \r
366     /** @cfg {Boolean} hideBorders\r
367      * True to hide the borders of each contained component, false to defer to the component's existing\r
368      * border settings (defaults to false).\r
369      */\r
370     /** @cfg {String} defaultType\r
371      * <p>The default {@link Ext.Component xtype} of child Components to create in this Container when\r
372      * a child item is specified as a raw configuration object, rather than as an instantiated Component.</p>\r
373      * <p>Defaults to <tt>'panel'</tt>, except {@link Ext.menu.Menu} which defaults to <tt>'menuitem'</tt>,\r
374      * and {@link Ext.Toolbar} and {@link Ext.ButtonGroup} which default to <tt>'button'</tt>.</p>\r
375      */\r
376     defaultType : 'panel',\r
377 \r
378     /** @cfg {String} resizeEvent\r
379      * The event to listen to for resizing in layouts. Defaults to <tt>'resize'</tt>.\r
380      */\r
381     resizeEvent: 'resize',\r
382     \r
383     /**\r
384      * @cfg {Array} bubbleEvents\r
385      * <p>An array of events that, when fired, should be bubbled to any parent container.\r
386      * Defaults to <tt>['add', 'remove']</tt>.\r
387      */\r
388     bubbleEvents: ['add', 'remove'],\r
389 \r
390     // private\r
391     initComponent : function(){\r
392         Ext.Container.superclass.initComponent.call(this);\r
393 \r
394         this.addEvents(\r
395             /**\r
396              * @event afterlayout\r
397              * Fires when the components in this container are arranged by the associated layout manager.\r
398              * @param {Ext.Container} this\r
399              * @param {ContainerLayout} layout The ContainerLayout implementation for this container\r
400              */\r
401             'afterlayout',\r
402             /**\r
403              * @event beforeadd\r
404              * Fires before any {@link Ext.Component} is added or inserted into the container.\r
405              * A handler can return false to cancel the add.\r
406              * @param {Ext.Container} this\r
407              * @param {Ext.Component} component The component being added\r
408              * @param {Number} index The index at which the component will be added to the container's items collection\r
409              */\r
410             'beforeadd',\r
411             /**\r
412              * @event beforeremove\r
413              * Fires before any {@link Ext.Component} is removed from the container.  A handler can return\r
414              * false to cancel the remove.\r
415              * @param {Ext.Container} this\r
416              * @param {Ext.Component} component The component being removed\r
417              */\r
418             'beforeremove',\r
419             /**\r
420              * @event add\r
421              * @bubbles\r
422              * Fires after any {@link Ext.Component} is added or inserted into the container.\r
423              * @param {Ext.Container} this\r
424              * @param {Ext.Component} component The component that was added\r
425              * @param {Number} index The index at which the component was added to the container's items collection\r
426              */\r
427             'add',\r
428             /**\r
429              * @event remove\r
430              * @bubbles\r
431              * Fires after any {@link Ext.Component} is removed from the container.\r
432              * @param {Ext.Container} this\r
433              * @param {Ext.Component} component The component that was removed\r
434              */\r
435             'remove'\r
436         );\r
437 \r
438         this.enableBubble(this.bubbleEvents);\r
439 \r
440         /**\r
441          * The collection of components in this container as a {@link Ext.util.MixedCollection}\r
442          * @type MixedCollection\r
443          * @property items\r
444          */\r
445         var items = this.items;\r
446         if(items){\r
447             delete this.items;\r
448             this.add(items);\r
449         }\r
450     },\r
451 \r
452     // private\r
453     initItems : function(){\r
454         if(!this.items){\r
455             this.items = new Ext.util.MixedCollection(false, this.getComponentId);\r
456             this.getLayout(); // initialize the layout\r
457         }\r
458     },\r
459 \r
460     // private\r
461     setLayout : function(layout){\r
462         if(this.layout && this.layout != layout){\r
463             this.layout.setContainer(null);\r
464         }\r
465         this.initItems();\r
466         this.layout = layout;\r
467         layout.setContainer(this);\r
468     },\r
469 \r
470     afterRender: function(){\r
471         Ext.Container.superclass.afterRender.call(this);\r
472         if(!this.layout){\r
473             this.layout = 'auto';\r
474         }\r
475         if(Ext.isObject(this.layout) && !this.layout.layout){\r
476             this.layoutConfig = this.layout;\r
477             this.layout = this.layoutConfig.type;\r
478         }\r
479         if(Ext.isString(this.layout)){\r
480             this.layout = new Ext.Container.LAYOUTS[this.layout.toLowerCase()](this.layoutConfig);\r
481         }\r
482         this.setLayout(this.layout);\r
483 \r
484         if(this.activeItem !== undefined){\r
485             var item = this.activeItem;\r
486             delete this.activeItem;\r
487             this.layout.setActiveItem(item);\r
488         }\r
489         if(!this.ownerCt){\r
490             // force a layout if no ownerCt is set\r
491             this.doLayout(false, true);\r
492         }\r
493         if(this.monitorResize === true){\r
494             Ext.EventManager.onWindowResize(this.doLayout, this, [false]);\r
495         }\r
496     },\r
497 \r
498     /**\r
499      * <p>Returns the Element to be used to contain the child Components of this Container.</p>\r
500      * <p>An implementation is provided which returns the Container's {@link #getEl Element}, but\r
501      * if there is a more complex structure to a Container, this may be overridden to return\r
502      * the element into which the {@link #layout layout} renders child Components.</p>\r
503      * @return {Ext.Element} The Element to render child Components into.\r
504      */\r
505     getLayoutTarget : function(){\r
506         return this.el;\r
507     },\r
508 \r
509     // private - used as the key lookup function for the items collection\r
510     getComponentId : function(comp){\r
511         return comp.getItemId();\r
512     },\r
513 \r
514     /**\r
515      * <p>Adds {@link Ext.Component Component}(s) to this Container.</p>\r
516      * <br><p><b>Description</b></u> :\r
517      * <div><ul class="mdetail-params">\r
518      * <li>Fires the {@link #beforeadd} event before adding</li>\r
519      * <li>The Container's {@link #defaults default config values} will be applied\r
520      * accordingly (see <code>{@link #defaults}</code> for details).</li>\r
521      * <li>Fires the {@link #add} event after the component has been added.</li>\r
522      * </ul></div>\r
523      * <br><p><b>Notes</b></u> :\r
524      * <div><ul class="mdetail-params">\r
525      * <li>If the Container is <i>already rendered</i> when <tt>add</tt>\r
526      * is called, you may need to call {@link #doLayout} to refresh the view which causes\r
527      * any unrendered child Components to be rendered. This is required so that you can\r
528      * <tt>add</tt> multiple child components if needed while only refreshing the layout\r
529      * once. For example:<pre><code>\r
530 var tb = new {@link Ext.Toolbar}();\r
531 tb.render(document.body);  // toolbar is rendered\r
532 tb.add({text:'Button 1'}); // add multiple items ({@link #defaultType} for {@link Ext.Toolbar Toolbar} is 'button')\r
533 tb.add({text:'Button 2'});\r
534 tb.{@link #doLayout}();             // refresh the layout\r
535      * </code></pre></li>\r
536      * <li><i>Warning:</i> Containers directly managed by the BorderLayout layout manager\r
537      * may not be removed or added.  See the Notes for {@link Ext.layout.BorderLayout BorderLayout}\r
538      * for more details.</li>\r
539      * </ul></div>\r
540      * @param {Object/Array} component\r
541      * <p>Either a single component or an Array of components to add.  See\r
542      * <code>{@link #items}</code> for additional information.</p>\r
543      * @param {Object} (Optional) component_2\r
544      * @param {Object} (Optional) component_n\r
545      * @return {Ext.Component} component The Component (or config object) that was added.\r
546      */\r
547     add : function(comp){\r
548         this.initItems();\r
549         var args = arguments.length > 1;\r
550         if(args || Ext.isArray(comp)){\r
551             Ext.each(args ? arguments : comp, function(c){\r
552                 this.add(c);\r
553             }, this);\r
554             return;\r
555         }\r
556         var c = this.lookupComponent(this.applyDefaults(comp));\r
557         var pos = this.items.length;\r
558         if(this.fireEvent('beforeadd', this, c, pos) !== false && this.onBeforeAdd(c) !== false){\r
559             this.items.add(c);\r
560             c.ownerCt = this;\r
561             this.onAdd(c);\r
562             this.fireEvent('add', this, c, pos);\r
563         }\r
564         return c;\r
565     },\r
566 \r
567     onAdd : function(c){\r
568         // Empty template method\r
569     },\r
570 \r
571     /**\r
572      * Inserts a Component into this Container at a specified index. Fires the\r
573      * {@link #beforeadd} event before inserting, then fires the {@link #add} event after the\r
574      * Component has been inserted.\r
575      * @param {Number} index The index at which the Component will be inserted\r
576      * into the Container's items collection\r
577      * @param {Ext.Component} component The child Component to insert.<br><br>\r
578      * Ext uses lazy rendering, and will only render the inserted Component should\r
579      * it become necessary.<br><br>\r
580      * A Component config object may be passed in order to avoid the overhead of\r
581      * constructing a real Component object if lazy rendering might mean that the\r
582      * inserted Component will not be rendered immediately. To take advantage of\r
583      * this 'lazy instantiation', set the {@link Ext.Component#xtype} config\r
584      * property to the registered type of the Component wanted.<br><br>\r
585      * For a list of all available xtypes, see {@link Ext.Component}.\r
586      * @return {Ext.Component} component The Component (or config object) that was\r
587      * inserted with the Container's default config values applied.\r
588      */\r
589     insert : function(index, comp){\r
590         this.initItems();\r
591         var a = arguments, len = a.length;\r
592         if(len > 2){\r
593             for(var i = len-1; i >= 1; --i) {\r
594                 this.insert(index, a[i]);\r
595             }\r
596             return;\r
597         }\r
598         var c = this.lookupComponent(this.applyDefaults(comp));\r
599         index = Math.min(index, this.items.length);\r
600         if(this.fireEvent('beforeadd', this, c, index) !== false && this.onBeforeAdd(c) !== false){\r
601             if(c.ownerCt == this){\r
602                 this.items.remove(c);\r
603             }\r
604             this.items.insert(index, c);\r
605             c.ownerCt = this;\r
606             this.onAdd(c);\r
607             this.fireEvent('add', this, c, index);\r
608         }\r
609         return c;\r
610     },\r
611 \r
612     // private\r
613     applyDefaults : function(c){\r
614         if(this.defaults){\r
615             if(Ext.isString(c)){\r
616                 c = Ext.ComponentMgr.get(c);\r
617                 Ext.apply(c, this.defaults);\r
618             }else if(!c.events){\r
619                 Ext.applyIf(c, this.defaults);\r
620             }else{\r
621                 Ext.apply(c, this.defaults);\r
622             }\r
623         }\r
624         return c;\r
625     },\r
626 \r
627     // private\r
628     onBeforeAdd : function(item){\r
629         if(item.ownerCt){\r
630             item.ownerCt.remove(item, false);\r
631         }\r
632         if(this.hideBorders === true){\r
633             item.border = (item.border === true);\r
634         }\r
635     },\r
636 \r
637     /**\r
638      * Removes a component from this container.  Fires the {@link #beforeremove} event before removing, then fires\r
639      * the {@link #remove} event after the component has been removed.\r
640      * @param {Component/String} component The component reference or id to remove.\r
641      * @param {Boolean} autoDestroy (optional) True to automatically invoke the removed Component's {@link Ext.Component#destroy} function.\r
642      * Defaults to the value of this Container's {@link #autoDestroy} config.\r
643      * @return {Ext.Component} component The Component that was removed.\r
644      */\r
645     remove : function(comp, autoDestroy){\r
646         this.initItems();\r
647         var c = this.getComponent(comp);\r
648         if(c && this.fireEvent('beforeremove', this, c) !== false){\r
649             delete c.ownerCt;\r
650             if(this.layout && this.rendered){\r
651                 this.layout.onRemove(c);\r
652             }\r
653             this.onRemove(c);\r
654             this.items.remove(c);\r
655             if(autoDestroy === true || (autoDestroy !== false && this.autoDestroy)){\r
656                 c.destroy();\r
657             }\r
658             this.fireEvent('remove', this, c);\r
659         }\r
660         return c;\r
661     },\r
662 \r
663     onRemove: function(c){\r
664         // Empty template method\r
665     },\r
666 \r
667     /**\r
668      * Removes all components from this container.\r
669      * @param {Boolean} autoDestroy (optional) True to automatically invoke the removed Component's {@link Ext.Component#destroy} function.\r
670      * Defaults to the value of this Container's {@link #autoDestroy} config.\r
671      * @return {Array} Array of the destroyed components\r
672      */\r
673     removeAll: function(autoDestroy){\r
674         this.initItems();\r
675         var item, rem = [], items = [];\r
676         this.items.each(function(i){\r
677             rem.push(i);\r
678         });\r
679         for (var i = 0, len = rem.length; i < len; ++i){\r
680             item = rem[i];\r
681             this.remove(item, autoDestroy);\r
682             if(item.ownerCt !== this){\r
683                 items.push(item);\r
684             }\r
685         }\r
686         return items;\r
687     },\r
688 \r
689     /**\r
690      * Examines this container's <code>{@link #items}</code> <b>property</b>\r
691      * and gets a direct child component of this container.\r
692      * @param {String/Number} comp This parameter may be any of the following:\r
693      * <div><ul class="mdetail-params">\r
694      * <li>a <b><tt>String</tt></b> : representing the <code>{@link Ext.Component#itemId itemId}</code>\r
695      * or <code>{@link Ext.Component#id id}</code> of the child component </li>\r
696      * <li>a <b><tt>Number</tt></b> : representing the position of the child component\r
697      * within the <code>{@link #items}</code> <b>property</b></li>\r
698      * </ul></div>\r
699      * <p>For additional information see {@link Ext.util.MixedCollection#get}.\r
700      * @return Ext.Component The component (if found).\r
701      */\r
702     getComponent : function(comp){\r
703         if(Ext.isObject(comp)){\r
704             comp = comp.getItemId();\r
705         }\r
706         return this.items.get(comp);\r
707     },\r
708 \r
709     // private\r
710     lookupComponent : function(comp){\r
711         if(Ext.isString(comp)){\r
712             return Ext.ComponentMgr.get(comp);\r
713         }else if(!comp.events){\r
714             return this.createComponent(comp);\r
715         }\r
716         return comp;\r
717     },\r
718 \r
719     // private\r
720     createComponent : function(config){\r
721         return Ext.create(config, this.defaultType);\r
722     },\r
723 \r
724     // private\r
725     canLayout: function() {\r
726         var el = this.getVisibilityEl();\r
727         return el && !el.isStyle("display", "none");\r
728     },\r
729 \r
730 \r
731     /**\r
732      * Force this container's layout to be recalculated. A call to this function is required after adding a new component\r
733      * to an already rendered container, or possibly after changing sizing/position properties of child components.\r
734      * @param {Boolean} shallow (optional) True to only calc the layout of this component, and let child components auto\r
735      * calc layouts as required (defaults to false, which calls doLayout recursively for each subcontainer)\r
736      * @param {Boolean} force (optional) True to force a layout to occur, even if the item is hidden.\r
737      * @return {Ext.Container} this\r
738      */\r
739     doLayout: function(shallow, force){\r
740         var rendered = this.rendered;\r
741         forceLayout = force || this.forceLayout;\r
742 \r
743         if(!this.canLayout() || this.collapsed){\r
744             this.deferLayout = this.deferLayout || !shallow;\r
745             if(!forceLayout){\r
746                 return;\r
747             }\r
748             shallow = shallow && !this.deferLayout;\r
749         } else {\r
750             delete this.deferLayout;\r
751         }\r
752         if(rendered && this.layout){\r
753             this.layout.layout();\r
754         }\r
755         if(shallow !== true && this.items){\r
756             var cs = this.items.items;\r
757             for(var i = 0, len = cs.length; i < len; i++){\r
758                 var c = cs[i];\r
759                 if(c.doLayout){\r
760                     c.doLayout(false, forceLayout);\r
761                 }\r
762             }\r
763         }\r
764         if(rendered){\r
765             this.onLayout(shallow, forceLayout);\r
766         }\r
767         // Initial layout completed\r
768         this.hasLayout = true;\r
769         delete this.forceLayout;\r
770     },\r
771 \r
772     //private\r
773     onLayout : Ext.emptyFn,\r
774 \r
775     // private\r
776     shouldBufferLayout: function(){\r
777         /*\r
778          * Returns true if the container should buffer a layout.\r
779          * This is true only if the container has previously been laid out\r
780          * and has a parent container that is pending a layout.\r
781          */\r
782         var hl = this.hasLayout;\r
783         if(this.ownerCt){\r
784             // Only ever buffer if we've laid out the first time and we have one pending.\r
785             return hl ? !this.hasLayoutPending() : false;\r
786         }\r
787         // Never buffer initial layout\r
788         return hl;\r
789     },\r
790 \r
791     // private\r
792     hasLayoutPending: function(){\r
793         // Traverse hierarchy to see if any parent container has a pending layout.\r
794         var pending = false;\r
795         this.ownerCt.bubble(function(c){\r
796             if(c.layoutPending){\r
797                 pending = true;\r
798                 return false;\r
799             }\r
800         });\r
801         return pending;\r
802     },\r
803 \r
804     onShow : function(){\r
805         Ext.Container.superclass.onShow.call(this);\r
806         if(this.deferLayout !== undefined){\r
807             this.doLayout(true);\r
808         }\r
809     },\r
810 \r
811     /**\r
812      * Returns the layout currently in use by the container.  If the container does not currently have a layout\r
813      * set, a default {@link Ext.layout.ContainerLayout} will be created and set as the container's layout.\r
814      * @return {ContainerLayout} layout The container's layout\r
815      */\r
816     getLayout : function(){\r
817         if(!this.layout){\r
818             var layout = new Ext.layout.ContainerLayout(this.layoutConfig);\r
819             this.setLayout(layout);\r
820         }\r
821         return this.layout;\r
822     },\r
823 \r
824     // private\r
825     beforeDestroy : function(){\r
826         if(this.items){\r
827             Ext.destroy.apply(Ext, this.items.items);\r
828         }\r
829         if(this.monitorResize){\r
830             Ext.EventManager.removeResizeListener(this.doLayout, this);\r
831         }\r
832         Ext.destroy(this.layout);\r
833         Ext.Container.superclass.beforeDestroy.call(this);\r
834     },\r
835 \r
836     /**\r
837      * Bubbles up the component/container heirarchy, calling the specified function with each component. The scope (<i>this</i>) of\r
838      * function call will be the scope provided or the current component. The arguments to the function\r
839      * will be the args provided or the current component. If the function returns false at any point,\r
840      * the bubble is stopped.\r
841      * @param {Function} fn The function to call\r
842      * @param {Object} scope (optional) The scope of the function (defaults to current node)\r
843      * @param {Array} args (optional) The args to call the function with (default to passing the current component)\r
844      * @return {Ext.Container} this\r
845      */\r
846     bubble : function(fn, scope, args){\r
847         var p = this;\r
848         while(p){\r
849             if(fn.apply(scope || p, args || [p]) === false){\r
850                 break;\r
851             }\r
852             p = p.ownerCt;\r
853         }\r
854         return this;\r
855     },\r
856 \r
857     /**\r
858      * Cascades down the component/container heirarchy from this component (called first), calling the specified function with\r
859      * each component. The scope (<i>this</i>) of\r
860      * function call will be the scope provided or the current component. The arguments to the function\r
861      * will be the args provided or the current component. If the function returns false at any point,\r
862      * the cascade is stopped on that branch.\r
863      * @param {Function} fn The function to call\r
864      * @param {Object} scope (optional) The scope of the function (defaults to current component)\r
865      * @param {Array} args (optional) The args to call the function with (defaults to passing the current component)\r
866      * @return {Ext.Container} this\r
867      */\r
868     cascade : function(fn, scope, args){\r
869         if(fn.apply(scope || this, args || [this]) !== false){\r
870             if(this.items){\r
871                 var cs = this.items.items;\r
872                 for(var i = 0, len = cs.length; i < len; i++){\r
873                     if(cs[i].cascade){\r
874                         cs[i].cascade(fn, scope, args);\r
875                     }else{\r
876                         fn.apply(scope || cs[i], args || [cs[i]]);\r
877                     }\r
878                 }\r
879             }\r
880         }\r
881         return this;\r
882     },\r
883 \r
884     /**\r
885      * Find a component under this container at any level by id\r
886      * @param {String} id\r
887      * @return Ext.Component\r
888      */\r
889     findById : function(id){\r
890         var m, ct = this;\r
891         this.cascade(function(c){\r
892             if(ct != c && c.id === id){\r
893                 m = c;\r
894                 return false;\r
895             }\r
896         });\r
897         return m || null;\r
898     },\r
899 \r
900     /**\r
901      * Find a component under this container at any level by xtype or class\r
902      * @param {String/Class} xtype The xtype string for a component, or the class of the component directly\r
903      * @param {Boolean} shallow (optional) False to check whether this Component is descended from the xtype (this is\r
904      * the default), or true to check whether this Component is directly of the specified xtype.\r
905      * @return {Array} Array of Ext.Components\r
906      */\r
907     findByType : function(xtype, shallow){\r
908         return this.findBy(function(c){\r
909             return c.isXType(xtype, shallow);\r
910         });\r
911     },\r
912 \r
913     /**\r
914      * Find a component under this container at any level by property\r
915      * @param {String} prop\r
916      * @param {String} value\r
917      * @return {Array} Array of Ext.Components\r
918      */\r
919     find : function(prop, value){\r
920         return this.findBy(function(c){\r
921             return c[prop] === value;\r
922         });\r
923     },\r
924 \r
925     /**\r
926      * Find a component under this container at any level by a custom function. If the passed function returns\r
927      * true, the component will be included in the results. The passed function is called with the arguments (component, this container).\r
928      * @param {Function} fn The function to call\r
929      * @param {Object} scope (optional)\r
930      * @return {Array} Array of Ext.Components\r
931      */\r
932     findBy : function(fn, scope){\r
933         var m = [], ct = this;\r
934         this.cascade(function(c){\r
935             if(ct != c && fn.call(scope || c, c, ct) === true){\r
936                 m.push(c);\r
937             }\r
938         });\r
939         return m;\r
940     },\r
941 \r
942     /**\r
943      * Get a component contained by this container (alias for items.get(key))\r
944      * @param {String/Number} key The index or id of the component\r
945      * @return {Ext.Component} Ext.Component\r
946      */\r
947     get : function(key){\r
948         return this.items.get(key);\r
949     }\r
950 });\r
951 \r
952 Ext.Container.LAYOUTS = {};\r
953 Ext.reg('container', Ext.Container);\r