Upgrade to ExtJS 3.2.2 - Released 06/02/2010
[extjs.git] / src / ext-core / src / core / Element.style.js
1 /*!
2  * Ext JS Library 3.2.2
3  * Copyright(c) 2006-2010 Ext JS, Inc.
4  * licensing@extjs.com
5  * http://www.extjs.com/license
6  */
7 /**
8  * @class Ext.Element
9  */
10 Ext.Element.addMethods(function(){
11     // local style camelizing for speed
12     var propCache = {},
13         camelRe = /(-[a-z])/gi,
14         view = document.defaultView,
15         propFloat = Ext.isIE ? 'styleFloat' : 'cssFloat',
16         opacityRe = /alpha\(opacity=(.*)\)/i,
17         trimRe = /^\s+|\s+$/g,
18         spacesRe = /\s+/,
19         wordsRe = /\w/g,
20         PADDING = "padding",
21         MARGIN = "margin",
22         BORDER = "border",
23         LEFT = "-left",
24         RIGHT = "-right",
25         TOP = "-top",
26         BOTTOM = "-bottom",
27         WIDTH = "-width",
28         MATH = Math,
29         HIDDEN = 'hidden',
30         ISCLIPPED = 'isClipped',
31         OVERFLOW = 'overflow',
32         OVERFLOWX = 'overflow-x',
33         OVERFLOWY = 'overflow-y',
34         ORIGINALCLIP = 'originalClip',
35         // special markup used throughout Ext when box wrapping elements
36         borders = {l: BORDER + LEFT + WIDTH, r: BORDER + RIGHT + WIDTH, t: BORDER + TOP + WIDTH, b: BORDER + BOTTOM + WIDTH},
37         paddings = {l: PADDING + LEFT, r: PADDING + RIGHT, t: PADDING + TOP, b: PADDING + BOTTOM},
38         margins = {l: MARGIN + LEFT, r: MARGIN + RIGHT, t: MARGIN + TOP, b: MARGIN + BOTTOM},
39         data = Ext.Element.data;
40
41
42     // private
43     function camelFn(m, a) {
44         return a.charAt(1).toUpperCase();
45     }
46
47     function chkCache(prop) {
48         return propCache[prop] || (propCache[prop] = prop == 'float' ? propFloat : prop.replace(camelRe, camelFn));
49     }
50
51     return {
52         // private  ==> used by Fx
53         adjustWidth : function(width) {
54             var me = this;
55             var isNum = (typeof width == "number");
56             if(isNum && me.autoBoxAdjust && !me.isBorderBox()){
57                width -= (me.getBorderWidth("lr") + me.getPadding("lr"));
58             }
59             return (isNum && width < 0) ? 0 : width;
60         },
61
62         // private   ==> used by Fx
63         adjustHeight : function(height) {
64             var me = this;
65             var isNum = (typeof height == "number");
66             if(isNum && me.autoBoxAdjust && !me.isBorderBox()){
67                height -= (me.getBorderWidth("tb") + me.getPadding("tb"));
68             }
69             return (isNum && height < 0) ? 0 : height;
70         },
71
72
73         /**
74          * Adds one or more CSS classes to the element. Duplicate classes are automatically filtered out.
75          * @param {String/Array} className The CSS class to add, or an array of classes
76          * @return {Ext.Element} this
77          */
78         addClass : function(className){
79             var me = this,
80                 i,
81                 len,
82                 v,
83                 cls = [];
84             // Separate case is for speed
85             if (!Ext.isArray(className)) {
86                 if (typeof className == 'string' && !this.hasClass(className)) {
87                     me.dom.className += " " + className;
88                 }
89             }
90             else {
91                 for (i = 0, len = className.length; i < len; i++) {
92                     v = className[i];
93                     if (typeof v == 'string' && (' ' + me.dom.className + ' ').indexOf(' ' + v + ' ') == -1) {
94                         cls.push(v);
95                     }
96                 }
97                 if (cls.length) {
98                     me.dom.className += " " + cls.join(" ");
99                 }
100             }
101             return me;
102         },
103
104         /**
105          * Removes one or more CSS classes from the element.
106          * @param {String/Array} className The CSS class to remove, or an array of classes
107          * @return {Ext.Element} this
108          */
109         removeClass : function(className){
110             var me = this,
111                 i,
112                 idx,
113                 len,
114                 cls,
115                 elClasses;
116             if (!Ext.isArray(className)){
117                 className = [className];
118             }
119             if (me.dom && me.dom.className) {
120                 elClasses = me.dom.className.replace(trimRe, '').split(spacesRe);
121                 for (i = 0, len = className.length; i < len; i++) {
122                     cls = className[i];
123                     if (typeof cls == 'string') {
124                         cls = cls.replace(trimRe, '');
125                         idx = elClasses.indexOf(cls);
126                         if (idx != -1) {
127                             elClasses.splice(idx, 1);
128                         }
129                     }
130                 }
131                 me.dom.className = elClasses.join(" ");
132             }
133             return me;
134         },
135
136         /**
137          * Adds one or more CSS classes to this element and removes the same class(es) from all siblings.
138          * @param {String/Array} className The CSS class to add, or an array of classes
139          * @return {Ext.Element} this
140          */
141         radioClass : function(className){
142             var cn = this.dom.parentNode.childNodes,
143                 v,
144                 i,
145                 len;
146             className = Ext.isArray(className) ? className : [className];
147             for (i = 0, len = cn.length; i < len; i++) {
148                 v = cn[i];
149                 if (v && v.nodeType == 1) {
150                     Ext.fly(v, '_internal').removeClass(className);
151                 }
152             };
153             return this.addClass(className);
154         },
155
156         /**
157          * Toggles the specified CSS class on this element (removes it if it already exists, otherwise adds it).
158          * @param {String} className The CSS class to toggle
159          * @return {Ext.Element} this
160          */
161         toggleClass : function(className){
162             return this.hasClass(className) ? this.removeClass(className) : this.addClass(className);
163         },
164
165         /**
166          * Checks if the specified CSS class exists on this element's DOM node.
167          * @param {String} className The CSS class to check for
168          * @return {Boolean} True if the class exists, else false
169          */
170         hasClass : function(className){
171             return className && (' '+this.dom.className+' ').indexOf(' '+className+' ') != -1;
172         },
173
174         /**
175          * Replaces a CSS class on the element with another.  If the old name does not exist, the new name will simply be added.
176          * @param {String} oldClassName The CSS class to replace
177          * @param {String} newClassName The replacement CSS class
178          * @return {Ext.Element} this
179          */
180         replaceClass : function(oldClassName, newClassName){
181             return this.removeClass(oldClassName).addClass(newClassName);
182         },
183
184         isStyle : function(style, val) {
185             return this.getStyle(style) == val;
186         },
187
188         /**
189          * Normalizes currentStyle and computedStyle.
190          * @param {String} property The style property whose value is returned.
191          * @return {String} The current value of the style property for this element.
192          */
193         getStyle : function(){
194             return view && view.getComputedStyle ?
195                 function(prop){
196                     var el = this.dom,
197                         v,
198                         cs,
199                         out,
200                         display,
201                         wk = Ext.isWebKit,
202                         display;
203
204                     if(el == document){
205                         return null;
206                     }
207                     prop = chkCache(prop);
208                     // Fix bug caused by this: https://bugs.webkit.org/show_bug.cgi?id=13343
209                     if(wk && (/marginRight/.test(prop))) {
210                         display = this.getStyle('display');
211                         el.style.display = 'inline-block';
212                     }
213                     out = (v = el.style[prop]) ? v :
214                            (cs = view.getComputedStyle(el, "")) ? cs[prop] : null;
215
216                     // Webkit returns rgb values for transparent.
217                     if(wk){
218                         if(out == 'rgba(0, 0, 0, 0)'){
219                             out = 'transparent';
220                         }else if(display){
221                             el.style.display = display;
222                         }
223                     }
224                     return out;
225                 } :
226                 function(prop){
227                     var el = this.dom,
228                         m,
229                         cs;
230
231                     if(el == document) return null;
232                     if (prop == 'opacity') {
233                         if (el.style.filter.match) {
234                             if(m = el.style.filter.match(opacityRe)){
235                                 var fv = parseFloat(m[1]);
236                                 if(!isNaN(fv)){
237                                     return fv ? fv / 100 : 0;
238                                 }
239                             }
240                         }
241                         return 1;
242                     }
243                     prop = chkCache(prop);
244                     return el.style[prop] || ((cs = el.currentStyle) ? cs[prop] : null);
245                 };
246         }(),
247
248         /**
249          * Return the CSS color for the specified CSS attribute. rgb, 3 digit (like #fff) and valid values
250          * are convert to standard 6 digit hex color.
251          * @param {String} attr The css attribute
252          * @param {String} defaultValue The default value to use when a valid color isn't found
253          * @param {String} prefix (optional) defaults to #. Use an empty string when working with
254          * color anims.
255          */
256         getColor : function(attr, defaultValue, prefix){
257             var v = this.getStyle(attr),
258                 color = (typeof prefix != 'undefined') ? prefix : '#',
259                 h;
260
261             if(!v || (/transparent|inherit/.test(v))) {
262                 return defaultValue;
263             }
264             if(/^r/.test(v)){
265                 Ext.each(v.slice(4, v.length -1).split(','), function(s){
266                     h = parseInt(s, 10);
267                     color += (h < 16 ? '0' : '') + h.toString(16);
268                 });
269             }else{
270                 v = v.replace('#', '');
271                 color += v.length == 3 ? v.replace(/^(\w)(\w)(\w)$/, '$1$1$2$2$3$3') : v;
272             }
273             return(color.length > 5 ? color.toLowerCase() : defaultValue);
274         },
275
276         /**
277          * Wrapper for setting style properties, also takes single object parameter of multiple styles.
278          * @param {String/Object} property The style property to be set, or an object of multiple styles.
279          * @param {String} value (optional) The value to apply to the given property, or null if an object was passed.
280          * @return {Ext.Element} this
281          */
282         setStyle : function(prop, value){
283             var tmp, style;
284             
285             if (typeof prop != 'object') {
286                 tmp = {};
287                 tmp[prop] = value;
288                 prop = tmp;
289             }
290             for (style in prop) {
291                 value = prop[style];
292                 style == 'opacity' ?
293                     this.setOpacity(value) :
294                     this.dom.style[chkCache(style)] = value;
295             }
296             return this;
297         },
298
299         /**
300          * Set the opacity of the element
301          * @param {Float} opacity The new opacity. 0 = transparent, .5 = 50% visibile, 1 = fully visible, etc
302          * @param {Boolean/Object} animate (optional) a standard Element animation config object or <tt>true</tt> for
303          * the default animation (<tt>{duration: .35, easing: 'easeIn'}</tt>)
304          * @return {Ext.Element} this
305          */
306          setOpacity : function(opacity, animate){
307             var me = this,
308                 s = me.dom.style;
309
310             if(!animate || !me.anim){
311                 if(Ext.isIE){
312                     var opac = opacity < 1 ? 'alpha(opacity=' + opacity * 100 + ')' : '',
313                     val = s.filter.replace(opacityRe, '').replace(trimRe, '');
314
315                     s.zoom = 1;
316                     s.filter = val + (val.length > 0 ? ' ' : '') + opac;
317                 }else{
318                     s.opacity = opacity;
319                 }
320             }else{
321                 me.anim({opacity: {to: opacity}}, me.preanim(arguments, 1), null, .35, 'easeIn');
322             }
323             return me;
324         },
325
326         /**
327          * Clears any opacity settings from this element. Required in some cases for IE.
328          * @return {Ext.Element} this
329          */
330         clearOpacity : function(){
331             var style = this.dom.style;
332             if(Ext.isIE){
333                 if(!Ext.isEmpty(style.filter)){
334                     style.filter = style.filter.replace(opacityRe, '').replace(trimRe, '');
335                 }
336             }else{
337                 style.opacity = style['-moz-opacity'] = style['-khtml-opacity'] = '';
338             }
339             return this;
340         },
341
342         /**
343          * Returns the offset height of the element
344          * @param {Boolean} contentHeight (optional) true to get the height minus borders and padding
345          * @return {Number} The element's height
346          */
347         getHeight : function(contentHeight){
348             var me = this,
349                 dom = me.dom,
350                 hidden = Ext.isIE && me.isStyle('display', 'none'),
351                 h = MATH.max(dom.offsetHeight, hidden ? 0 : dom.clientHeight) || 0;
352
353             h = !contentHeight ? h : h - me.getBorderWidth("tb") - me.getPadding("tb");
354             return h < 0 ? 0 : h;
355         },
356
357         /**
358          * Returns the offset width of the element
359          * @param {Boolean} contentWidth (optional) true to get the width minus borders and padding
360          * @return {Number} The element's width
361          */
362         getWidth : function(contentWidth){
363             var me = this,
364                 dom = me.dom,
365                 hidden = Ext.isIE && me.isStyle('display', 'none'),
366                 w = MATH.max(dom.offsetWidth, hidden ? 0 : dom.clientWidth) || 0;
367             w = !contentWidth ? w : w - me.getBorderWidth("lr") - me.getPadding("lr");
368             return w < 0 ? 0 : w;
369         },
370
371         /**
372          * Set the width of this Element.
373          * @param {Mixed} width The new width. This may be one of:<div class="mdetail-params"><ul>
374          * <li>A Number specifying the new width in this Element's {@link #defaultUnit}s (by default, pixels).</li>
375          * <li>A String used to set the CSS width style. Animation may <b>not</b> be used.
376          * </ul></div>
377          * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
378          * @return {Ext.Element} this
379          */
380         setWidth : function(width, animate){
381             var me = this;
382             width = me.adjustWidth(width);
383             !animate || !me.anim ?
384                 me.dom.style.width = me.addUnits(width) :
385                 me.anim({width : {to : width}}, me.preanim(arguments, 1));
386             return me;
387         },
388
389         /**
390          * Set the height of this Element.
391          * <pre><code>
392 // change the height to 200px and animate with default configuration
393 Ext.fly('elementId').setHeight(200, true);
394
395 // change the height to 150px and animate with a custom configuration
396 Ext.fly('elId').setHeight(150, {
397     duration : .5, // animation will have a duration of .5 seconds
398     // will change the content to "finished"
399     callback: function(){ this.{@link #update}("finished"); }
400 });
401          * </code></pre>
402          * @param {Mixed} height The new height. This may be one of:<div class="mdetail-params"><ul>
403          * <li>A Number specifying the new height in this Element's {@link #defaultUnit}s (by default, pixels.)</li>
404          * <li>A String used to set the CSS height style. Animation may <b>not</b> be used.</li>
405          * </ul></div>
406          * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
407          * @return {Ext.Element} this
408          */
409          setHeight : function(height, animate){
410             var me = this;
411             height = me.adjustHeight(height);
412             !animate || !me.anim ?
413                 me.dom.style.height = me.addUnits(height) :
414                 me.anim({height : {to : height}}, me.preanim(arguments, 1));
415             return me;
416         },
417
418         /**
419          * Gets the width of the border(s) for the specified side(s)
420          * @param {String} side Can be t, l, r, b or any combination of those to add multiple values. For example,
421          * passing <tt>'lr'</tt> would get the border <b><u>l</u></b>eft width + the border <b><u>r</u></b>ight width.
422          * @return {Number} The width of the sides passed added together
423          */
424         getBorderWidth : function(side){
425             return this.addStyles(side, borders);
426         },
427
428         /**
429          * Gets the width of the padding(s) for the specified side(s)
430          * @param {String} side Can be t, l, r, b or any combination of those to add multiple values. For example,
431          * passing <tt>'lr'</tt> would get the padding <b><u>l</u></b>eft + the padding <b><u>r</u></b>ight.
432          * @return {Number} The padding of the sides passed added together
433          */
434         getPadding : function(side){
435             return this.addStyles(side, paddings);
436         },
437
438         /**
439          *  Store the current overflow setting and clip overflow on the element - use <tt>{@link #unclip}</tt> to remove
440          * @return {Ext.Element} this
441          */
442         clip : function(){
443             var me = this,
444                 dom = me.dom;
445
446             if(!data(dom, ISCLIPPED)){
447                 data(dom, ISCLIPPED, true);
448                 data(dom, ORIGINALCLIP, {
449                     o: me.getStyle(OVERFLOW),
450                     x: me.getStyle(OVERFLOWX),
451                     y: me.getStyle(OVERFLOWY)
452                 });
453                 me.setStyle(OVERFLOW, HIDDEN);
454                 me.setStyle(OVERFLOWX, HIDDEN);
455                 me.setStyle(OVERFLOWY, HIDDEN);
456             }
457             return me;
458         },
459
460         /**
461          *  Return clipping (overflow) to original clipping before <tt>{@link #clip}</tt> was called
462          * @return {Ext.Element} this
463          */
464         unclip : function(){
465             var me = this,
466                 dom = me.dom;
467
468             if(data(dom, ISCLIPPED)){
469                 data(dom, ISCLIPPED, false);
470                 var o = data(dom, ORIGINALCLIP);
471                 if(o.o){
472                     me.setStyle(OVERFLOW, o.o);
473                 }
474                 if(o.x){
475                     me.setStyle(OVERFLOWX, o.x);
476                 }
477                 if(o.y){
478                     me.setStyle(OVERFLOWY, o.y);
479                 }
480             }
481             return me;
482         },
483
484         // private
485         addStyles : function(sides, styles){
486             var ttlSize = 0,
487                 sidesArr = sides.match(wordsRe),
488                 side,
489                 size,
490                 i,
491                 len = sidesArr.length;
492             for (i = 0; i < len; i++) {
493                 side = sidesArr[i];
494                 size = side && parseInt(this.getStyle(styles[side]), 10);
495                 if (size) {
496                     ttlSize += MATH.abs(size);
497                 }
498             }
499             return ttlSize;
500         },
501
502         margins : margins
503     };
504 }()
505 );