]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - include/javascript/yui/build/stylesheet/stylesheet-debug.js
Release 6.2.1
[Github/sugarcrm.git] / include / javascript / yui / build / stylesheet / stylesheet-debug.js
1 /*
2 Copyright (c) 2009, Yahoo! Inc. All rights reserved.
3 Code licensed under the BSD License:
4 http://developer.yahoo.net/yui/license.txt
5 version: 2.8.0r4
6 */
7 /**
8  * The StyleSheet component is a utility for managing css rules at the
9  * stylesheet level
10  *
11  * @module stylesheet
12  * @namespace YAHOO.util
13  * @requires yahoo
14  * @beta
15  */
16 (function () {
17
18 var d      = document,
19     p      = d.createElement('p'), // Have to hold the node (see notes)
20     workerStyle = p.style, // worker style collection
21     lang   = YAHOO.lang,
22     selectors = {},
23     sheets = {},
24     ssId   = 0,
25     floatAttr = ('cssFloat' in workerStyle) ? 'cssFloat' : 'styleFloat',
26     _toCssText,
27     _unsetOpacity,
28     _unsetProperty;
29
30 /*
31  * Normalizes the removal of an assigned style for opacity.  IE uses the filter property.
32  */
33 _unsetOpacity = ('opacity' in workerStyle) ?
34     function (style) { style.opacity = ''; } :
35     function (style) { style.filter = ''; };
36         
37 /*
38  * Normalizes the removal of an assigned style for a given property.  Expands
39  * shortcut properties if necessary and handles the various names for the float property.
40  */
41 workerStyle.border = "1px solid red";
42 workerStyle.border = ''; // IE doesn't unset child properties
43 _unsetProperty = workerStyle.borderLeft ?
44     function (style,prop) {
45         var p;
46         if (prop !== floatAttr && prop.toLowerCase().indexOf('float') != -1) {
47             prop = floatAttr;
48         }
49         if (typeof style[prop] === 'string') {
50             switch (prop) {
51                 case 'opacity':
52                 case 'filter' : _unsetOpacity(style); break;
53                 case 'font'   :
54                     style.font       = style.fontStyle = style.fontVariant =
55                     style.fontWeight = style.fontSize  = style.lineHeight  =
56                     style.fontFamily = '';
57                     break;
58                 default       :
59                     for (p in style) {
60                         if (p.indexOf(prop) === 0) {
61                             style[p] = '';
62                         }
63                     }
64             }
65         }
66     } :
67     function (style,prop) {
68         if (prop !== floatAttr && prop.toLowerCase().indexOf('float') != -1) {
69             prop = floatAttr;
70         }
71         if (lang.isString(style[prop])) {
72             if (prop === 'opacity') {
73                 _unsetOpacity(style);
74             } else {
75                 style[prop] = '';
76             }
77         }
78     };
79     
80 /**
81  * Create an instance of YAHOO.util.StyleSheet to encapsulate a css stylesheet.
82  * The constructor can be called using function or constructor syntax.
83  * <pre><code>var sheet = YAHOO.util.StyleSheet(..);</pre></code>
84  * or
85  * <pre><code>var sheet = new YAHOO.util.StyleSheet(..);</pre></code>
86  *
87  * The first parameter passed can be any of the following things:
88  * <ul>
89  *   <li>The desired string name to register a new empty sheet</li>
90  *   <li>The string name of an existing YAHOO.util.StyleSheet instance</li>
91  *   <li>The unique yuiSSID generated for an existing YAHOO.util.StyleSheet instance</li>
92  *   <li>The id of an existing <code>&lt;link&gt;</code> or <code>&lt;style&gt;</code> node</li>
93  *   <li>The node reference for an existing <code>&lt;link&gt;</code> or <code>&lt;style&gt;</code> node</li>
94  *   <li>A chunk of css text to create a new stylesheet from</li>
95  * </ul>
96  *
97  * <p>If a string is passed, StyleSheet will first look in its static name
98  * registry for an existing sheet, then in the DOM for an element with that id.
99  * If neither are found and the string contains the { character, it will be
100  * used as a the initial cssText for a new StyleSheet.  Otherwise, a new empty
101  * StyleSheet is created, assigned the string value as a name, and registered
102  * statically by that name.</p>
103  *
104  * <p>The optional second parameter is a string name to register the sheet as.
105  * This param is largely useful when providing a node id/ref or chunk of css
106  * text to create a populated instance.</p>
107  * 
108  * @class StyleSheet
109  * @constructor
110  * @param seed {String|HTMLElement} a style or link node, its id, or a name or
111  *              yuiSSID of a StyleSheet, or a string of css text (see above)
112  * @param name {String} OPTIONAL name to register instance for future static
113  *              access
114  */
115 function StyleSheet(seed, name) {
116     var head,
117         node,
118         sheet,
119         cssRules = {},
120         _rules,
121         _insertRule,
122         _deleteRule,
123         i,r,sel;
124
125     // Factory or constructor
126     if (!(this instanceof StyleSheet)) {
127         return new StyleSheet(seed,name);
128     }
129
130     // capture the DOM node if the string is an id
131     node = seed && (seed.nodeName ? seed : d.getElementById(seed));
132
133     // Check for the StyleSheet in the static registry
134     if (seed && sheets[seed]) {
135         return sheets[seed];
136     } else if (node && node.yuiSSID && sheets[node.yuiSSID]) {
137         return sheets[node.yuiSSID];
138     }
139
140     // Create a style node if necessary
141     if (!node || !/^(?:style|link)$/i.test(node.nodeName)) {
142         node = d.createElement('style');
143         node.type = 'text/css';
144     }
145
146     if (lang.isString(seed)) {
147         // Create entire sheet from seed cssText
148         if (seed.indexOf('{') != -1) {
149             // Not a load-time fork because low run-time impact and IE fails
150             // test for s.styleSheet at page load time (oddly)
151             if (node.styleSheet) {
152                 node.styleSheet.cssText = seed;
153             } else {
154                 node.appendChild(d.createTextNode(seed));
155             }
156         } else if (!name) {
157             name = seed;
158         }
159     }
160
161     if (!node.parentNode || node.parentNode.nodeName.toLowerCase() !== 'head') {
162         head = (node.ownerDocument || d).getElementsByTagName('head')[0];
163         // styleSheet isn't available on the style node in FF2 until appended
164         // to the head element.  style nodes appended to body do not affect
165         // change in Safari.
166         head.appendChild(node);
167     }
168
169     // Begin setting up private aliases to the important moving parts
170     // 1. The stylesheet object
171     // IE stores StyleSheet under the "styleSheet" property
172     // Safari doesn't populate sheet for xdomain link elements
173     sheet = node.sheet || node.styleSheet;
174
175     // 2. The style rules collection
176     // IE stores the rules collection under the "rules" property
177     _rules = sheet && ('cssRules' in sheet) ? 'cssRules' : 'rules';
178
179     // 3. The method to remove a rule from the stylesheet
180     // IE supports removeRule
181     _deleteRule = ('deleteRule' in sheet) ?
182         function (i) { sheet.deleteRule(i); } :
183         function (i) { sheet.removeRule(i); };
184
185     // 4. The method to add a new rule to the stylesheet
186     // IE supports addRule with different signature
187     _insertRule = ('insertRule' in sheet) ?
188         function (sel,css,i) { sheet.insertRule(sel+' {'+css+'}',i); } :
189         function (sel,css,i) { sheet.addRule(sel,css,i); };
190
191     // 5. Initialize the cssRules map from the node
192     // xdomain link nodes forbid access to the cssRules collection, so this
193     // will throw an error.
194     // TODO: research alternate stylesheet, @media
195     for (i = sheet[_rules].length - 1; i >= 0; --i) {
196         r   = sheet[_rules][i];
197         sel = r.selectorText;
198
199         if (cssRules[sel]) {
200             cssRules[sel].style.cssText += ';' + r.style.cssText;
201             _deleteRule(i);
202         } else {
203             cssRules[sel] = r;
204         }
205     }
206
207     // Cache the instance by the generated Id
208     node.yuiSSID = 'yui-stylesheet-' + (ssId++);
209     StyleSheet.register(node.yuiSSID,this);
210
211     // Register the instance by name if provided or defaulted from seed
212     if (name) {
213         StyleSheet.register(name,this);
214     }
215
216     // Public API
217     lang.augmentObject(this,{
218         /**
219          * Get the unique yuiSSID for this StyleSheet instance
220          *
221          * @method getId
222          * @return {Number} the static id
223          */
224         getId : function () { return node.yuiSSID; },
225
226         /**
227          * The HTMLElement that this instance encapsulates
228          *
229          * @property node
230          * @type HTMLElement
231          */
232         node : node,
233
234         /**
235          * Enable all the rules in the sheet
236          *
237          * @method enable
238          * @return {StyleSheet} the instance
239          * @chainable
240          */
241         // Enabling/disabling the stylesheet.  Changes may be made to rules
242         // while disabled.
243         enable : function () { sheet.disabled = false; return this; },
244
245         /**
246          * Disable all the rules in the sheet.  Rules may be changed while the
247          * StyleSheet is disabled.
248          *
249          * @method disable
250          * @return {StyleSheet} the instance
251          * @chainable
252          */
253         disable : function () { sheet.disabled = true; return this; },
254
255         /**
256          * Returns boolean indicating whether the StyleSheet is enabled
257          *
258          * @method isEnabled
259          * @return {Boolean} is it enabled?
260          */
261         isEnabled : function () { return !sheet.disabled; },
262
263         /**
264          * <p>Set style properties for a provided selector string.
265          * If the selector includes commas, it will be split into individual
266          * selectors and applied accordingly.  If the selector string does not
267          * have a corresponding rule in the sheet, it will be added.</p>
268          *
269          * <p>The second parameter can be either a string of CSS text,
270          * formatted as CSS ("font-size: 10px;"), or an object collection of
271          * properties and their new values.  Object properties must be in
272          * JavaScript format ({ fontSize: "10px" }).</p>
273          *
274          * <p>The float style property will be set by any of &quot;float&quot;,
275          * &quot;styleFloat&quot;, or &quot;cssFloat&quot; if passed in the
276          * object map.  Use "float: left;" format when passing a CSS text
277          * string.</p>
278          *
279          * @method set
280          * @param sel {String} the selector string to apply the changes to
281          * @param css {Object|String} Object literal of style properties and
282          *                      new values, or a string of cssText
283          * @return {StyleSheet} the StyleSheet instance
284          * @chainable
285          */
286         set : function (sel,css) {
287             var rule = cssRules[sel],
288                 multi = sel.split(/\s*,\s*/),i,
289                 idx;
290
291             // IE's addRule doesn't support multiple comma delimited selectors
292             if (multi.length > 1) {
293                 for (i = multi.length - 1; i >= 0; --i) {
294                     this.set(multi[i], css);
295                 }
296                 return this;
297             }
298
299             // Some selector values can cause IE to hang
300             if (!StyleSheet.isValidSelector(sel)) {
301                 YAHOO.log("Invalid selector '"+sel+"' passed to set (ignoring).",'warn','StyleSheet');
302                 return this;
303             }
304
305             // Opera throws an error if there's a syntax error in assigned
306             // cssText. Avoid this using a worker style collection, then
307             // assigning the resulting cssText.
308             if (rule) {
309                 rule.style.cssText = StyleSheet.toCssText(css,rule.style.cssText);
310             } else {
311                 idx = sheet[_rules].length;
312                 css = StyleSheet.toCssText(css);
313
314                 // IE throws an error when attempting to addRule(sel,'',n)
315                 // which would crop up if no, or only invalid values are used
316                 if (css) {
317                     _insertRule(sel, css, idx);
318
319                     // Safari replaces the rules collection, but maintains the
320                     // rule instances in the new collection when rules are
321                     // added/removed
322                     cssRules[sel] = sheet[_rules][idx];
323                 }
324             }
325             return this;
326         },
327
328         /**
329          * <p>Unset style properties for a provided selector string, removing
330          * their effect from the style cascade.</p>
331          *
332          * <p>If the selector includes commas, it will be split into individual
333          * selectors and applied accordingly.  If there are no properties
334          * remaining in the rule after unsetting, the rule is removed.</p>
335          *
336          * <p>The style property or properties in the second parameter must be the
337          * <p>JavaScript style property names. E.g. fontSize rather than font-size.</p>
338          *
339          * <p>The float style property will be unset by any of &quot;float&quot;,
340          * &quot;styleFloat&quot;, or &quot;cssFloat&quot;.</p>
341          *
342          * @method unset
343          * @param sel {String} the selector string to apply the changes to
344          * @param css {String|Array} style property name or Array of names
345          * @return {StyleSheet} the StyleSheet instance
346          * @chainable
347          */
348         unset : function (sel,css) {
349             var rule = cssRules[sel],
350                 multi = sel.split(/\s*,\s*/),
351                 remove = !css,
352                 rules, i;
353
354             // IE's addRule doesn't support multiple comma delimited selectors
355             // so rules are mapped internally by atomic selectors
356             if (multi.length > 1) {
357                 for (i = multi.length - 1; i >= 0; --i) {
358                     this.unset(multi[i], css);
359                 }
360                 return this;
361             }
362
363             if (rule) {
364                 if (!remove) {
365                     if (!lang.isArray(css)) {
366                         css = [css];
367                     }
368
369                     workerStyle.cssText = rule.style.cssText;
370                     for (i = css.length - 1; i >= 0; --i) {
371                         _unsetProperty(workerStyle,css[i]);
372                     }
373
374                     if (workerStyle.cssText) {
375                         rule.style.cssText = workerStyle.cssText;
376                     } else {
377                         remove = true;
378                     }
379                 }
380                 
381                 if (remove) { // remove the rule altogether
382                     rules = sheet[_rules];
383                     for (i = rules.length - 1; i >= 0; --i) {
384                         if (rules[i] === rule) {
385                             delete cssRules[sel];
386                             _deleteRule(i);
387                             break;
388                         }
389                     }
390                 }
391             }
392             return this;
393         },
394
395         /**
396          * Get the current cssText for a rule or the entire sheet.  If the
397          * selector param is supplied, only the cssText for that rule will be
398          * returned, if found.  If the selector string targets multiple
399          * selectors separated by commas, the cssText of the first rule only
400          * will be returned.  If no selector string, the stylesheet's full
401          * cssText will be returned.
402          *
403          * @method getCssText
404          * @param sel {String} Selector string
405          * @return {String}
406          */
407         getCssText : function (sel) {
408             var rule,css;
409
410             if (lang.isString(sel)) {
411                 // IE's addRule doesn't support multiple comma delimited
412                 // selectors so rules are mapped internally by atomic selectors
413                 rule = cssRules[sel.split(/\s*,\s*/)[0]];
414
415                 return rule ? rule.style.cssText : null;
416             } else {
417                 css = [];
418                 for (sel in cssRules) {
419                     if (cssRules.hasOwnProperty(sel)) {
420                         rule = cssRules[sel];
421                         css.push(rule.selectorText+" {"+rule.style.cssText+"}");
422                     }
423                 }
424                 return css.join("\n");
425             }
426         }
427     },true);
428
429 }
430
431 _toCssText = function (css,base) {
432     var f = css.styleFloat || css.cssFloat || css['float'],
433         prop;
434
435     workerStyle.cssText = base || '';
436
437     if (lang.isString(css)) {
438         // There is a danger here of incremental memory consumption in Opera
439         workerStyle.cssText += ';' + css;
440     } else {
441         if (f && !css[floatAttr]) {
442             css = lang.merge(css);
443             delete css.styleFloat; delete css.cssFloat; delete css['float'];
444             css[floatAttr] = f;
445         }
446
447         for (prop in css) {
448             if (css.hasOwnProperty(prop)) {
449                 try {
450                     // IE throws Invalid Value errors and doesn't like whitespace
451                     // in values ala ' red' or 'red '
452                     workerStyle[prop] = lang.trim(css[prop]);
453                 }
454                 catch (e) {
455                     YAHOO.log('Error assigning property "'+prop+'" to "'+css[prop]+
456                               "\" (ignored):\n"+e.message,'warn','StyleSheet');
457                 }
458             }
459         }
460     }
461
462     return workerStyle.cssText;
463 };
464
465 lang.augmentObject(StyleSheet, {
466     /**
467      * <p>Converts an object literal of style properties and values into a string
468      * of css text.  This can then be assigned to el.style.cssText.</p>
469      *
470      * <p>The optional second parameter is a cssText string representing the
471      * starting state of the style prior to alterations.  This is most often
472      * extracted from the eventual target's current el.style.cssText.</p>
473      *
474      * @method StyleSheet.toCssText
475      * @param css {Object} object literal of style properties and values
476      * @param cssText {String} OPTIONAL starting cssText value
477      * @return {String} the resulting cssText string
478      * @static
479      */
480     toCssText : (('opacity' in workerStyle) ? _toCssText :
481         // Wrap IE's toCssText to catch opacity.  The copy/merge is to preserve
482         // the input object's integrity, but if float and opacity are set, the
483         // input will be copied twice in IE.  Is there a way to avoid this
484         // without increasing the byte count?
485         function (css, cssText) {
486             if (lang.isObject(css) && 'opacity' in css) {
487                 css = lang.merge(css,{
488                         filter: 'alpha(opacity='+(css.opacity*100)+')'
489                       });
490                 delete css.opacity;
491             }
492             return _toCssText(css,cssText);
493         }),
494
495     /**
496      * Registers a StyleSheet instance in the static registry by the given name
497      *
498      * @method StyleSheet.register
499      * @param name {String} the name to assign the StyleSheet in the registry
500      * @param sheet {StyleSheet} The StyleSheet instance
501      * @return {Boolean} false if no name or sheet is not a StyleSheet
502      *              instance. true otherwise.
503      * @static
504      */
505     register : function (name,sheet) {
506         return !!(name && sheet instanceof StyleSheet &&
507                   !sheets[name] && (sheets[name] = sheet));
508     },
509
510     /**
511      * <p>Determines if a selector string is safe to use.  Used internally
512      * in set to prevent IE from locking up when attempting to add a rule for a
513      * &quot;bad selector&quot;.</p>
514      *
515      * <p>Bad selectors are considered to be any string containing unescaped
516      * `~!@$%^&()+=|{}[];'"?< or space. Also forbidden are . or # followed by
517      * anything other than an alphanumeric.  Additionally -abc or .-abc or
518      * #_abc or '# ' all fail.  There are likely more failure cases, so
519      * please file a bug if you encounter one.</p>
520      *
521      * @method StyleSheet.isValidSelector
522      * @param sel {String} the selector string
523      * @return {Boolean}
524      * @static
525      */
526     isValidSelector : function (sel) {
527         var valid = false;
528
529         if (sel && lang.isString(sel)) {
530
531             if (!selectors.hasOwnProperty(sel)) {
532                 // TEST: there should be nothing but white-space left after
533                 // these destructive regexs
534                 selectors[sel] = !/\S/.test(
535                     // combinators
536                     sel.replace(/\s+|\s*[+~>]\s*/g,' ').
537                     // attribute selectors (contents not validated)
538                     replace(/([^ ])\[.*?\]/g,'$1').
539                     // pseudo-class|element selectors (contents of parens
540                     // such as :nth-of-type(2) or :not(...) not validated)
541                     replace(/([^ ])::?[a-z][a-z\-]+[a-z](?:\(.*?\))?/ig,'$1').
542                     // element tags
543                     replace(/(?:^| )[a-z0-6]+/ig,' ').
544                     // escaped characters
545                     replace(/\\./g,'').
546                     // class and id identifiers
547                     replace(/[.#]\w[\w\-]*/g,''));
548             }
549
550             valid = selectors[sel];
551         }
552
553         return valid;
554     }
555 },true);
556
557 YAHOO.util.StyleSheet = StyleSheet;
558
559 })();
560
561 /*
562
563 NOTES
564  * Style node must be added to the head element.  Safari does not honor styles
565    applied to StyleSheet objects on style nodes in the body.
566  * StyleSheet object is created on the style node when the style node is added
567    to the head element in Firefox 2 (and maybe 3?)
568  * The cssRules collection is replaced after insertRule/deleteRule calls in
569    Safari 3.1.  Existing Rules are used in the new collection, so the collection
570    cannot be cached, but the rules can be.
571  * Opera requires that the index be passed with insertRule.
572  * Same-domain restrictions prevent modifying StyleSheet objects attached to
573    link elements with remote href (or "about:blank" or "javascript:false")
574  * Same-domain restrictions prevent reading StyleSheet cssRules/rules
575    collection of link elements with remote href (or "about:blank" or
576    "javascript:false")
577  * Same-domain restrictions result in Safari not populating node.sheet property
578    for link elements with remote href (et.al)
579  * IE names StyleSheet related properties and methods differently (see code)
580  * IE converts tag names to upper case in the Rule's selectorText
581  * IE converts empty string assignment to complex properties to value settings
582    for all child properties.  E.g. style.background = '' sets non-'' values on
583    style.backgroundPosition, style.backgroundColor, etc.  All else clear
584    style.background and all child properties.
585  * IE assignment style.filter = '' will result in style.cssText == 'FILTER:'
586  * All browsers support Rule.style.cssText as a read/write property, leaving
587    only opacity needing to be accounted for.
588  * Benchmarks of style.property = value vs style.cssText += 'property: value'
589    indicate cssText is slightly slower for single property assignment.  For
590    multiple property assignment, cssText speed stays relatively the same where
591    style.property speed decreases linearly by the number of properties set.
592    Exception being Opera 9.27, where style.property is always faster than
593    style.cssText.
594  * Opera 9.5b throws a syntax error when assigning cssText with a syntax error.
595  * Opera 9.5 doesn't honor rule.style.cssText = ''.  Previous style persists.
596    You have to remove the rule altogether.
597  * Stylesheet properties set with !important will trump inline style set on an
598    element or in el.style.property.
599  * Creating a worker style collection like document.createElement('p').style;
600    will fail after a time in FF (~5secs of inactivity).  Property assignments
601    will not alter the property or cssText.  It may be the generated node is
602    garbage collected and the style collection becomes inert (speculation).
603  * IE locks up when attempting to add a rule with a selector including at least
604    characters {[]}~`!@%^&*()+=|? (unescaped) and leading _ or -
605    such as addRule('-foo','{ color: red }') or addRule('._abc','{...}')
606  * IE's addRule doesn't support comma separated selectors such as
607    addRule('.foo, .bar','{..}')
608  * IE throws an error on valid values with leading/trailing white space.
609  * When creating an entire sheet at once, only FF2/3 & Opera allow creating a
610    style node, setting its innerHTML and appending to head.
611  * When creating an entire sheet at once, Safari requires the style node to be
612    created with content in innerHTML of another element.
613  * When creating an entire sheet at once, IE requires the style node content to
614    be set via node.styleSheet.cssText
615  * When creating an entire sheet at once in IE, styleSheet.cssText can't be
616    written until node.type = 'text/css'; is performed.
617  * When creating an entire sheet at once in IE, load-time fork on
618    var styleNode = d.createElement('style'); _method = styleNode.styleSheet ?..
619    fails (falsey).  During run-time, the test for .styleSheet works fine
620  * Setting complex properties in cssText will SOMETIMES allow child properties
621    to be unset
622    set         unset              FF2  FF3  S3.1  IE6  IE7  Op9.27  Op9.5
623    ----------  -----------------  ---  ---  ----  ---  ---  ------  -----
624    border      -top               NO   NO   YES   YES  YES  YES     YES
625                -top-color         NO   NO   YES             YES     YES
626                -color             NO   NO   NO              NO      NO
627    background  -color             NO   NO   YES             YES     YES
628                -position          NO   NO   YES             YES     YES
629                -position-x        NO   NO   NO              NO      NO
630    font        line-height        YES  YES  NO    NO   NO   NO      YES
631                -style             YES  YES  NO              YES     YES
632                -size              YES  YES  NO              YES     YES
633                -size-adjust       ???  ???  n/a   n/a  n/a  ???     ???
634    padding     -top               NO   NO   YES             YES     YES
635    margin      -top               NO   NO   YES             YES     YES
636    list-style  -type              YES  YES  YES             YES     YES
637                -position          YES  YES  YES             YES     YES
638    overflow    -x                 NO   NO   YES             n/a     YES
639
640    ??? - unsetting font-size-adjust has the same effect as unsetting font-size
641  * FireFox and WebKit populate rule.cssText as "SELECTOR { CSSTEXT }", but
642    Opera and IE do not.
643  * IE6 and IE7 silently ignore the { and } if passed into addRule('.foo','{
644    color:#000}',0).  IE8 does not and creates an empty rule.
645  * IE6-8 addRule('.foo','',n) throws an error.  Must supply *some* cssText
646 */
647
648 YAHOO.register("stylesheet", YAHOO.util.StyleSheet, {version: "2.8.0r4", build: "2449"});