-
-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathspecificity.ts
More file actions
279 lines (239 loc) · 8.07 KB
/
Copy pathspecificity.ts
File metadata and controls
279 lines (239 loc) · 8.07 KB
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
// NOTICE
// BELOW IS A COPY OF BRAMUS/SPECIFICTY (MIT) AND CSSO's SPECIFICITY (MIT), TAILORED FOR PORJECT WALLACE'S CSS PARSER
// https://github.com/css/csso/blob/221c9a7145721362ae98ef0313cef4f60dbfa65a/lib/restructure/prepare/specificity.js#L30
// https://github.com/bramus/specificity/blob/80938c4cf77518a4d4abe559eb5a5ff919626c39/src/core/calculate.js
import {
ID_SELECTOR,
ATTRIBUTE_SELECTOR,
CLASS_SELECTOR,
PSEUDO_CLASS_SELECTOR,
PSEUDO_ELEMENT_SELECTOR,
TYPE_SELECTOR,
type CSSNode,
type Selector,
type SelectorNode,
is_selector_list,
is_nth_of_selector,
is_selector,
is_combinator,
} from '@projectwallace/css-parser'
import { parse_selector_list } from '@projectwallace/css-parser/parse-selector'
type Specificity = [number, number, number]
/**
* @returns 0 if s1 equals s2, a negative number if s1 is lower than s2, or a positive number if s1 higher than s2
*/
export function compare(s1: Specificity, s2: Specificity): number {
if (s1[0] === s2[0]) {
if (s1[1] === s2[1]) {
return s1[2] - s2[2]
}
return s1[1] - s2[1]
}
return s1[0] - s2[0]
}
function max(list: Specificity[]): Specificity {
return list.sort(compare).at(-1)!
}
export const calculateForAST = (selectorAST: Selector): Specificity => {
// https://www.w3.org/TR/selectors-4/#specificity-rules
let a = 0 /* ID Selectors */
let b = 0 /* Class selectors, Attributes selectors, and Pseudo-classes */
let c = 0 /* Type selectors and Pseudo-elements */
// Iterate through all parts of the selector (children of NODE_SELECTOR)
let current = selectorAST.first_child
while (current) {
switch (current.type) {
case ID_SELECTOR:
a += 1
break
case ATTRIBUTE_SELECTOR:
case CLASS_SELECTOR:
b += 1
break
case PSEUDO_CLASS_SELECTOR:
switch (current.name.toLowerCase()) {
// "The specificity of a :where() pseudo-class is replaced by zero."
case 'where':
// Noop :)
break
case '-webkit-any':
case 'any':
if (current.first_child) {
b += 1
}
break
// "The specificity of an :is(), :not(), or :has() pseudo-class is replaced by the specificity of the most specific complex selector in its selector list argument."
case '-moz-any':
case 'is':
case 'matches':
case 'not':
case 'has':
if (current.has_children) {
// The first child should be a NODE_SELECTOR_LIST
const childSelectorList = current.first_child
if (childSelectorList && is_selector_list(childSelectorList)) {
// Calculate Specificity for all selectors in the list and get max
const max1 = max(calculate(childSelectorList))
// Adjust orig specificity
a += max1[0]
b += max1[1]
c += max1[2]
}
}
break
// "The specificity of an :nth-child() or :nth-last-child() selector is the specificity of the pseudo class itself (counting as one pseudo-class selector) plus the specificity of the most specific complex selector in its selector list argument"
case 'nth-child':
case 'nth-last-child':
b += 1
// Get NODE_SELECTOR_NTH_OF which contains the "of" selector list
const nthOf = current.first_child
if (nthOf && is_nth_of_selector(nthOf) && nthOf.selector) {
// Use the convenience property to access the selector list directly
const max2 = max(calculate(nthOf.selector))
// Adjust orig specificity
a += max2[0]
b += max2[1]
c += max2[2]
}
break
// "The specificity of :host is that of a pseudo-class. The specificity of :host() is that of a pseudo-class, plus the specificity of its argument."
// "The specificity of :host-context() is that of a pseudo-class, plus the specificity of its argument."
case 'host-context':
case 'host':
b += 1
const selector_list = current.first_child
const childSelector = selector_list?.first_child
if (childSelector && is_selector(childSelector)) {
// Calculate specificity for parts before the first combinator
let childPart = childSelector.first_child
while (childPart) {
if (is_combinator(childPart)) break
// Calculate contribution from this part
const partSpecificity = calculateForAST({
type_name: 'Selector',
first_child: childPart,
has_children: true,
} as Selector)
a += partSpecificity[0] ?? 0
b += partSpecificity[1] ?? 0
c += partSpecificity[2] ?? 0
childPart = childPart.next_sibling as SelectorNode
}
}
break
// Improper use of Pseudo-Class Selectors instead of a Pseudo-Element
// @ref https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-elements#index
case 'after':
case 'before':
case 'first-letter':
case 'first-line':
c += 1
break
default:
b += 1
break
}
break
case PSEUDO_ELEMENT_SELECTOR:
switch (current.name.toLowerCase()) {
// "The specificity of ::slotted() is that of a pseudo-element, plus the specificity of its argument."
case 'slotted':
c += 1
const selector_list = current.first_child
const childSelector = selector_list?.first_child
if (childSelector && is_selector(childSelector)) {
// Calculate specificity for parts before the first combinator
let childPart = childSelector.first_child
while (childPart) {
if (is_combinator(childPart)) break
// Calculate contribution from this part
const partSpecificity = calculateForAST({
type_name: 'Selector',
first_child: childPart,
has_children: true,
} as Selector)
a += partSpecificity[0] ?? 0
b += partSpecificity[1] ?? 0
c += partSpecificity[2] ?? 0
childPart = childPart.next_sibling as SelectorNode
}
}
break
case 'view-transition-group':
case 'view-transition-image-pair':
case 'view-transition-old':
case 'view-transition-new':
// The specificity of a view-transition selector with a * argument is zero.
if (current.first_child?.text === '*') {
break
}
// The specificity of a view-transition selector with an argument is the same
// as for other pseudo - elements, and is equivalent to a type selector.
c += 1
break
default:
c += 1
break
}
break
case TYPE_SELECTOR:
// Omit namespace
let typeSelector = current.name ?? ''
if (typeSelector.includes('|')) {
typeSelector = typeSelector.split('|')[1] ?? ''
}
// "Ignore the universal selector"
if (typeSelector !== '*') {
c += 1
}
break
default:
// NOOP
break
}
current = current.next_sibling as SelectorNode
}
return [a, b, c]
}
const convertToAST = (source: string | CSSNode) => {
// The passed in argument was a String.
// ~> Let's try and parse to an AST
if (typeof source === 'string') {
try {
return parse_selector_list(source)
} catch (e) {
const message = e instanceof Error ? e.message : String(e)
throw new TypeError(
`Could not convert passed in source '${source}' to SelectorList: ${message}`,
)
}
}
// The passed in argument was an Object.
// ~> Let's verify if it's a AST of the type NODE_SELECTOR_LIST
if (source instanceof Object) {
if (is_selector_list(source)) {
return source
}
throw new TypeError(`Passed in source is an Object but no AST / AST of the type SelectorList`)
}
throw new TypeError(
`Passed in source is not a String nor an Object. I don't know what to do with it.`,
)
}
export const calculate = (selector: string | CSSNode): Specificity[] => {
// Quit while you're ahead
if (!selector) {
return []
}
// Make sure we have a SelectorList AST
// If not, an exception will be thrown
const selector_list = convertToAST(selector)
// SelectorList - the ast is always a SelectorList
// Its children are NODE_SELECTOR (type 5) nodes
// ~> Calculate Specificity for each NODE_SELECTOR
const specificities: Specificity[] = []
for (const selector_node of selector_list) {
specificities.push(calculateForAST(selector_node))
}
return specificities
}