Upgrade to ExtJS 3.2.0 - Released 03/30/2010
[extjs.git] / src / widgets / BoxComponent.js
1 /*!
2  * Ext JS Library 3.2.0
3  * Copyright(c) 2006-2010 Ext JS, Inc.
4  * licensing@extjs.com
5  * http://www.extjs.com/license
6  */
7 /**
8  * @class Ext.BoxComponent
9  * @extends Ext.Component
10  * <p>Base class for any {@link Ext.Component Component} that is to be sized as a box, using width and height.</p>
11  * <p>BoxComponent provides automatic box model adjustments for sizing and positioning and will work correctly
12  * within the Component rendering model.</p>
13  * <p>A BoxComponent may be created as a custom Component which encapsulates any HTML element, either a pre-existing
14  * element, or one that is created to your specifications at render time. Usually, to participate in layouts,
15  * a Component will need to be a <b>Box</b>Component in order to have its width and height managed.</p>
16  * <p>To use a pre-existing element as a BoxComponent, configure it so that you preset the <b>el</b> property to the
17  * element to reference:<pre><code>
18 var pageHeader = new Ext.BoxComponent({
19     el: 'my-header-div'
20 });</code></pre>
21  * This may then be {@link Ext.Container#add added} to a {@link Ext.Container Container} as a child item.</p>
22  * <p>To create a BoxComponent based around a HTML element to be created at render time, use the
23  * {@link Ext.Component#autoEl autoEl} config option which takes the form of a
24  * {@link Ext.DomHelper DomHelper} specification:<pre><code>
25 var myImage = new Ext.BoxComponent({
26     autoEl: {
27         tag: 'img',
28         src: '/images/my-image.jpg'
29     }
30 });</code></pre></p>
31  * @constructor
32  * @param {Ext.Element/String/Object} config The configuration options.
33  * @xtype box
34  */
35 Ext.BoxComponent = Ext.extend(Ext.Component, {
36
37     // Configs below are used for all Components when rendered by BoxLayout.
38     /**
39      * @cfg {Number} flex
40      * <p><b>Note</b>: this config is only used when this Component is rendered
41      * by a Container which has been configured to use a <b>{@link Ext.layout.BoxLayout BoxLayout}.</b>
42      * Each child Component with a <code>flex</code> property will be flexed either vertically (by a VBoxLayout)
43      * or horizontally (by an HBoxLayout) according to the item's <b>relative</b> <code>flex</code> value
44      * compared to the sum of all Components with <code>flex</flex> value specified. Any child items that have
45      * either a <code>flex = 0</code> or <code>flex = undefined</code> will not be 'flexed' (the initial size will not be changed).
46      */
47     // Configs below are used for all Components when rendered by AnchorLayout.
48     /**
49      * @cfg {String} anchor <p><b>Note</b>: this config is only used when this Component is rendered
50      * by a Container which has been configured to use an <b>{@link Ext.layout.AnchorLayout AnchorLayout} (or subclass thereof).</b>
51      * based layout manager, for example:<div class="mdetail-params"><ul>
52      * <li>{@link Ext.form.FormPanel}</li>
53      * <li>specifying <code>layout: 'anchor' // or 'form', or 'absolute'</code></li>
54      * </ul></div></p>
55      * <p>See {@link Ext.layout.AnchorLayout}.{@link Ext.layout.AnchorLayout#anchor anchor} also.</p>
56      */
57     // tabTip config is used when a BoxComponent is a child of a TabPanel
58     /**
59      * @cfg {String} tabTip
60      * <p><b>Note</b>: this config is only used when this BoxComponent is a child item of a TabPanel.</p>
61      * A string to be used as innerHTML (html tags are accepted) to show in a tooltip when mousing over
62      * the associated tab selector element. {@link Ext.QuickTips}.init()
63      * must be called in order for the tips to render.
64      */
65     // Configs below are used for all Components when rendered by BorderLayout.
66     /**
67      * @cfg {String} region <p><b>Note</b>: this config is only used when this BoxComponent is rendered
68      * by a Container which has been configured to use the <b>{@link Ext.layout.BorderLayout BorderLayout}</b>
69      * layout manager (e.g. specifying <tt>layout:'border'</tt>).</p><br>
70      * <p>See {@link Ext.layout.BorderLayout} also.</p>
71      */
72     // margins config is used when a BoxComponent is rendered by BorderLayout or BoxLayout.
73     /**
74      * @cfg {Object} margins <p><b>Note</b>: this config is only used when this BoxComponent is rendered
75      * by a Container which has been configured to use the <b>{@link Ext.layout.BorderLayout BorderLayout}</b>
76      * or one of the two <b>{@link Ext.layout.BoxLayout BoxLayout} subclasses.</b></p>
77      * <p>An object containing margins to apply to this BoxComponent in the
78      * format:</p><pre><code>
79 {
80     top: (top margin),
81     right: (right margin),
82     bottom: (bottom margin),
83     left: (left margin)
84 }</code></pre>
85      * <p>May also be a string containing space-separated, numeric margin values. The order of the
86      * sides associated with each value matches the way CSS processes margin values:</p>
87      * <p><div class="mdetail-params"><ul>
88      * <li>If there is only one value, it applies to all sides.</li>
89      * <li>If there are two values, the top and bottom borders are set to the first value and the
90      * right and left are set to the second.</li>
91      * <li>If there are three values, the top is set to the first value, the left and right are set
92      * to the second, and the bottom is set to the third.</li>
93      * <li>If there are four values, they apply to the top, right, bottom, and left, respectively.</li>
94      * </ul></div></p>
95      * <p>Defaults to:</p><pre><code>
96      * {top:0, right:0, bottom:0, left:0}
97      * </code></pre>
98      */
99     /**
100      * @cfg {Number} x
101      * The local x (left) coordinate for this component if contained within a positioning container.
102      */
103     /**
104      * @cfg {Number} y
105      * The local y (top) coordinate for this component if contained within a positioning container.
106      */
107     /**
108      * @cfg {Number} pageX
109      * The page level x coordinate for this component if contained within a positioning container.
110      */
111     /**
112      * @cfg {Number} pageY
113      * The page level y coordinate for this component if contained within a positioning container.
114      */
115     /**
116      * @cfg {Number} height
117      * The height of this component in pixels (defaults to auto).
118      * <b>Note</b> to express this dimension as a percentage or offset see {@link Ext.Component#anchor}.
119      */
120     /**
121      * @cfg {Number} width
122      * The width of this component in pixels (defaults to auto).
123      * <b>Note</b> to express this dimension as a percentage or offset see {@link Ext.Component#anchor}.
124      */
125     /**
126      * @cfg {Number} boxMinHeight
127      * <p>The minimum value in pixels which this BoxComponent will set its height to.</p>
128      * <p><b>Warning:</b> This will override any size management applied by layout managers.</p>
129      */
130     /**
131      * @cfg {Number} boxMinWidth
132      * <p>The minimum value in pixels which this BoxComponent will set its width to.</p>
133      * <p><b>Warning:</b> This will override any size management applied by layout managers.</p>
134      */
135     /**
136      * @cfg {Number} boxMaxHeight
137      * <p>The maximum value in pixels which this BoxComponent will set its height to.</p>
138      * <p><b>Warning:</b> This will override any size management applied by layout managers.</p>
139      */
140     /**
141      * @cfg {Number} boxMaxWidth
142      * <p>The maximum value in pixels which this BoxComponent will set its width to.</p>
143      * <p><b>Warning:</b> This will override any size management applied by layout managers.</p>
144      */
145     /**
146      * @cfg {Boolean} autoHeight
147      * <p>True to use height:'auto', false to use fixed height (or allow it to be managed by its parent
148      * Container's {@link Ext.Container#layout layout manager}. Defaults to false.</p>
149      * <p><b>Note</b>: Although many components inherit this config option, not all will
150      * function as expected with a height of 'auto'. Setting autoHeight:true means that the
151      * browser will manage height based on the element's contents, and that Ext will not manage it at all.</p>
152      * <p>If the <i>browser</i> is managing the height, be aware that resizes performed by the browser in response
153      * to changes within the structure of the Component cannot be detected. Therefore changes to the height might
154      * result in elements needing to be synchronized with the new height. Example:</p><pre><code>
155 var w = new Ext.Window({
156     title: 'Window',
157     width: 600,
158     autoHeight: true,
159     items: {
160         title: 'Collapse Me',
161         height: 400,
162         collapsible: true,
163         border: false,
164         listeners: {
165             beforecollapse: function() {
166                 w.el.shadow.hide();
167             },
168             beforeexpand: function() {
169                 w.el.shadow.hide();
170             },
171             collapse: function() {
172                 w.syncShadow();
173             },
174             expand: function() {
175                 w.syncShadow();
176             }
177         }
178     }
179 }).show();
180 </code></pre>
181      */
182     /**
183      * @cfg {Boolean} autoWidth
184      * <p>True to use width:'auto', false to use fixed width (or allow it to be managed by its parent
185      * Container's {@link Ext.Container#layout layout manager}. Defaults to false.</p>
186      * <p><b>Note</b>: Although many components  inherit this config option, not all will
187      * function as expected with a width of 'auto'. Setting autoWidth:true means that the
188      * browser will manage width based on the element's contents, and that Ext will not manage it at all.</p>
189      * <p>If the <i>browser</i> is managing the width, be aware that resizes performed by the browser in response
190      * to changes within the structure of the Component cannot be detected. Therefore changes to the width might
191      * result in elements needing to be synchronized with the new width. For example, where the target element is:</p><pre><code>
192 &lt;div id='grid-container' style='margin-left:25%;width:50%'>&lt;/div>
193 </code></pre>
194      * A Panel rendered into that target element must listen for browser window resize in order to relay its
195       * child items when the browser changes its width:<pre><code>
196 var myPanel = new Ext.Panel({
197     renderTo: 'grid-container',
198     monitorResize: true, // relay on browser resize
199     title: 'Panel',
200     height: 400,
201     autoWidth: true,
202     layout: 'hbox',
203     layoutConfig: {
204         align: 'stretch'
205     },
206     defaults: {
207         flex: 1
208     },
209     items: [{
210         title: 'Box 1',
211     }, {
212         title: 'Box 2'
213     }, {
214         title: 'Box 3'
215     }],
216 });
217 </code></pre>
218      */
219     /**
220      * @cfg {Boolean} autoScroll
221      * <code>true</code> to use overflow:'auto' on the components layout element and show scroll bars automatically when
222      * necessary, <code>false</code> to clip any overflowing content (defaults to <code>false</code>).
223      */
224
225     /* // private internal config
226      * {Boolean} deferHeight
227      * True to defer height calculations to an external component, false to allow this component to set its own
228      * height (defaults to false).
229      */
230
231     // private
232     initComponent : function(){
233         Ext.BoxComponent.superclass.initComponent.call(this);
234         this.addEvents(
235             /**
236              * @event resize
237              * Fires after the component is resized.
238              * @param {Ext.Component} this
239              * @param {Number} adjWidth The box-adjusted width that was set
240              * @param {Number} adjHeight The box-adjusted height that was set
241              * @param {Number} rawWidth The width that was originally specified
242              * @param {Number} rawHeight The height that was originally specified
243              */
244             'resize',
245             /**
246              * @event move
247              * Fires after the component is moved.
248              * @param {Ext.Component} this
249              * @param {Number} x The new x position
250              * @param {Number} y The new y position
251              */
252             'move'
253         );
254     },
255
256     // private, set in afterRender to signify that the component has been rendered
257     boxReady : false,
258     // private, used to defer height settings to subclasses
259     deferHeight: false,
260
261     /**
262      * Sets the width and height of this BoxComponent. This method fires the {@link #resize} event. This method can accept
263      * either width and height as separate arguments, or you can pass a size object like <code>{width:10, height:20}</code>.
264      * @param {Mixed} width The new width to set. This may be one of:<div class="mdetail-params"><ul>
265      * <li>A Number specifying the new width in the {@link #getEl Element}'s {@link Ext.Element#defaultUnit}s (by default, pixels).</li>
266      * <li>A String used to set the CSS width style.</li>
267      * <li>A size object in the format <code>{width: widthValue, height: heightValue}</code>.</li>
268      * <li><code>undefined</code> to leave the width unchanged.</li>
269      * </ul></div>
270      * @param {Mixed} height The new height to set (not required if a size object is passed as the first arg).
271      * This may be one of:<div class="mdetail-params"><ul>
272      * <li>A Number specifying the new height in the {@link #getEl Element}'s {@link Ext.Element#defaultUnit}s (by default, pixels).</li>
273      * <li>A String used to set the CSS height style. Animation may <b>not</b> be used.</li>
274      * <li><code>undefined</code> to leave the height unchanged.</li>
275      * </ul></div>
276      * @return {Ext.BoxComponent} this
277      */
278     setSize : function(w, h){
279
280         // support for standard size objects
281         if(typeof w == 'object'){
282             h = w.height;
283             w = w.width;
284         }
285         if (Ext.isDefined(w) && Ext.isDefined(this.boxMinWidth) && (w < this.boxMinWidth)) {
286             w = this.boxMinWidth;
287         }
288         if (Ext.isDefined(h) && Ext.isDefined(this.boxMinHeight) && (h < this.boxMinHeight)) {
289             h = this.boxMinHeight;
290         }
291         if (Ext.isDefined(w) && Ext.isDefined(this.boxMaxWidth) && (w > this.boxMaxWidth)) {
292             w = this.boxMaxWidth;
293         }
294         if (Ext.isDefined(h) && Ext.isDefined(this.boxMaxHeight) && (h > this.boxMaxHeight)) {
295             h = this.boxMaxHeight;
296         }
297         // not rendered
298         if(!this.boxReady){
299             this.width  = w;
300             this.height = h;
301             return this;
302         }
303
304         // prevent recalcs when not needed
305         if(this.cacheSizes !== false && this.lastSize && this.lastSize.width == w && this.lastSize.height == h){
306             return this;
307         }
308         this.lastSize = {width: w, height: h};
309         var adj = this.adjustSize(w, h),
310             aw = adj.width,
311             ah = adj.height,
312             rz;
313         if(aw !== undefined || ah !== undefined){ // this code is nasty but performs better with floaters
314             rz = this.getResizeEl();
315             if(!this.deferHeight && aw !== undefined && ah !== undefined){
316                 rz.setSize(aw, ah);
317             }else if(!this.deferHeight && ah !== undefined){
318                 rz.setHeight(ah);
319             }else if(aw !== undefined){
320                 rz.setWidth(aw);
321             }
322             this.onResize(aw, ah, w, h);
323             this.fireEvent('resize', this, aw, ah, w, h);
324         }
325         return this;
326     },
327
328     /**
329      * Sets the width of the component.  This method fires the {@link #resize} event.
330      * @param {Mixed} width The new width to set. This may be one of:<div class="mdetail-params"><ul>
331      * <li>A Number specifying the new width in the {@link #getEl Element}'s {@link Ext.Element#defaultUnit defaultUnit}s (by default, pixels).</li>
332      * <li>A String used to set the CSS width style.</li>
333      * </ul></div>
334      * @return {Ext.BoxComponent} this
335      */
336     setWidth : function(width){
337         return this.setSize(width);
338     },
339
340     /**
341      * Sets the height of the component.  This method fires the {@link #resize} event.
342      * @param {Mixed} height The new height to set. This may be one of:<div class="mdetail-params"><ul>
343      * <li>A Number specifying the new height in the {@link #getEl Element}'s {@link Ext.Element#defaultUnit defaultUnit}s (by default, pixels).</li>
344      * <li>A String used to set the CSS height style.</li>
345      * <li><i>undefined</i> to leave the height unchanged.</li>
346      * </ul></div>
347      * @return {Ext.BoxComponent} this
348      */
349     setHeight : function(height){
350         return this.setSize(undefined, height);
351     },
352
353     /**
354      * Gets the current size of the component's underlying element.
355      * @return {Object} An object containing the element's size {width: (element width), height: (element height)}
356      */
357     getSize : function(){
358         return this.getResizeEl().getSize();
359     },
360
361     /**
362      * Gets the current width of the component's underlying element.
363      * @return {Number}
364      */
365     getWidth : function(){
366         return this.getResizeEl().getWidth();
367     },
368
369     /**
370      * Gets the current height of the component's underlying element.
371      * @return {Number}
372      */
373     getHeight : function(){
374         return this.getResizeEl().getHeight();
375     },
376
377     /**
378      * Gets the current size of the component's underlying element, including space taken by its margins.
379      * @return {Object} An object containing the element's size {width: (element width + left/right margins), height: (element height + top/bottom margins)}
380      */
381     getOuterSize : function(){
382         var el = this.getResizeEl();
383         return {width: el.getWidth() + el.getMargins('lr'),
384                 height: el.getHeight() + el.getMargins('tb')};
385     },
386
387     /**
388      * Gets the current XY position of the component's underlying element.
389      * @param {Boolean} local (optional) If true the element's left and top are returned instead of page XY (defaults to false)
390      * @return {Array} The XY position of the element (e.g., [100, 200])
391      */
392     getPosition : function(local){
393         var el = this.getPositionEl();
394         if(local === true){
395             return [el.getLeft(true), el.getTop(true)];
396         }
397         return this.xy || el.getXY();
398     },
399
400     /**
401      * Gets the current box measurements of the component's underlying element.
402      * @param {Boolean} local (optional) If true the element's left and top are returned instead of page XY (defaults to false)
403      * @return {Object} box An object in the format {x, y, width, height}
404      */
405     getBox : function(local){
406         var pos = this.getPosition(local);
407         var s = this.getSize();
408         s.x = pos[0];
409         s.y = pos[1];
410         return s;
411     },
412
413     /**
414      * Sets the current box measurements of the component's underlying element.
415      * @param {Object} box An object in the format {x, y, width, height}
416      * @return {Ext.BoxComponent} this
417      */
418     updateBox : function(box){
419         this.setSize(box.width, box.height);
420         this.setPagePosition(box.x, box.y);
421         return this;
422     },
423
424     /**
425      * <p>Returns the outermost Element of this Component which defines the Components overall size.</p>
426      * <p><i>Usually</i> this will return the same Element as <code>{@link #getEl}</code>,
427      * but in some cases, a Component may have some more wrapping Elements around its main
428      * active Element.</p>
429      * <p>An example is a ComboBox. It is encased in a <i>wrapping</i> Element which
430      * contains both the <code>&lt;input></code> Element (which is what would be returned
431      * by its <code>{@link #getEl}</code> method, <i>and</i> the trigger button Element.
432      * This Element is returned as the <code>resizeEl</code>.
433      * @return {Ext.Element} The Element which is to be resized by size managing layouts.
434      */
435     getResizeEl : function(){
436         return this.resizeEl || this.el;
437     },
438
439     /**
440      * Sets the overflow on the content element of the component.
441      * @param {Boolean} scroll True to allow the Component to auto scroll.
442      * @return {Ext.BoxComponent} this
443      */
444     setAutoScroll : function(scroll){
445         if(this.rendered){
446             this.getContentTarget().setOverflow(scroll ? 'auto' : '');
447         }
448         this.autoScroll = scroll;
449         return this;
450     },
451
452     /**
453      * Sets the left and top of the component.  To set the page XY position instead, use {@link #setPagePosition}.
454      * This method fires the {@link #move} event.
455      * @param {Number} left The new left
456      * @param {Number} top The new top
457      * @return {Ext.BoxComponent} this
458      */
459     setPosition : function(x, y){
460         if(x && typeof x[1] == 'number'){
461             y = x[1];
462             x = x[0];
463         }
464         this.x = x;
465         this.y = y;
466         if(!this.boxReady){
467             return this;
468         }
469         var adj = this.adjustPosition(x, y);
470         var ax = adj.x, ay = adj.y;
471
472         var el = this.getPositionEl();
473         if(ax !== undefined || ay !== undefined){
474             if(ax !== undefined && ay !== undefined){
475                 el.setLeftTop(ax, ay);
476             }else if(ax !== undefined){
477                 el.setLeft(ax);
478             }else if(ay !== undefined){
479                 el.setTop(ay);
480             }
481             this.onPosition(ax, ay);
482             this.fireEvent('move', this, ax, ay);
483         }
484         return this;
485     },
486
487     /**
488      * Sets the page XY position of the component.  To set the left and top instead, use {@link #setPosition}.
489      * This method fires the {@link #move} event.
490      * @param {Number} x The new x position
491      * @param {Number} y The new y position
492      * @return {Ext.BoxComponent} this
493      */
494     setPagePosition : function(x, y){
495         if(x && typeof x[1] == 'number'){
496             y = x[1];
497             x = x[0];
498         }
499         this.pageX = x;
500         this.pageY = y;
501         if(!this.boxReady){
502             return;
503         }
504         if(x === undefined || y === undefined){ // cannot translate undefined points
505             return;
506         }
507         var p = this.getPositionEl().translatePoints(x, y);
508         this.setPosition(p.left, p.top);
509         return this;
510     },
511
512     // private
513     afterRender : function(){
514         Ext.BoxComponent.superclass.afterRender.call(this);
515         if(this.resizeEl){
516             this.resizeEl = Ext.get(this.resizeEl);
517         }
518         if(this.positionEl){
519             this.positionEl = Ext.get(this.positionEl);
520         }
521         this.boxReady = true;
522         Ext.isDefined(this.autoScroll) && this.setAutoScroll(this.autoScroll);
523         this.setSize(this.width, this.height);
524         if(this.x || this.y){
525             this.setPosition(this.x, this.y);
526         }else if(this.pageX || this.pageY){
527             this.setPagePosition(this.pageX, this.pageY);
528         }
529     },
530
531     /**
532      * Force the component's size to recalculate based on the underlying element's current height and width.
533      * @return {Ext.BoxComponent} this
534      */
535     syncSize : function(){
536         delete this.lastSize;
537         this.setSize(this.autoWidth ? undefined : this.getResizeEl().getWidth(), this.autoHeight ? undefined : this.getResizeEl().getHeight());
538         return this;
539     },
540
541     /* // protected
542      * Called after the component is resized, this method is empty by default but can be implemented by any
543      * subclass that needs to perform custom logic after a resize occurs.
544      * @param {Number} adjWidth The box-adjusted width that was set
545      * @param {Number} adjHeight The box-adjusted height that was set
546      * @param {Number} rawWidth The width that was originally specified
547      * @param {Number} rawHeight The height that was originally specified
548      */
549     onResize : function(adjWidth, adjHeight, rawWidth, rawHeight){
550     },
551
552     /* // protected
553      * Called after the component is moved, this method is empty by default but can be implemented by any
554      * subclass that needs to perform custom logic after a move occurs.
555      * @param {Number} x The new x position
556      * @param {Number} y The new y position
557      */
558     onPosition : function(x, y){
559
560     },
561
562     // private
563     adjustSize : function(w, h){
564         if(this.autoWidth){
565             w = 'auto';
566         }
567         if(this.autoHeight){
568             h = 'auto';
569         }
570         return {width : w, height: h};
571     },
572
573     // private
574     adjustPosition : function(x, y){
575         return {x : x, y: y};
576     }
577 });
578 Ext.reg('box', Ext.BoxComponent);
579
580
581 /**
582  * @class Ext.Spacer
583  * @extends Ext.BoxComponent
584  * <p>Used to provide a sizable space in a layout.</p>
585  * @constructor
586  * @param {Object} config
587  */
588 Ext.Spacer = Ext.extend(Ext.BoxComponent, {
589     autoEl:'div'
590 });
591 Ext.reg('spacer', Ext.Spacer);