forked from capricorn86/happy-dom
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SelectorItem.ts
382 lines (338 loc) · 10.3 KB
/
SelectorItem.ts
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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
import DOMException from '../exception/DOMException';
import IElement from '../nodes/element/IElement';
import Element from '../nodes/element/Element';
import CSSEscape from 'css.escape';
const ATTRIBUTE_REGEXP =
/\[([a-zA-Z0-9-_]+)\]|\[([a-zA-Z0-9-_]+)([~|^$*]{0,1})[ ]*=[ ]*["']{0,1}([^"']+)["']{0,1}\]/g;
const ATTRIBUTE_NAME_REGEXP = /[^a-zA-Z0-9-_$]/;
const PSUEDO_REGEXP =
/(?<!\\):([a-zA-Z-]+)\(([0-9n+-]+|odd|even)\)|(?<!\\):not\(([^)]+)\)|(?<!\\):([a-zA-Z-]+)/g;
const CLASS_REGEXP = /\.([a-zA-Z0-9-_$]+)/g;
const TAG_NAME_REGEXP = /^[a-zA-Z0-9-]+/;
const ID_REGEXP = /#[A-Za-z][-A-Za-z0-9_]*/g;
/**
* Selector item.
*/
export default class SelectorItem {
private isAll: boolean;
private isID: boolean;
private isAttribute: boolean;
private isPseudo: boolean;
private isClass: boolean;
private isTagName: boolean;
private tagName = null;
private selector: string;
private id: string;
/**
* Constructor.
*
* @param selector Selector.
*/
constructor(selector: string) {
const baseSelector = selector.replace(new RegExp(PSUEDO_REGEXP, 'g'), '');
this.isAll = baseSelector === '*';
this.isID = !this.isAll ? selector.indexOf('#') !== -1 : false;
this.isAttribute = !this.isAll && baseSelector.includes('[');
// If baseSelector !== selector then some psuedo selector was replaced above
this.isPseudo = !this.isAll && baseSelector !== selector;
this.isClass = !this.isAll && new RegExp(CLASS_REGEXP, 'g').test(baseSelector);
this.tagName = !this.isAll ? baseSelector.match(TAG_NAME_REGEXP) : null;
this.tagName = this.tagName ? this.tagName[0].toUpperCase() : null;
this.isTagName = this.tagName !== null;
this.selector = selector;
this.id = null;
if (!this.isAll && this.isID) {
const idMatches = baseSelector.match(ID_REGEXP);
if (idMatches) {
this.id = idMatches[0].replace('#', '');
}
}
}
/**
* Matches a selector against an element.
*
* @param element HTML element.
* @returns Result.
*/
public match(element: IElement): { priorityWeight: number; matches: boolean } {
const selector = this.selector;
let priorityWeight = 0;
// Is all (*)
if (this.isAll) {
return { priorityWeight: 0, matches: true };
}
// ID Match
if (this.isID) {
priorityWeight += 100;
if (this.id !== element.id) {
return { priorityWeight: 0, matches: false };
}
}
// Tag name match
if (this.isTagName) {
priorityWeight += 1;
if (this.tagName !== element.tagName) {
return { priorityWeight: 0, matches: false };
}
}
// Class match
if (this.isClass) {
const result = this.matchesClass(element, selector);
priorityWeight += result.priorityWeight;
if (!result.matches) {
return { priorityWeight: 0, matches: false };
}
}
// Pseudo match
if (this.isPseudo && !this.matchesPsuedo(element, selector)) {
return { priorityWeight: 0, matches: false };
}
// Attribute match
if (this.isAttribute) {
const result = this.matchesAttribute(element, selector);
priorityWeight += result.priorityWeight;
if (!result.matches) {
return { priorityWeight: 0, matches: false };
}
}
return { priorityWeight, matches: true };
}
/**
* Matches a psuedo selector.
*
* @param element Element.
* @param selector Selector.
* @returns True if it is a match.
*/
private matchesPsuedo(element: IElement, selector: string): boolean {
const regexp = new RegExp(PSUEDO_REGEXP, 'g');
let match: RegExpMatchArray;
while ((match = regexp.exec(selector))) {
const isNotClass = match[3] && match[3].trim()[0] === '.';
if (match[1] && !this.matchesNthChild(element, match[1], match[2])) {
return false;
} else if (
match[3] &&
((isNotClass && this.matchesClass(element, match[3]).matches) ||
(!isNotClass && this.matchesAttribute(element, match[3])).matches)
) {
return false;
} else if (match[4] && !this.matchesPsuedoExpression(element, match[4])) {
return false;
}
}
return true;
}
/**
* Matches a nth-child selector.
*
* @param element Element.
* @param psuedo Psuedo name.
* @param place Place.
* @returns True if it is a match.
*/
private matchesNthChild(element: IElement, psuedo: string, place: string): boolean {
let children = element.parentNode ? (<IElement>element.parentNode).children : [];
switch (psuedo.toLowerCase()) {
case 'nth-of-type':
children = children.filter((child) => child.tagName === element.tagName);
break;
case 'nth-last-child':
children = children.reverse();
break;
case 'nth-last-of-type':
children = children.filter((child) => child.tagName === element.tagName).reverse();
break;
}
if (place === 'odd') {
const index = children.indexOf(element);
return index !== -1 && (index + 1) % 2 !== 0;
} else if (place === 'even') {
const index = children.indexOf(element);
return index !== -1 && (index + 1) % 2 === 0;
} else if (place.includes('n')) {
const [a, b] = place.replace(/ /g, '').split('n');
const childIndex = children.indexOf(element);
const aNumber = Number(a);
const bNumber = b !== undefined ? Number(b) : 0;
if (isNaN(aNumber) || isNaN(bNumber)) {
throw new DOMException(`The selector "${this.selector}" is not valid.`);
}
for (let i = 0, max = children.length; i <= max; i += aNumber) {
if (childIndex === i + bNumber - 1) {
return true;
}
}
return false;
}
const number = Number(place);
if (isNaN(number)) {
throw new DOMException(`The selector "${this.selector}" is not valid.`);
}
return children[number - 1] === element;
}
/**
* Matches a psuedo selector expression.
*
* @param element Element.
* @param psuedo Psuedo name.
* @returns True if it is a match.
*/
private matchesPsuedoExpression(element: IElement, psuedo: string): boolean {
const parent = <IElement>element.parentNode;
if (!parent) {
return false;
}
switch (psuedo.toLowerCase()) {
case 'first-child':
return parent.children[0] === element;
case 'last-child':
const lastChildChildren = parent.children;
return lastChildChildren[lastChildChildren.length - 1] === element;
case 'only-child':
const onlyChildChildren = parent.children;
return onlyChildChildren.length === 1 && onlyChildChildren[0] === element;
case 'first-of-type':
for (const child of parent.children) {
if (child.tagName === element.tagName) {
return child === element;
}
}
return false;
case 'last-of-type':
for (let i = parent.children.length - 1; i >= 0; i--) {
const child = parent.children[i];
if (child.tagName === element.tagName) {
return child === element;
}
}
return false;
case 'only-of-type':
let isFound = false;
for (const child of parent.children) {
if (child.tagName === element.tagName) {
if (isFound || child !== element) {
return false;
}
isFound = true;
}
}
return isFound;
}
return false;
}
/**
* Matches attribute.
*
* @param element Element.
* @param selector Selector.
* @returns Result.
*/
private matchesAttribute(
element: IElement,
selector: string
): { priorityWeight: number; matches: boolean } {
const regexp = new RegExp(ATTRIBUTE_REGEXP, 'g');
let match: RegExpMatchArray;
let priorityWeight = 0;
while ((match = regexp.exec(selector))) {
const isPsuedo = match.index > 0 && selector[match.index - 1] === '(';
priorityWeight += 10;
if (
!isPsuedo &&
((match[1] && !this.matchesAttributeName(element, match[1])) ||
(match[2] && !this.matchesAttributeNameAndValue(element, match[2], match[4], match[3])))
) {
return { priorityWeight: 0, matches: false };
}
}
return { priorityWeight, matches: true };
}
/**
* Matches class.
*
* @param element Element.
* @param selector Selector.
* @returns Result.
*/
private matchesClass(
element: IElement,
selector: string
): { priorityWeight: number; matches: boolean } {
const classList = element.className.split(' ').map(CSSEscape);
const classSelector = selector.replace(new RegExp(PSUEDO_REGEXP, 'g'), '');
let priorityWeight = 0;
if (classSelector.startsWith('.')) {
priorityWeight += 10;
if (!classList.includes(classSelector.slice(1))) {
return { priorityWeight: 0, matches: false };
}
}
return { priorityWeight, matches: true };
}
/**
* Matches attribute name only.
*
* @param element Element.
* @param attributeName Attribute name.
* @returns True if it is a match.
*/
private matchesAttributeName(element: IElement, attributeName: string): boolean {
if (ATTRIBUTE_NAME_REGEXP.test(attributeName)) {
throw new DOMException(`The selector "${this.selector}" is not valid.`);
}
return !!(<Element>element)._attributes[attributeName.toLowerCase()];
}
/** .
*
* Matches attribute name and value.
*
* @param element Element.
* @param attributeName Attribute name.
* @param attributeValue Attribute value.
* @param [matchType] Match type.
* @returns True if it is a match.
*/
/**
*
* @param element
* @param attributeName
* @param attributeValue
* @param matchType
*/
private matchesAttributeNameAndValue(
element: IElement,
attributeName: string,
attributeValue: string,
matchType: string = null
): boolean {
const attribute = (<Element>element)._attributes[attributeName.toLowerCase()];
const value = attributeValue;
if (ATTRIBUTE_NAME_REGEXP.test(attributeName)) {
throw new DOMException(`The selector "${this.selector}" is not valid.`);
}
if (!attribute) {
return false;
}
if (matchType) {
switch (matchType) {
// [attribute~="value"] - Contains a specified word.
case '~':
return attribute.value && attribute.value.split(' ').includes(value);
// [attribute|="value"] - Starts with the specified word.
case '|':
return attribute && attribute.value && new RegExp(`^${value}[- ]`).test(attribute.value);
// [attribute^="value"] - Begins with a specified value.
case '^':
return attribute && attribute.value && attribute.value.startsWith(value);
// [attribute$="value"] - Ends with a specified value.
case '$':
return attribute && attribute.value && attribute.value.endsWith(value);
// [attribute*="value"] - Contains a specified value.
case '*':
return attribute && attribute.value && attribute.value.includes(value);
}
}
return attribute && attribute.value === value;
}
}