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