forked from LeaVerou/parsel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparsel.js
335 lines (273 loc) · 8.72 KB
/
parsel.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
const TOKENS = {
attribute: /\[\s*(?:(?<namespace>\*|[-\w]*)\|)?(?<name>[-\w\u{0080}-\u{FFFF}]+)\s*(?:(?<operator>\W?=)\s*(?<value>.+?)\s*(?<i>i)?\s*)?\]/gu,
id: /#(?<name>(?:[-\w\u{0080}-\u{FFFF}]|\\.)+)/gu,
class: /\.(?<name>(?:[-\w\u{0080}-\u{FFFF}]|\\.)+)/gu,
comma: /\s*,\s*/g, // must be before combinator
combinator: /\s*[\s>+~]\s*/g, // this must be after attribute
"pseudo-element": /::(?<name>[-\w\u{0080}-\u{FFFF}]+)(?:\((?<argument>¶+)\))?/gu, // this must be before pseudo-class
"pseudo-class": /:(?<name>[-\w\u{0080}-\u{FFFF}]+)(?:\((?<argument>¶+)\))?/gu,
type: /(?:(?<namespace>\*|[-\w]*)\|)?(?<name>[-\w\u{0080}-\u{FFFF}]+)|\*/gu // this must be last
};
const TOKENS_WITH_PARENS = new Set(["pseudo-class", "pseudo-element"]);
const TOKENS_WITH_STRINGS = new Set([...TOKENS_WITH_PARENS, "attribute"]);
const TRIM_TOKENS = new Set(["combinator", "comma"]);
const RECURSIVE_PSEUDO_CLASSES = new Set(["not", "is", "where", "has", "matches", "-moz-any", "-webkit-any"]);
const TOKENS_FOR_RESTORE = Object.assign({}, TOKENS);
TOKENS_FOR_RESTORE["pseudo-element"] = RegExp(TOKENS["pseudo-element"].source.replace("(?<argument>¶+)", "(?<argument>.+?)"), "gu")
TOKENS_FOR_RESTORE["pseudo-class"] = RegExp(TOKENS["pseudo-class"].source.replace("(?<argument>¶+)", "(?<argument>.+)"), "gu")
export function gobbleParens(text, i) {
let str = "", stack = [];
for (; i < text.length; i++) {
let char = text[i];
if (char === "(") {
stack.push(char);
}
else if (char === ")") {
if (stack.length > 0) {
stack.pop();
}
else {
throw new Error("Closing paren without opening paren at " + i);
}
}
str += char;
if (stack.length === 0) {
return str;
}
}
throw new Error("Opening paren without closing paren");
}
export function tokenizeBy (text, grammar) {
if (!text) {
return [];
}
var strarr = [text];
tokenloop: for (var token in grammar) {
let pattern = grammar[token];
for (var i=0; i < strarr.length; i++) { // Don’t cache length as it changes during the loop
var str = strarr[i];
if (typeof str === "string") {
pattern.lastIndex = 0;
var match = pattern.exec(str);
if (match) {
let from = match.index - 1;
let args = [];
let content = match[0];
let before = str.slice(0, from + 1);
if (before) {
args.push(before);
}
args.push({
type: token,
content,
...match.groups
});
let after = str.slice(from + content.length + 1);
if (after) {
args.push(after);
}
strarr.splice(i, 1, ...args);
}
}
}
}
let offset = 0;
for (let i=0; i<strarr.length; i++) {
let token = strarr[i];
let length = token.length || token.content.length;
if (typeof token === "object") {
token.pos = [offset, offset + length];
if (TRIM_TOKENS.has(token.type)) {
token.content = token.content.trim() || " ";
}
}
offset += length;
}
return strarr;
}
export function tokenize (selector) {
if (!selector) {
return null;
}
selector = selector.trim(); // prevent leading/trailing whitespace be interpreted as combinators
// Replace strings with whitespace strings (to preserve offsets)
let strings = [];
// FIXME Does not account for escaped backslashes before a quote
selector = selector.replace(/(['"])(\\\1|.)+?\1/g, (str, quote, content, start) => {
strings.push({str, start});
return quote + "§".repeat(content.length) + quote;
});
// Now that strings are out of the way, extract parens and replace them with parens with whitespace (to preserve offsets)
let parens = [], offset = 0, start;
while ((start = selector.indexOf("(", offset)) > -1) {
let str = gobbleParens(selector, start);
parens.push({str, start});
selector = selector.substring(0, start) + "(" + "¶".repeat(str.length - 2) + ")" + selector.substring(start + str.length);
offset = start + str.length;
}
// Now we have no nested structures and we can parse with regexes
let tokens = tokenizeBy(selector, TOKENS);
// Now restore parens and strings in reverse order
function restoreNested(strings, regex, types) {
for (let str of strings) {
for (let token of tokens) {
if (types.has(token.type) && token.pos[0] < str.start && str.start < token.pos[1]) {
let content = token.content;
token.content = token.content.replace(regex, str.str);
if (token.content !== content) { // actually changed?
// Re-evaluate groups
TOKENS_FOR_RESTORE[token.type].lastIndex = 0;
let match = TOKENS_FOR_RESTORE[token.type].exec(token.content);
let groups = match.groups;
Object.assign(token, groups);
}
}
}
}
}
restoreNested(parens, /\(¶+\)/, TOKENS_WITH_PARENS);
restoreNested(strings, /(['"])§+?\1/, TOKENS_WITH_STRINGS);
return tokens;
}
// Convert a flat list of tokens into a tree of complex & compound selectors
export function nestTokens(tokens, {list = true} = {}) {
if (list && tokens.find(t => t.type === "comma")) {
let selectors = [], temp = [];
for (let i=0; i<tokens.length; i++) {
if (tokens[i].type === "comma") {
if (temp.length === 0) {
throw new Error("Incorrect comma at " + i);
}
selectors.push(nestTokens(temp, {list: false}));
temp.length = 0;
}
else {
temp.push(tokens[i]);
}
}
if (temp.length === 0) {
throw new Error("Trailing comma");
}
else {
selectors.push(nestTokens(temp, {list: false}));
}
return { type: "list", list: selectors };
}
for (let i=tokens.length - 1; i>=0; i--) {
let token = tokens[i];
if (token.type === "combinator") {
let left = tokens.slice(0, i);
let right = tokens.slice(i + 1);
if (left.length === 0 || right.length === 0) {
throw new Error(`Combinator ${token.content} used in selector ${left.length === 0? "start" : "end"}`);
}
return {
type: "complex",
combinator: token.content,
left: nestTokens(left),
right: nestTokens(right)
};
}
}
// If we're here, there are no combinators, so it's just a list
return tokens.length === 1? tokens[0] : {
type: "compound",
list: [...tokens] // clone to avoid pointers messing up the AST
};
}
// Traverse an AST (or part thereof), in depth-first order
export function walk(node, callback, o, parent) {
if (node.type === "complex") {
walk(node.left, callback, o, node);
walk(node.right, callback, o, node);
}
else if (node.type === "compound") {
for (let n of node.list) {
walk(n, callback, o, node);
}
}
else if (node.subtree && o && o.subtree) {
walk(node.subtree, callback, o, node);
}
callback(node, parent);
}
/**
* Parse a CSS selector
* @param selector {String} The selector to parse
* @param options.recursive {Boolean} Whether to parse the arguments of pseudo-classes like :is(), :has() etc. Defaults to true.
* @param options.list {Boolean} Whether this can be a selector list (A, B, C etc). Defaults to true.
*/
export function parse(selector, {recursive = true, list = true} = {}) {
let tokens = tokenize(selector);
if (!tokens) {
return null;
}
let ast = nestTokens(tokens, {list});
if (recursive) {
walk(ast, node => {
if (node.type === "pseudo-class" && node.argument && RECURSIVE_PSEUDO_CLASSES.has(node.name)) {
node.subtree = parse(node.argument, {recursive: true, list: true});
}
});
}
return ast;
}
export function specificityToNumber(specificity, base) {
base = base || Math.max(...specificity) + 1;
return specificity[0] * base ** 2 + specificity[1] * base + specificity[0];
}
function maxIndexOf(arr) {
let max = arr[0], ret = 0;
for (let i=0; i<arr.length; i++) {
if (arr[i] > max) {
ret = i;
max = arr[i];
}
}
return arr.length === 0? -1 : ret;
}
/**
* Calculate specificity of a selector.
* If the selector is a list, the max specificity is returned.
*/
export function specificity(selector, {format = "array"} = {}) {
let ast = typeof selector === "object"? selector : parse(selector, {recursive: true});
if (!ast) {
return null;
}
if (ast.type === "list") {
// Return max specificity
let base = 10;
let specificities = ast.list.map(s => {
let sp = specificity(s);
base = Math.max(base, ...sp);
return sp;
});
let numbers = specificities.map(s => specificityToNumber(s, base));
let i = maxIndexOf(numbers);
return specificities[i];
}
let ret = [0, 0, 0];
walk(ast, node => {
if (node.type === "id") {
ret[0]++;
}
else if (node.type === "class" || node.type === "attribute") {
ret[1]++;
}
else if ((node.type === "type" && node.content !== "*") || node.type === "pseudo-element") {
ret[2]++;
}
else if (node.type === "pseudo-class" && node.name !== "where") {
if (RECURSIVE_PSEUDO_CLASSES.has(node.name) && node.subtree) {
// Max of argument list
let sub = specificity(node.subtree);
sub.forEach((s, i) => ret[i] += s);
}
else {
ret[1]++;
}
}
});
return ret;
}