-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgetCssSelectorFromAttributesChain.ts
85 lines (66 loc) · 2.41 KB
/
getCssSelectorFromAttributesChain.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
import type {Attributes} from './oldTypes';
/**
* Get CSS selector string from attributes chain.
* This function is convenient to use inside `mapAttributesChain` function.
*/
export const getCssSelectorFromAttributesChain = (
attributesChain: readonly Attributes[],
): string => {
const cssSelectors = attributesChain.map(getCssSelectorFromAttributes).filter(Boolean);
if (cssSelectors.length === 0) {
return '*';
}
return cssSelectors.join(' ');
};
/**
* Get CSS selector string from attributes object.
*/
const getCssSelectorFromAttributes = (attributes: Attributes): string => {
const attributeCssSelectors: string[] = [];
for (const attributeName of Object.keys(attributes)) {
const attributeValue = attributes[attributeName]!;
const cssSelector = getAttributeCssSelector(attributeName, attributeValue);
attributeCssSelectors.push(cssSelector);
}
return attributeCssSelectors.join('');
};
/**
* Get CSS selector string for single attribute.
*/
const getAttributeCssSelector = (attributeName: string, attributeValue: string): string => {
const valueParts = attributeValue.split(starsRegexp);
if (valueParts.length === 1) {
return attributeSelectors.exact(attributeName, attributeValue);
}
const lastPart = valueParts[valueParts.length - 1]!;
const startsWithStar = valueParts[0] === '';
const endsWithStar = lastPart === '';
if (startsWithStar && endsWithStar && valueParts.length === 2) {
return attributeSelectors.any(attributeName);
}
const cssSelectors: string[] = [];
if (!startsWithStar) {
cssSelectors.push(attributeSelectors.startsWith(attributeName, valueParts[0]!));
}
for (let index = 1; index < valueParts.length - 1; index += 1) {
cssSelectors.push(attributeSelectors.contains(attributeName, valueParts[index]!));
}
if (!endsWithStar) {
cssSelectors.push(attributeSelectors.endsWith(attributeName, lastPart));
}
return cssSelectors.join('');
};
/**
* Attribute CSS selectors by attribute value inclusion type.
*/
const attributeSelectors = {
any: (name: string) => `[${name}]`,
contains: (name: string, value: string) => `[${name}*="${value}"]`,
endsWith: (name: string, value: string) => `[${name}$="${value}"]`,
exact: (name: string, value: string) => `[${name}="${value}"]`,
startsWith: (name: string, value: string) => `[${name}^="${value}"]`,
};
/**
* Regexp to split a string by stars.
*/
const starsRegexp = /\*+/;