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