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