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