2 YUI 3.13.0 (build 508226d)
3 Copyright 2013 Yahoo! Inc. All rights reserved.
4 Licensed under the BSD License.
5 http://yuilibrary.com/license/
8 YUI.add('stylesheet', function (Y, NAME) {
11 * The StyleSheet component is a module for creating and modifying CSS
17 p = d.createElement('p'), // Have to hold the node (see notes)
18 workerStyle = p.style, // worker style collection
19 isString = Y.Lang.isString,
22 floatAttr = ('cssFloat' in workerStyle) ? 'cssFloat' : 'styleFloat',
30 // Normalizes the removal of an assigned style for opacity. IE uses the filter
32 _unsetOpacity = (OPACITY in workerStyle) ?
33 function (style) { style.opacity = EMPTY; } :
34 function (style) { style.filter = EMPTY; };
36 // Normalizes the removal of an assigned style for a given property. Expands
37 // shortcut properties if necessary and handles the various names for the float
39 workerStyle.border = "1px solid red";
40 workerStyle.border = EMPTY; // IE doesn't unset child properties
41 _unsetProperty = workerStyle.borderLeft ?
42 function (style,prop) {
44 if (prop !== floatAttr && prop.toLowerCase().indexOf(FLOAT) != -1) {
47 if (isString(style[prop])) {
50 case 'filter' : _unsetOpacity(style); break;
52 style.font = style.fontStyle = style.fontVariant =
53 style.fontWeight = style.fontSize = style.lineHeight =
54 style.fontFamily = EMPTY;
58 if (p.indexOf(prop) === 0) {
65 function (style,prop) {
66 if (prop !== floatAttr && prop.toLowerCase().indexOf(FLOAT) != -1) {
69 if (isString(style[prop])) {
70 if (prop === OPACITY) {
79 * Create an instance of StyleSheet to encapsulate a css stylesheet.
80 * The constructor can be called using function or constructor syntax.
81 * <pre><code>var sheet = Y.StyleSheet(..);</pre></code>
83 * <pre><code>var sheet = new Y.StyleSheet(..);</pre></code>
85 * The first parameter passed can be any of the following things:
87 * <li>The desired string name to register a new empty sheet</li>
88 * <li>The string name of an existing StyleSheet instance</li>
89 * <li>The unique guid generated for an existing StyleSheet instance</li>
90 * <li>The id of an existing <code><link></code> or <code><style></code> node</li>
91 * <li>The node reference for an existing <code><link></code> or <code><style></code> node</li>
92 * <li>The Y.Node instance wrapping an existing <code><link></code> or <code><style></code> node</li>
93 * <li>A chunk of css text to create a new stylesheet from</li>
96 * <p>If a string is passed, StyleSheet will first look in its static name
97 * registry for an existing sheet, then in the DOM for an element with that id.
98 * If neither are found and the string contains the { character, it will be
99 * used as a the initial cssText for a new StyleSheet. Otherwise, a new empty
100 * StyleSheet is created, assigned the string value as a name, and registered
101 * statically by that name.</p>
103 * <p>The optional second parameter is a string name to register the sheet as.
104 * This param is largely useful when providing a node id/ref or chunk of css
105 * text to create a populated instance.</p>
109 * @param seed {String|HTMLElement|Node} a style or link node, its id, or a
110 * name or guid of a StyleSheet, or a string of css text
111 * @param name {String} (optional) name to register instance for future static
114 function StyleSheet(seed, name) {
124 // Factory or constructor
125 if (!(Y.instanceOf(this, StyleSheet))) {
126 return new StyleSheet(seed,name);
129 // Extract the DOM node from Node instances
131 if (Y.Node && seed instanceof Y.Node) {
133 } else if (seed.nodeName) {
135 // capture the DOM node if the string is an id
136 } else if (isString(seed)) {
137 if (seed && sheets[seed]) {
140 node = d.getElementById(seed.replace(/^#/,EMPTY));
143 // Check for the StyleSheet in the static registry
144 if (node && sheets[Y.stamp(node)]) {
145 return sheets[Y.stamp(node)];
150 // Create a style node if necessary
151 if (!node || !/^(?:style|link)$/i.test(node.nodeName)) {
152 node = d.createElement('style');
153 node.type = 'text/css';
156 if (isString(seed)) {
157 // Create entire sheet from seed cssText
158 if (seed.indexOf('{') != -1) {
159 // Not a load-time fork because low run-time impact and IE fails
160 // test for s.styleSheet at page load time (oddly)
161 if (node.styleSheet) {
162 node.styleSheet.cssText = seed;
164 node.appendChild(d.createTextNode(seed));
171 // Make sure the node is attached to the appropriate head element
172 if (!node.parentNode || node.parentNode.nodeName.toLowerCase() !== 'head') {
173 head = (node.ownerDocument || d).getElementsByTagName('head')[0];
174 // styleSheet isn't available on the style node in FF2 until appended
175 // to the head element. style nodes appended to body do not affect
177 head.appendChild(node);
180 // Begin setting up private aliases to the important moving parts
181 // 1. The stylesheet object
182 // IE stores StyleSheet under the "styleSheet" property
183 // Safari doesn't populate sheet for xdomain link elements
184 sheet = node.sheet || node.styleSheet;
186 // 2. The style rules collection
187 // IE stores the rules collection under the "rules" property
188 _rules = sheet && ('cssRules' in sheet) ? 'cssRules' : 'rules';
190 // 3. The method to remove a rule from the stylesheet
191 // IE supports removeRule
192 _deleteRule = ('deleteRule' in sheet) ?
193 function (i) { sheet.deleteRule(i); } :
194 function (i) { sheet.removeRule(i); };
196 // 4. The method to add a new rule to the stylesheet
197 // IE supports addRule with different signature
198 _insertRule = ('insertRule' in sheet) ?
199 function (sel,css,i) { sheet.insertRule(sel+' {'+css+'}',i); } :
200 function (sel,css,i) { sheet.addRule(sel,css,i); };
202 // 5. Initialize the cssRules map from the node
203 // xdomain link nodes forbid access to the cssRules collection, so this
204 // will throw an error.
205 // TODO: research alternate stylesheet, @media
206 for (i = sheet[_rules].length - 1; i >= 0; --i) {
207 r = sheet[_rules][i];
208 sel = r.selectorText;
211 cssRules[sel].style.cssText += ';' + r.style.cssText;
218 // Cache the instance by the generated Id
219 StyleSheet.register(Y.stamp(node),this);
221 // Register the instance by name if provided or defaulted from seed
223 StyleSheet.register(name,this);
229 * Get the unique stamp for this StyleSheet instance
232 * @return {Number} the static id
234 getId : function () { return Y.stamp(node); },
237 * Enable all the rules in the sheet
240 * @return {StyleSheet}
243 enable : function () { sheet.disabled = false; return this; },
246 * Disable all the rules in the sheet. Rules may be changed while the
247 * StyleSheet is disabled.
250 * @return {StyleSheet}
253 disable : function () { sheet.disabled = true; return this; },
256 * Returns false if the StyleSheet is disabled. Otherwise true.
261 isEnabled : function () { return !sheet.disabled; },
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>
269 * <p>The object properties in the second parameter must be the JavaScript
270 * names of style properties. E.g. fontSize rather than font-size.</p>
272 * <p>The float style property will be set by any of "float",
273 * "styleFloat", or "cssFloat".</p>
276 * @param sel {String} the selector string to apply the changes to
277 * @param css {Object} Object literal of style properties and new values
278 * @return {StyleSheet}
281 set : function (sel,css) {
282 var rule = cssRules[sel],
283 multi = sel.split(/\s*,\s*/),i,
286 // IE's addRule doesn't support multiple comma delimited selectors
287 if (multi.length > 1) {
288 for (i = multi.length - 1; i >= 0; --i) {
289 this.set(multi[i], css);
294 // Some selector values can cause IE to hang
295 if (!StyleSheet.isValidSelector(sel)) {
299 // Opera throws an error if there's a syntax error in assigned
300 // cssText. Avoid this using a worker style collection, then
301 // assigning the resulting cssText.
303 rule.style.cssText = StyleSheet.toCssText(css,rule.style.cssText);
305 idx = sheet[_rules].length;
306 css = StyleSheet.toCssText(css);
308 // IE throws an error when attempting to addRule(sel,'',n)
309 // which would crop up if no, or only invalid values are used
311 _insertRule(sel, css, idx);
313 // Safari replaces the rules collection, but maintains the
314 // rule instances in the new collection when rules are
316 cssRules[sel] = sheet[_rules][idx];
323 * <p>Unset style properties for a provided selector string, removing
324 * their effect from the style cascade.</p>
326 * <p>If the selector includes commas, it will be split into individual
327 * selectors and applied accordingly. If there are no properties
328 * remaining in the rule after unsetting, the rule is removed.</p>
330 * <p>The style property or properties in the second parameter must be the
331 * JavaScript style property names. E.g. fontSize rather than font-size.</p>
333 * <p>The float style property will be unset by any of "float",
334 * "styleFloat", or "cssFloat".</p>
337 * @param sel {String} the selector string to apply the changes to
338 * @param css {String|Array} style property name or Array of names
339 * @return {StyleSheet}
342 unset : function (sel,css) {
343 var rule = cssRules[sel],
344 multi = sel.split(/\s*,\s*/),
348 // IE's addRule doesn't support multiple comma delimited selectors
349 // so rules are mapped internally by atomic selectors
350 if (multi.length > 1) {
351 for (i = multi.length - 1; i >= 0; --i) {
352 this.unset(multi[i], css);
361 workerStyle.cssText = rule.style.cssText;
362 for (i = css.length - 1; i >= 0; --i) {
363 _unsetProperty(workerStyle,css[i]);
366 if (workerStyle.cssText) {
367 rule.style.cssText = workerStyle.cssText;
373 if (remove) { // remove the rule altogether
374 rules = sheet[_rules];
375 for (i = rules.length - 1; i >= 0; --i) {
376 if (rules[i] === rule) {
377 delete cssRules[sel];
388 * Get the current cssText for a rule or the entire sheet. If the
389 * selector param is supplied, only the cssText for that rule will be
390 * returned, if found. If the selector string targets multiple
391 * selectors separated by commas, the cssText of the first rule only
392 * will be returned. If no selector string, the stylesheet's full
393 * cssText will be returned.
396 * @param sel {String} Selector string
399 getCssText : function (sel) {
400 var rule, css, selector;
403 // IE's addRule doesn't support multiple comma delimited
404 // selectors so rules are mapped internally by atomic selectors
405 rule = cssRules[sel.split(/\s*,\s*/)[0]];
407 return rule ? rule.style.cssText : null;
410 for (selector in cssRules) {
411 if (cssRules.hasOwnProperty(selector)) {
412 rule = cssRules[selector];
413 css.push(rule.selectorText+" {"+rule.style.cssText+"}");
416 return css.join("\n");
423 _toCssText = function (css,base) {
424 var f = css.styleFloat || css.cssFloat || css[FLOAT],
428 // A very difficult to repro/isolate IE 9 beta (and Platform Preview 7) bug
429 // was reduced to this line throwing the error:
430 // "Invalid this pointer used as target for method call"
431 // It appears that the style collection is corrupted. The error is
432 // catchable, so in a best effort to work around it, replace the
433 // p and workerStyle and try the assignment again.
435 workerStyle.cssText = base || EMPTY;
437 p = d.createElement('p');
438 workerStyle = p.style;
439 workerStyle.cssText = base || EMPTY;
442 if (f && !css[floatAttr]) {
444 delete css.styleFloat; delete css.cssFloat; delete css[FLOAT];
449 if (css.hasOwnProperty(prop)) {
451 // IE throws Invalid Value errors and doesn't like whitespace
452 // in values ala ' red' or 'red '
453 workerStyle[prop] = trim(css[prop]);
459 return workerStyle.cssText;
464 * <p>Converts an object literal of style properties and values into a string
465 * of css text. This can then be assigned to el.style.cssText.</p>
467 * <p>The optional second parameter is a cssText string representing the
468 * starting state of the style prior to alterations. This is most often
469 * extracted from the eventual target's current el.style.cssText.</p>
472 * @param css {Object} object literal of style properties and values
473 * @param cssText {String} (optional) starting cssText value
474 * @return {String} the resulting cssText string
477 toCssText : ((OPACITY in workerStyle) ? _toCssText :
478 // Wrap IE's toCssText to catch opacity. The copy/merge is to preserve
479 // the input object's integrity, but if float and opacity are set, the
480 // input will be copied twice in IE. Is there a way to avoid this
481 // without increasing the byte count?
482 function (css, cssText) {
483 if (OPACITY in css) {
485 filter: 'alpha(opacity='+(css.opacity*100)+')'
489 return _toCssText(css,cssText);
493 * Registers a StyleSheet instance in the static registry by the given name
496 * @param name {String} the name to assign the StyleSheet in the registry
497 * @param sheet {StyleSheet} The StyleSheet instance
498 * @return {Boolean} false if no name or sheet is not a StyleSheet
499 * instance. true otherwise.
502 register : function (name,sheet) {
503 return !!(name && sheet instanceof StyleSheet &&
504 !sheets[name] && (sheets[name] = sheet));
508 * <p>Determines if a selector string is safe to use. Used internally
509 * in set to prevent IE from locking up when attempting to add a rule for a
510 * "bad selector".</p>
512 * <p>Bad selectors are considered to be any string containing unescaped
513 * `~!@$%^&()+=|{}[];'"?< or space. Also forbidden are . or # followed by
514 * anything other than an alphanumeric. Additionally -abc or .-abc or
515 * #_abc or '# ' all fail. There are likely more failure cases, so
516 * please file a bug if you encounter one.</p>
518 * @method isValidSelector
519 * @param sel {String} the selector string
523 isValidSelector : function (sel) {
526 if (sel && isString(sel)) {
528 if (!selectors.hasOwnProperty(sel)) {
529 // TEST: there should be nothing but white-space left after
530 // these destructive regexs
531 selectors[sel] = !/\S/.test(
533 sel.replace(/\s+|\s*[+~>]\s*/g,' ').
534 // attribute selectors (contents not validated)
535 replace(/([^ ])\[.*?\]/g,'$1').
536 // pseudo-class|element selectors (contents of parens
537 // such as :nth-of-type(2) or :not(...) not validated)
538 replace(/([^ ])::?[a-z][a-z\-]+[a-z](?:\(.*?\))?/ig,'$1').
540 replace(/(?:^| )[a-z0-6]+/ig,' ').
541 // escaped characters
542 replace(/\\./g,EMPTY).
543 // class and id identifiers
544 replace(/[.#]\w[\w\-]*/g,EMPTY));
547 valid = selectors[sel];
554 Y.StyleSheet = StyleSheet;
559 * Style node must be added to the head element. Safari does not honor styles
560 applied to StyleSheet objects on style nodes in the body.
561 * StyleSheet object is created on the style node when the style node is added
562 to the head element in Firefox 2 (and maybe 3?)
563 * The cssRules collection is replaced after insertRule/deleteRule calls in
564 Safari 3.1. Existing Rules are used in the new collection, so the collection
565 cannot be cached, but the rules can be.
566 * Opera requires that the index be passed with insertRule.
567 * Same-domain restrictions prevent modifying StyleSheet objects attached to
568 link elements with remote href (or "about:blank" or "javascript:false")
569 * Same-domain restrictions prevent reading StyleSheet cssRules/rules
570 collection of link elements with remote href (or "about:blank" or
572 * Same-domain restrictions result in Safari not populating node.sheet property
573 for link elements with remote href (et.al)
574 * IE names StyleSheet related properties and methods differently (see code)
575 * IE converts tag names to upper case in the Rule's selectorText
576 * IE converts empty string assignment to complex properties to value settings
577 for all child properties. E.g. style.background = '' sets non-'' values on
578 style.backgroundPosition, style.backgroundColor, etc. All else clear
579 style.background and all child properties.
580 * IE assignment style.filter = '' will result in style.cssText == 'FILTER:'
581 * All browsers support Rule.style.cssText as a read/write property, leaving
582 only opacity needing to be accounted for.
583 * Benchmarks of style.property = value vs style.cssText += 'property: value'
584 indicate cssText is slightly slower for single property assignment. For
585 multiple property assignment, cssText speed stays relatively the same where
586 style.property speed decreases linearly by the number of properties set.
587 Exception being Opera 9.27, where style.property is always faster than
589 * Opera 9.5b throws a syntax error when assigning cssText with a syntax error.
590 * Opera 9.5 doesn't honor rule.style.cssText = ''. Previous style persists.
591 You have to remove the rule altogether.
592 * Stylesheet properties set with !important will trump inline style set on an
593 element or in el.style.property.
594 * Creating a worker style collection like document.createElement('p').style;
595 will fail after a time in FF (~5secs of inactivity). Property assignments
596 will not alter the property or cssText. It may be the generated node is
597 garbage collected and the style collection becomes inert (speculation).
598 * IE locks up when attempting to add a rule with a selector including at least
599 characters {[]}~`!@%^&*()+=|? (unescaped) and leading _ or -
600 such as addRule('-foo','{ color: red }') or addRule('._abc','{...}')
601 * IE's addRule doesn't support comma separated selectors such as
602 addRule('.foo, .bar','{..}')
603 * IE throws an error on valid values with leading/trailing white space.
604 * When creating an entire sheet at once, only FF2/3 & Opera allow creating a
605 style node, setting its innerHTML and appending to head.
606 * When creating an entire sheet at once, Safari requires the style node to be
607 created with content in innerHTML of another element.
608 * When creating an entire sheet at once, IE requires the style node content to
609 be set via node.styleSheet.cssText
610 * When creating an entire sheet at once in IE, styleSheet.cssText can't be
611 written until node.type = 'text/css'; is performed.
612 * When creating an entire sheet at once in IE, load-time fork on
613 var styleNode = d.createElement('style'); _method = styleNode.styleSheet ?..
614 fails (falsey). During run-time, the test for .styleSheet works fine
615 * Setting complex properties in cssText will SOMETIMES allow child properties
617 set unset FF2 FF3 S3.1 IE6 IE7 Op9.27 Op9.5
618 ---------- ----------------- --- --- ---- --- --- ------ -----
619 border -top NO NO YES YES YES YES YES
620 -top-color NO NO YES YES YES
621 -color NO NO NO NO NO
622 background -color NO NO YES YES YES
623 -position NO NO YES YES YES
624 -position-x NO NO NO NO NO
625 font line-height YES YES NO NO NO NO YES
626 -style YES YES NO YES YES
627 -size YES YES NO YES YES
628 -size-adjust ??? ??? n/a n/a n/a ??? ???
629 padding -top NO NO YES YES YES
630 margin -top NO NO YES YES YES
631 list-style -type YES YES YES YES YES
632 -position YES YES YES YES YES
633 overflow -x NO NO YES n/a YES
635 ??? - unsetting font-size-adjust has the same effect as unsetting font-size
636 * FireFox and WebKit populate rule.cssText as "SELECTOR { CSSTEXT }", but
638 * IE6 and IE7 silently ignore the { and } if passed into addRule('.foo','{
639 color:#000}',0). IE8 does not and creates an empty rule.
640 * IE6-8 addRule('.foo','',n) throws an error. Must supply *some* cssText
645 }, '3.13.0', {"requires": ["yui-base"]});