Debian Codegraph @

closure-library/closure/goog/debug/devcss/devcss.js

raw
1 // Copyright 2008 The Closure Library Authors. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS-IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 /**
16 * @fileoverview Runtime development CSS Compiler emulation, via javascript.
17 * This class provides an approximation to CSSCompiler's functionality by
18 * hacking the live CSSOM.
19 * This code is designed to be inserted in the DOM immediately after the last
20 * style block in HEAD when in development mode, i.e. you are not using a
21 * running instance of a CSS Compiler to pass your CSS through.
22 */
23
24
25 goog.provide('goog.debug.DevCss');
26 goog.provide('goog.debug.DevCss.UserAgent');
27
28 goog.require('goog.asserts');
29 goog.require('goog.cssom');
30 goog.require('goog.dom.classlist');
31 goog.require('goog.events');
32 goog.require('goog.events.EventType');
33 goog.require('goog.string');
34 goog.require('goog.userAgent');
35
36
37
38 /**
39 * A class for solving development CSS issues/emulating the CSS Compiler.
40 * @param {goog.debug.DevCss.UserAgent=} opt_userAgent The user agent, if not
41 * passed in, will be determined using goog.userAgent.
42 * @param {number|string=} opt_userAgentVersion The user agent's version.
43 * If not passed in, will be determined using goog.userAgent.
44 * @throws {Error} When userAgent detection fails.
45 * @constructor
46 * @final
47 */
48 goog.debug.DevCss = function(opt_userAgent, opt_userAgentVersion) {
49 if (!opt_userAgent) {
50 // Walks through the known goog.userAgents.
51 if (goog.userAgent.IE) {
52 opt_userAgent = goog.debug.DevCss.UserAgent.IE;
53 } else if (goog.userAgent.GECKO) {
54 opt_userAgent = goog.debug.DevCss.UserAgent.GECKO;
55 } else if (goog.userAgent.WEBKIT) {
56 opt_userAgent = goog.debug.DevCss.UserAgent.WEBKIT;
57 } else if (goog.userAgent.MOBILE) {
58 opt_userAgent = goog.debug.DevCss.UserAgent.MOBILE;
59 } else if (goog.userAgent.OPERA) {
60 opt_userAgent = goog.debug.DevCss.UserAgent.OPERA;
61 } else if (goog.userAgent.EDGE) {
62 opt_userAgent = goog.debug.DevCss.UserAgent.EDGE;
63 }
64 }
65 switch (opt_userAgent) {
66 case goog.debug.DevCss.UserAgent.OPERA:
67 case goog.debug.DevCss.UserAgent.IE:
68 case goog.debug.DevCss.UserAgent.GECKO:
69 case goog.debug.DevCss.UserAgent.FIREFOX:
70 case goog.debug.DevCss.UserAgent.WEBKIT:
71 case goog.debug.DevCss.UserAgent.SAFARI:
72 case goog.debug.DevCss.UserAgent.MOBILE:
73 case goog.debug.DevCss.UserAgent.EDGE:
74 break;
75 default:
76 throw new Error(
77 'Could not determine the user agent from known UserAgents');
78 }
79
80 /**
81 * One of goog.debug.DevCss.UserAgent.
82 * @type {string}
83 * @private
84 */
85 this.userAgent_ = opt_userAgent;
86
87 /**
88 * @const @private
89 */
90 this.userAgentTokens_ = {};
91
92 /**
93 * @type {number|string}
94 * @private
95 */
96 this.userAgentVersion_ = opt_userAgentVersion || goog.userAgent.VERSION;
97 this.generateUserAgentTokens_();
98
99 /**
100 * @type {boolean}
101 * @private
102 */
103 this.isIe6OrLess_ = this.userAgent_ == goog.debug.DevCss.UserAgent.IE &&
104 goog.string.compareVersions('7', this.userAgentVersion_) > 0;
105
106 if (this.isIe6OrLess_) {
107 /**
108 * @type {Array<{classNames,combinedClassName,els}>}
109 * @private
110 */
111 this.ie6CombinedMatches_ = [];
112 }
113 };
114
115
116 /**
117 * Rewrites the CSSOM as needed to activate any useragent-specific selectors.
118 * @param {boolean=} opt_enableIe6ReadyHandler If true(the default), and the
119 * userAgent is ie6, we set a document "ready" event handler to walk the DOM
120 * and make combined selector className changes. Having this parameter also
121 * aids unit testing.
122 */
123 goog.debug.DevCss.prototype.activateBrowserSpecificCssRules = function(
124 opt_enableIe6ReadyHandler) {
125 var enableIe6EventHandler =
126 goog.isDef(opt_enableIe6ReadyHandler) ? opt_enableIe6ReadyHandler : true;
127 var cssRules = goog.cssom.getAllCssStyleRules();
128
129 for (var i = 0, cssRule; cssRule = cssRules[i]; i++) {
130 this.replaceBrowserSpecificClassNames_(cssRule);
131 }
132
133 // Since we may have manipulated the rules above, we'll have to do a
134 // complete sweep again if we're in IE6. Luckily performance doesn't
135 // matter for this tool.
136 if (this.isIe6OrLess_) {
137 cssRules = goog.cssom.getAllCssStyleRules();
138 for (var i = 0, cssRule; cssRule = cssRules[i]; i++) {
139 this.replaceIe6CombinedSelectors_(cssRule);
140 }
141 }
142
143 // Add an event listener for document ready to rewrite any necessary
144 // combined classnames in IE6.
145 if (this.isIe6OrLess_ && enableIe6EventHandler) {
146 goog.events.listen(
147 document, goog.events.EventType.LOAD,
148 goog.bind(this.addIe6CombinedClassNames_, this));
149 }
150 };
151
152
153 /**
154 * A list of possible user agent strings.
155 * @enum {string}
156 */
157 goog.debug.DevCss.UserAgent = {
158 OPERA: 'OPERA',
159 IE: 'IE',
160 GECKO: 'GECKO',
161 FIREFOX: 'GECKO',
162 WEBKIT: 'WEBKIT',
163 SAFARI: 'WEBKIT',
164 MOBILE: 'MOBILE',
165 EDGE: 'EDGE'
166 };
167
168
169 /**
170 * A list of strings that may be used for matching in CSS files/development.
171 * @enum {string}
172 * @private
173 */
174 goog.debug.DevCss.CssToken_ = {
175 USERAGENT: 'USERAGENT',
176 SEPARATOR: '-',
177 LESS_THAN: 'LT',
178 GREATER_THAN: 'GT',
179 LESS_THAN_OR_EQUAL: 'LTE',
180 GREATER_THAN_OR_EQUAL: 'GTE',
181 IE6_SELECTOR_TEXT: 'goog-ie6-selector',
182 IE6_COMBINED_GLUE: '_'
183 };
184
185
186 /**
187 * Generates user agent token match strings with comparison and version bits.
188 * For example:
189 * userAgentTokens_.ANY will be like 'GECKO'
190 * userAgentTokens_.LESS_THAN will be like 'GECKO-LT3' etc...
191 * @private
192 */
193 goog.debug.DevCss.prototype.generateUserAgentTokens_ = function() {
194 this.userAgentTokens_.ANY = goog.debug.DevCss.CssToken_.USERAGENT +
195 goog.debug.DevCss.CssToken_.SEPARATOR + this.userAgent_;
196 this.userAgentTokens_.EQUALS =
197 this.userAgentTokens_.ANY + goog.debug.DevCss.CssToken_.SEPARATOR;
198 this.userAgentTokens_.LESS_THAN = this.userAgentTokens_.ANY +
199 goog.debug.DevCss.CssToken_.SEPARATOR +
200 goog.debug.DevCss.CssToken_.LESS_THAN;
201 this.userAgentTokens_.LESS_THAN_OR_EQUAL = this.userAgentTokens_.ANY +
202 goog.debug.DevCss.CssToken_.SEPARATOR +
203 goog.debug.DevCss.CssToken_.LESS_THAN_OR_EQUAL;
204 this.userAgentTokens_.GREATER_THAN = this.userAgentTokens_.ANY +
205 goog.debug.DevCss.CssToken_.SEPARATOR +
206 goog.debug.DevCss.CssToken_.GREATER_THAN;
207 this.userAgentTokens_.GREATER_THAN_OR_EQUAL = this.userAgentTokens_.ANY +
208 goog.debug.DevCss.CssToken_.SEPARATOR +
209 goog.debug.DevCss.CssToken_.GREATER_THAN_OR_EQUAL;
210 };
211
212
213 /**
214 * Gets the version number bit from a selector matching userAgentToken.
215 * @param {string} selectorText The selector text of a CSS rule.
216 * @param {string} userAgentToken Includes the LTE/GTE bit to see if it matches.
217 * @return {string|undefined} The version number.
218 * @private
219 */
220 goog.debug.DevCss.prototype.getVersionNumberFromSelectorText_ = function(
221 selectorText, userAgentToken) {
222 var regex = new RegExp(userAgentToken + '([\\d\\.]+)');
223 var matches = regex.exec(selectorText);
224 if (matches && matches.length == 2) {
225 return matches[1];
226 }
227 };
228
229
230 /**
231 * Extracts a rule version from the selector text, and if it finds one, calls
232 * compareVersions against it and the passed in token string to provide the
233 * value needed to determine if we have a match or not.
234 * @param {CSSRule} cssRule The rule to test against.
235 * @param {string} token The match token to test against the rule.
236 * @return {!Array|undefined} A tuple with the result of the compareVersions
237 * call and the matched ruleVersion.
238 * @private
239 */
240 goog.debug.DevCss.prototype.getRuleVersionAndCompare_ = function(
241 cssRule, token) {
242 if (!cssRule.selectorText || !cssRule.selectorText.match(token)) {
243 return;
244 }
245 var ruleVersion =
246 this.getVersionNumberFromSelectorText_(cssRule.selectorText, token);
247 if (!ruleVersion) {
248 return;
249 }
250
251 var comparison =
252 goog.string.compareVersions(this.userAgentVersion_, ruleVersion);
253 return [comparison, ruleVersion];
254 };
255
256
257 /**
258 * Replaces a CSS selector if we have matches based on our useragent/version.
259 * Example: With a selector like ".USERAGENT-IE-LTE6 .class { prop: value }" if
260 * we are running IE6 we'll end up with ".class { prop: value }", thereby
261 * "activating" the selector.
262 * @param {CSSRule} cssRule The cssRule to potentially replace.
263 * @private
264 */
265 goog.debug.DevCss.prototype.replaceBrowserSpecificClassNames_ = function(
266 cssRule) {
267
268 // If we don't match the browser token, we can stop now.
269 if (!cssRule.selectorText ||
270 !cssRule.selectorText.match(this.userAgentTokens_.ANY)) {
271 return;
272 }
273
274 // We know it will begin as a classname.
275 var additionalRegexString;
276
277 // Tests "Less than or equals".
278 var compared = this.getRuleVersionAndCompare_(
279 cssRule, this.userAgentTokens_.LESS_THAN_OR_EQUAL);
280 if (compared && compared.length) {
281 if (compared[0] > 0) {
282 return;
283 }
284 additionalRegexString =
285 this.userAgentTokens_.LESS_THAN_OR_EQUAL + compared[1];
286 }
287
288 // Tests "Less than".
289 compared =
290 this.getRuleVersionAndCompare_(cssRule, this.userAgentTokens_.LESS_THAN);
291 if (compared && compared.length) {
292 if (compared[0] > -1) {
293 return;
294 }
295 additionalRegexString = this.userAgentTokens_.LESS_THAN + compared[1];
296 }
297
298 // Tests "Greater than or equals".
299 compared = this.getRuleVersionAndCompare_(
300 cssRule, this.userAgentTokens_.GREATER_THAN_OR_EQUAL);
301 if (compared && compared.length) {
302 if (compared[0] < 0) {
303 return;
304 }
305 additionalRegexString =
306 this.userAgentTokens_.GREATER_THAN_OR_EQUAL + compared[1];
307 }
308
309 // Tests "Greater than".
310 compared = this.getRuleVersionAndCompare_(
311 cssRule, this.userAgentTokens_.GREATER_THAN);
312 if (compared && compared.length) {
313 if (compared[0] < 1) {
314 return;
315 }
316 additionalRegexString = this.userAgentTokens_.GREATER_THAN + compared[1];
317 }
318
319 // Tests "Equals".
320 compared =
321 this.getRuleVersionAndCompare_(cssRule, this.userAgentTokens_.EQUALS);
322 if (compared && compared.length) {
323 if (compared[0] != 0) {
324 return;
325 }
326 additionalRegexString = this.userAgentTokens_.EQUALS + compared[1];
327 }
328
329 // If we got to here without generating the additionalRegexString, then
330 // we did not match any of our comparison token strings, and we want a
331 // general browser token replacement.
332 if (!additionalRegexString) {
333 additionalRegexString = this.userAgentTokens_.ANY;
334 }
335
336 // We need to match at least a single whitespace character to know that
337 // we are matching the entire useragent string token.
338 var regexString = '\\.' + additionalRegexString + '\\s+';
339 var re = new RegExp(regexString, 'g');
340
341 var currentCssText = goog.cssom.getCssTextFromCssRule(cssRule);
342
343 // Replacing the token with '' activates the selector for this useragent.
344 var newCssText = currentCssText.replace(re, '');
345
346 if (newCssText != currentCssText) {
347 goog.cssom.replaceCssRule(cssRule, newCssText);
348 }
349 };
350
351
352 /**
353 * Replaces IE6 combined selector rules with a workable development alternative.
354 * IE6 actually parses .class1.class2 {} to simply .class2 {} which is nasty.
355 * To fully support combined selectors in IE6 this function needs to be paired
356 * with a call to replace the relevant DOM elements classNames as well.
357 * @see {this.addIe6CombinedClassNames_}
358 * @param {CSSRule} cssRule The rule to potentially fix.
359 * @private
360 */
361 goog.debug.DevCss.prototype.replaceIe6CombinedSelectors_ = function(cssRule) {
362 // This match only ever works in IE because other UA's won't have our
363 // IE6_SELECTOR_TEXT in the cssText property.
364 if (cssRule.style && cssRule.style.cssText &&
365 cssRule.style.cssText.match(
366 goog.debug.DevCss.CssToken_.IE6_SELECTOR_TEXT)) {
367 var cssText = goog.cssom.getCssTextFromCssRule(cssRule);
368 var combinedSelectorText = this.getIe6CombinedSelectorText_(cssText);
369 if (combinedSelectorText) {
370 var newCssText = combinedSelectorText + '{' + cssRule.style.cssText + '}';
371 goog.cssom.replaceCssRule(cssRule, newCssText);
372 }
373 }
374 };
375
376
377 /**
378 * Gets the appropriate new combined selector text for IE6.
379 * Also adds an entry onto ie6CombinedMatches_ with relevant info for the
380 * likely following call to walk the DOM and rewrite the class attribute.
381 * Example: With a selector like
382 * ".class2 { -goog-ie6-selector: .class1.class2; prop: value }".
383 * this function will return:
384 * ".class1_class2 { prop: value }".
385 * @param {string} cssText The CSS selector text and css rule text combined.
386 * @return {?string} The rewritten css rule text.
387 * @private
388 */
389 goog.debug.DevCss.prototype.getIe6CombinedSelectorText_ = function(cssText) {
390 var regex = new RegExp(
391 goog.debug.DevCss.CssToken_.IE6_SELECTOR_TEXT +
392 '\\s*:\\s*\\"([^\\"]+)\\"',
393 'gi');
394 var matches = regex.exec(cssText);
395 if (matches) {
396 var combinedSelectorText = matches[1];
397 // To aid in later fixing the DOM, we need to split up the possible
398 // selector groups by commas.
399 var groupedSelectors = combinedSelectorText.split(/\s*\,\s*/);
400 for (var i = 0, selector; selector = groupedSelectors[i]; i++) {
401 // Strips off the leading ".".
402 var combinedClassName = selector.substr(1);
403 var classNames = combinedClassName.split(
404 goog.debug.DevCss.CssToken_.IE6_COMBINED_GLUE);
405 var entry = {
406 classNames: classNames,
407 combinedClassName: combinedClassName,
408 els: []
409 };
410 this.ie6CombinedMatches_.push(entry);
411 }
412 return combinedSelectorText;
413 }
414 return null;
415 };
416
417
418 /**
419 * Adds combined selectors with underscores to make them "work" in IE6.
420 * @see {this.replaceIe6CombinedSelectors_}
421 * @private
422 */
423 goog.debug.DevCss.prototype.addIe6CombinedClassNames_ = function() {
424 if (!this.ie6CombinedMatches_.length) {
425 return;
426 }
427 var allEls = document.getElementsByTagName('*');
428 // Match nodes for all classNames.
429 for (var i = 0, classNameEntry; classNameEntry = this.ie6CombinedMatches_[i];
430 i++) {
431 for (var j = 0, el; el = allEls[j]; j++) {
432 var classNamesLength = classNameEntry.classNames.length;
433 for (var k = 0, className; className = classNameEntry.classNames[k];
434 k++) {
435 if (!goog.dom.classlist.contains(el, className)) {
436 break;
437 }
438 if (k == classNamesLength - 1) {
439 classNameEntry.els.push(el);
440 }
441 }
442 }
443 // Walks over our matching nodes and fixes them.
444 if (classNameEntry.els.length) {
445 for (var j = 0, el; el = classNameEntry.els[j]; j++) {
446 goog.asserts.assert(el);
447 if (!goog.dom.classlist.contains(
448 el, classNameEntry.combinedClassName)) {
449 goog.dom.classlist.add(el, classNameEntry.combinedClassName);
450 }
451 }
452 }
453 }
454 };