Debian Codegraph @

packages/domutils/src/selector.ts

raw
1 // Copyright (c) Jupyter Development Team.
2 // Distributed under the terms of the Modified BSD License.
3 /*-----------------------------------------------------------------------------
4 | Copyright (c) 2014-2017, PhosphorJS Contributors
5 |
6 | Distributed under the terms of the BSD 3-Clause License.
7 |
8 | The full license is in the file LICENSE, distributed with this software.
9 |----------------------------------------------------------------------------*/
10
11 /**
12 * The namespace for selector related utilities.
13 */
14 export namespace Selector {
15 /**
16 * Calculate the specificity of a single CSS selector.
17 *
18 * @param selector - The CSS selector of interest.
19 *
20 * @returns The specificity of the selector.
21 *
22 * #### Undefined Behavior
23 * The selector is invalid.
24 *
25 * #### Notes
26 * This is based on https://www.w3.org/TR/css3-selectors/#specificity
27 *
28 * A larger number represents a more specific selector.
29 *
30 * The smallest possible specificity is `0`.
31 *
32 * The result is represented as a hex number `0x<aa><bb><cc>` where
33 * each component is the count of the respective selector clause.
34 *
35 * If the selector contains commas, only the first clause is used.
36 *
37 * The computed result is cached, so subsequent calculations for the
38 * same selector are extremely fast.
39 */
40 export function calculateSpecificity(selector: string): number {
41 if (selector in Private.specificityCache) {
42 return Private.specificityCache[selector];
43 }
44 let result = Private.calculateSingle(selector);
45 return (Private.specificityCache[selector] = result);
46 }
47
48 /**
49 * Test whether a selector is a valid CSS selector.
50 *
51 * @param selector - The CSS selector of interest.
52 *
53 * @returns `true` if the selector is valid, `false` otherwise.
54 *
55 * #### Notes
56 * The computed result is cached, so subsequent tests for the same
57 * selector are extremely fast.
58 */
59 export function isValid(selector: string): boolean {
60 if (selector in Private.validityCache) {
61 return Private.validityCache[selector];
62 }
63 let result = true;
64 try {
65 Private.testElem.querySelector(selector);
66 } catch (err) {
67 result = false;
68 }
69 return (Private.validityCache[selector] = result);
70 }
71
72 /**
73 * Test whether an element matches a CSS selector.
74 *
75 * @param element - The element of interest.
76 *
77 * @param selector - The valid CSS selector of interest.
78 *
79 * @returns `true` if the element is a match, `false` otherwise.
80 *
81 * #### Notes
82 * This function uses the builtin browser capabilities when possible,
83 * falling back onto a document query otherwise.
84 */
85 export function matches(element: Element, selector: string): boolean {
86 return Private.protoMatchFunc.call(element, selector);
87 }
88 }
89
90 /**
91 * The namespace for the module implementation details.
92 */
93 namespace Private {
94 /**
95 * A type alias for an object hash.
96 */
97 export type StringMap<T> = { [key: string]: T };
98
99 /**
100 * A cache of computed selector specificity values.
101 */
102 export const specificityCache: StringMap<number> = Object.create(null);
103
104 /**
105 * A cache of computed selector validity.
106 */
107 export const validityCache: StringMap<boolean> = Object.create(null);
108
109 /**
110 * An empty element for testing selector validity.
111 */
112 export const testElem = document.createElement('div');
113
114 /**
115 * A cross-browser CSS selector matching prototype function.
116 */
117 export const protoMatchFunc = (() => {
118 let proto = Element.prototype as any;
119 return (
120 proto.matches ||
121 proto.matchesSelector ||
122 proto.mozMatchesSelector ||
123 proto.msMatchesSelector ||
124 proto.oMatchesSelector ||
125 proto.webkitMatchesSelector ||
126 function (selector: string) {
127 let elem = this as Element;
128 let matches = elem.ownerDocument
129 ? elem.ownerDocument.querySelectorAll(selector)
130 : [];
131 return Array.prototype.indexOf.call(matches, elem) !== -1;
132 }
133 );
134 })();
135
136 /**
137 * Calculate the specificity of a single selector.
138 *
139 * The behavior is undefined if the selector is invalid.
140 */
141 export function calculateSingle(selector: string): number {
142 // Ignore anything after the first comma.
143 selector = selector.split(',', 1)[0];
144
145 // Setup the aggregate counters.
146 let a = 0;
147 let b = 0;
148 let c = 0;
149
150 // Apply a regex to the front of the selector. If it succeeds, that
151 // portion of the selector is removed. Returns a success/fail flag.
152 function match(re: RegExp): boolean {
153 let match = selector.match(re);
154 if (match === null) {
155 return false;
156 }
157 selector = selector.slice(match[0].length);
158 return true;
159 }
160
161 // Replace the negation pseudo-class (which is ignored),
162 // but keep its inner content (which is not ignored).
163 selector = selector.replace(NEGATION_RE, ' $1 ');
164
165 // Continue matching until the selector is consumed.
166 while (selector.length > 0) {
167 // Match an ID selector.
168 if (match(ID_RE)) {
169 a++;
170 continue;
171 }
172
173 // Match a class selector.
174 if (match(CLASS_RE)) {
175 b++;
176 continue;
177 }
178
179 // Match an attribute selector.
180 if (match(ATTR_RE)) {
181 b++;
182 continue;
183 }
184
185 // Match a pseudo-element selector. This is done before matching
186 // a pseudo-class since this regex overlaps with that regex.
187 if (match(PSEUDO_ELEM_RE)) {
188 c++;
189 continue;
190 }
191
192 // Match a pseudo-class selector.
193 if (match(PSEDUO_CLASS_RE)) {
194 b++;
195 continue;
196 }
197
198 // Match a plain type selector.
199 if (match(TYPE_RE)) {
200 c++;
201 continue;
202 }
203
204 // Finally, match any ignored characters.
205 if (match(IGNORE_RE)) {
206 continue;
207 }
208
209 // At this point, the selector is assumed to be invalid.
210 return 0;
211 }
212
213 // Clamp each component to a reasonable base.
214 a = Math.min(a, 0xff);
215 b = Math.min(b, 0xff);
216 c = Math.min(c, 0xff);
217
218 // Combine the components into a single result.
219 return (a << 16) | (b << 8) | c;
220 }
221
222 /**
223 * A regex which matches an ID selector at string start.
224 */
225 const ID_RE = /^#[^\s\+>~#\.\[:]+/;
226
227 /**
228 * A regex which matches a class selector at string start.
229 */
230 const CLASS_RE = /^\.[^\s\+>~#\.\[:]+/;
231
232 /**
233 * A regex which matches an attribute selector at string start.
234 */
235 const ATTR_RE = /^\[[^\]]+\]/;
236
237 /**
238 * A regex which matches a type selector at string start.
239 */
240 const TYPE_RE = /^[^\s\+>~#\.\[:]+/;
241
242 /**
243 * A regex which matches a pseudo-element selector at string start.
244 */
245 const PSEUDO_ELEM_RE =
246 /^(::[^\s\+>~#\.\[:]+|:first-line|:first-letter|:before|:after)/;
247
248 /**
249 * A regex which matches a pseudo-class selector at string start.
250 */
251 const PSEDUO_CLASS_RE = /^:[^\s\+>~#\.\[:]+/;
252
253 /**
254 * A regex which matches ignored characters at string start.
255 */
256 const IGNORE_RE = /^[\s\+>~\*]+/;
257
258 /**
259 * A regex which matches the negation pseudo-class globally.
260 */
261 const NEGATION_RE = /:not\(([^\)]+)\)/g;
262 }