Debian Codegraph @

closure-library/closure/goog/html/cssspecificity.js

raw
1 // Copyright 2016 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 /** @fileoverview Calculator for specificity of CSS selectors. */
16
17 goog.module('goog.html.CssSpecificity');
18 goog.module.declareLegacyNamespace();
19
20 var userAgent = goog.require('goog.userAgent');
21 var userAgentProduct = goog.require('goog.userAgent.product');
22
23
24 /**
25 * Cached mapping from selectors to specificities.
26 * @type {!Object<string, !Array<number>>}
27 */
28 var specificityCache = {};
29
30 /**
31 * Calculates the specificity of CSS selectors, using a global cache if
32 * supported.
33 * @see http://www.w3.org/TR/css3-selectors/#specificity
34 * @see https://specificity.keegan.st/
35 * @param {string} selector The CSS selector.
36 * @return {!Array<number>} The CSS specificity.
37 * @supported IE9+, other browsers.
38 */
39 function getSpecificity(selector) {
40 if (userAgentProduct.IE && !userAgent.isVersionOrHigher(9)) {
41 // IE8 has buggy regex support.
42 return [0, 0, 0, 0];
43 }
44 var specificity = specificityCache.hasOwnProperty(selector) ?
45 specificityCache[selector] :
46 null;
47 if (specificity) {
48 return specificity;
49 }
50 if (Object.keys(specificityCache).length > (1 << 16)) {
51 // Limit the size of cache to (1 << 16) == 65536. Normally HTML pages don't
52 // have such numbers of selectors.
53 specificityCache = {};
54 }
55 specificity = calculateSpecificity(selector);
56 specificityCache[selector] = specificity;
57 return specificity;
58 }
59
60 /**
61 * Find matches for a regular expression in the selector and increase count.
62 * @param {string} selector The selector to match the regex with.
63 * @param {!Array<number>} specificity The current specificity.
64 * @param {!RegExp} regex The regular expression.
65 * @param {number} typeIndex Index of type count.
66 * @return {string}
67 */
68 function replaceWithEmptyText(selector, specificity, regex, typeIndex) {
69 return selector.replace(regex, function(match) {
70 specificity[typeIndex] += 1;
71 // Replace this simple selector with whitespace so it won't be counted
72 // in further simple selectors.
73 return Array(match.length + 1).join(' ');
74 });
75 }
76
77 /**
78 * Replace escaped characters with plain text, using the "A" character.
79 * @see https://www.w3.org/TR/CSS21/syndata.html#characters
80 * @param {string} selector
81 * @param {!RegExp} regex
82 * @return {string}
83 */
84 function replaceWithPlainText(selector, regex) {
85 return selector.replace(regex, function(match) {
86 return Array(match.length + 1).join('A');
87 });
88 }
89
90 /**
91 * Calculates the specificity of CSS selectors
92 * @see http://www.w3.org/TR/css3-selectors/#specificity
93 * @see https://github.com/keeganstreet/specificity
94 * @see https://specificity.keegan.st/
95 * @param {string} selector
96 * @return {!Array<number>} The CSS specificity.
97 */
98 function calculateSpecificity(selector) {
99 var specificity = [0, 0, 0, 0];
100
101 // Cannot use RegExp literals for all regular expressions, IE does not accept
102 // the syntax.
103
104 // Matches a backslash followed by six hexadecimal digits followed by an
105 // optional single whitespace character.
106 var escapeHexadecimalRegex = new RegExp('\\\\[0-9A-Fa-f]{6}\\s?', 'g');
107 // Matches a backslash followed by fewer than six hexadecimal digits
108 // followed by a mandatory single whitespace character.
109 var escapeHexadecimalRegex2 = new RegExp('\\\\[0-9A-Fa-f]{1,5}\\s', 'g');
110 // Matches a backslash followed by any character
111 var escapeSpecialCharacter = /\\./g;
112 selector = replaceWithPlainText(selector, escapeHexadecimalRegex);
113 selector = replaceWithPlainText(selector, escapeHexadecimalRegex2);
114 selector = replaceWithPlainText(selector, escapeSpecialCharacter);
115
116 // Remove the negation pseudo-class (:not) but leave its argument because
117 // specificity is calculated on its argument.
118 var pseudoClassWithNotRegex = new RegExp(':not\\(([^\\)]*)\\)', 'g');
119 selector = selector.replace(pseudoClassWithNotRegex, ' $1 ');
120
121 // Remove anything after a left brace in case a user has pasted in a rule,
122 // not just a selector.
123 var rulesRegex = new RegExp('{[^]*', 'gm');
124 selector = selector.replace(rulesRegex, '');
125
126 // The following regular expressions assume that selectors matching the
127 // preceding regular expressions have been removed.
128
129 // SPECIFICITY 2: Counts attribute selectors.
130 var attributeRegex = new RegExp('(\\[[^\\]]+\\])', 'g');
131 selector = replaceWithEmptyText(selector, specificity, attributeRegex, 2);
132
133 // SPECIFICITY 1: Counts ID selectors.
134 var idRegex = new RegExp('(#[^\\#\\s\\+>~\\.\\[:]+)', 'g');
135 selector = replaceWithEmptyText(selector, specificity, idRegex, 1);
136
137 // SPECIFICITY 2: Counts class selectors.
138 var classRegex = new RegExp('(\\.[^\\s\\+>~\\.\\[:]+)', 'g');
139 selector = replaceWithEmptyText(selector, specificity, classRegex, 2);
140
141 // SPECIFICITY 3: Counts pseudo-element selectors.
142 var pseudoElementRegex =
143 /(::[^\s\+>~\.\[:]+|:first-line|:first-letter|:before|:after)/gi;
144 selector = replaceWithEmptyText(selector, specificity, pseudoElementRegex, 3);
145
146 // SPECIFICITY 2: Counts pseudo-class selectors.
147 // A regex for pseudo classes with brackets. For example:
148 // :nth-child()
149 // :nth-last-child()
150 // :nth-of-type()
151 // :nth-last-type()
152 // :lang()
153 var pseudoClassWithBracketsRegex = /(:[\w-]+\([^\)]*\))/gi;
154 selector = replaceWithEmptyText(
155 selector, specificity, pseudoClassWithBracketsRegex, 2);
156 // A regex for other pseudo classes, which don't have brackets.
157 var pseudoClassRegex = /(:[^\s\+>~\.\[:]+)/g;
158 selector = replaceWithEmptyText(selector, specificity, pseudoClassRegex, 2);
159
160 // Remove universal selector and separator characters.
161 selector = selector.replace(/[\*\s\+>~]/g, ' ');
162
163 // Remove any stray dots or hashes which aren't attached to words.
164 // These may be present if the user is live-editing this selector.
165 selector = selector.replace(/[#\.]/g, ' ');
166
167 // SPECIFICITY 3: The only things left should be element selectors.
168 var elementRegex = /([^\s\+>~\.\[:]+)/g;
169 selector = replaceWithEmptyText(selector, specificity, elementRegex, 3);
170
171 return specificity;
172 }
173
174 exports = {
175 getSpecificity: getSpecificity
176 };