-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
css_nesting.go
490 lines (442 loc) · 17.4 KB
/
css_nesting.go
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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
package css_parser
import (
"fmt"
"github.com/evanw/esbuild/internal/ast"
"github.com/evanw/esbuild/internal/compat"
"github.com/evanw/esbuild/internal/css_ast"
"github.com/evanw/esbuild/internal/logger"
)
func (p *parser) lowerNestingInRule(rule css_ast.Rule, results []css_ast.Rule) []css_ast.Rule {
switch r := rule.Data.(type) {
case *css_ast.RSelector:
scope := func(loc logger.Loc) css_ast.ComplexSelector {
return css_ast.ComplexSelector{
Selectors: []css_ast.CompoundSelector{{
SubclassSelectors: []css_ast.SubclassSelector{{
Range: logger.Range{Loc: loc},
Data: &css_ast.SSPseudoClass{Name: "scope"},
}},
}},
}
}
parentSelectors := make([]css_ast.ComplexSelector, 0, len(r.Selectors))
for i, sel := range r.Selectors {
// Top-level "&" should be replaced with ":scope" to avoid recursion.
// From https://www.w3.org/TR/css-nesting-1/#nest-selector:
//
// "When used in the selector of a nested style rule, the nesting
// selector represents the elements matched by the parent rule. When
// used in any other context, it represents the same elements as
// :scope in that context (unless otherwise defined)."
//
substituted := make([]css_ast.CompoundSelector, 0, len(sel.Selectors))
for _, x := range sel.Selectors {
substituted = p.substituteAmpersandsInCompoundSelector(x, scope, substituted, keepLeadingCombinator)
}
r.Selectors[i] = css_ast.ComplexSelector{Selectors: substituted}
// Filter out pseudo elements because they are ignored by nested style
// rules. This is because pseudo-elements are not valid within :is():
// https://www.w3.org/TR/selectors-4/#matches-pseudo. This restriction
// may be relaxed in the future, but this restriction hash shipped so
// we're stuck with it: https://github.com/w3c/csswg-drafts/issues/7433.
//
// Note: This is only for the parent selector list that is used to
// substitute "&" within child rules. Do not filter out the pseudo
// element from the top-level selector list.
if !sel.UsesPseudoElement() {
parentSelectors = append(parentSelectors, css_ast.ComplexSelector{Selectors: substituted})
}
}
// Emit this selector before its nested children
start := len(results)
results = append(results, rule)
// Lower all children and filter out ones that become empty
context := lowerNestingContext{
parentSelectors: parentSelectors,
loweredRules: results,
}
r.Rules = p.lowerNestingInRulesAndReturnRemaining(r.Rules, &context)
// Omit this selector entirely if it's now empty
if len(r.Rules) == 0 {
copy(context.loweredRules[start:], context.loweredRules[start+1:])
context.loweredRules = context.loweredRules[:len(context.loweredRules)-1]
}
return context.loweredRules
case *css_ast.RKnownAt:
var rules []css_ast.Rule
for _, child := range r.Rules {
rules = p.lowerNestingInRule(child, rules)
}
r.Rules = rules
case *css_ast.RAtLayer:
var rules []css_ast.Rule
for _, child := range r.Rules {
rules = p.lowerNestingInRule(child, rules)
}
r.Rules = rules
}
return append(results, rule)
}
// Lower all children and filter out ones that become empty
func (p *parser) lowerNestingInRulesAndReturnRemaining(rules []css_ast.Rule, context *lowerNestingContext) []css_ast.Rule {
n := 0
for _, child := range rules {
child = p.lowerNestingInRuleWithContext(child, context)
if child.Data != nil {
rules[n] = child
n++
}
}
return rules[:n]
}
type lowerNestingContext struct {
parentSelectors []css_ast.ComplexSelector
loweredRules []css_ast.Rule
}
func (p *parser) lowerNestingInRuleWithContext(rule css_ast.Rule, context *lowerNestingContext) css_ast.Rule {
switch r := rule.Data.(type) {
case *css_ast.RSelector:
// "a { & b {} }" => "a b {}"
// "a { &b {} }" => "a:is(b) {}"
// "a { &:hover {} }" => "a:hover {}"
// ".x { &b {} }" => "b.x {}"
// "a, b { .c, d {} }" => ":is(a, b) :is(.c, d) {}"
// "a, b { &.c, & d, e & {} }" => ":is(a, b).c, :is(a, b) d, e :is(a, b) {}"
// Pass 1: Canonicalize and analyze our selectors
canUseGroupDescendantCombinator := true // Can we do "parent «space» :is(...selectors)"?
canUseGroupSubSelector := true // Can we do "parent«nospace»:is(...selectors)"?
var commonLeadingCombinator css_ast.Combinator
for i := range r.Selectors {
sel := &r.Selectors[i]
// Inject the implicit "&" now for simplicity later on
if sel.IsRelative() {
sel.Selectors = append([]css_ast.CompoundSelector{{NestingSelectorLoc: ast.MakeIndex32(uint32(rule.Loc.Start))}}, sel.Selectors...)
}
// Pseudo-elements aren't supported by ":is" (i.e. ":is(div, div::before)"
// is the same as ":is(div)") so we need to avoid generating ":is" if a
// pseudo-element is present.
if sel.UsesPseudoElement() {
canUseGroupDescendantCombinator = false
canUseGroupSubSelector = false
}
// Are all children of the form "& «something»"?
if len(sel.Selectors) < 2 || !sel.Selectors[0].IsSingleAmpersand() {
canUseGroupDescendantCombinator = false
} else {
// If all children are of the form "& «COMBINATOR» «something»", is «COMBINATOR» the same in all cases?
var combinator css_ast.Combinator
if len(sel.Selectors) >= 2 {
combinator = sel.Selectors[1].Combinator
}
if i == 0 {
commonLeadingCombinator = combinator
} else if commonLeadingCombinator.Byte != combinator.Byte {
canUseGroupDescendantCombinator = false
}
}
// Are all children of the form "&«something»"?
if first := sel.Selectors[0]; !first.HasNestingSelector() || first.IsSingleAmpersand() {
canUseGroupSubSelector = false
}
}
// Avoid generating ":is" if it's not supported
if p.options.unsupportedCSSFeatures.Has(compat.IsPseudoClass) && len(r.Selectors) > 1 {
canUseGroupDescendantCombinator = false
canUseGroupSubSelector = false
}
// Try to apply simplifications for shorter output
if canUseGroupDescendantCombinator {
// "& a, & b {}" => "& :is(a, b) {}"
// "& > a, & > b {}" => "& > :is(a, b) {}"
nestingSelectorLoc := r.Selectors[0].Selectors[0].NestingSelectorLoc
for i := range r.Selectors {
sel := &r.Selectors[i]
sel.Selectors = sel.Selectors[1:]
}
merged := p.multipleComplexSelectorsToSingleComplexSelector(r.Selectors)(rule.Loc)
merged.Selectors = append([]css_ast.CompoundSelector{{NestingSelectorLoc: nestingSelectorLoc}}, merged.Selectors...)
r.Selectors = []css_ast.ComplexSelector{merged}
} else if canUseGroupSubSelector {
// "&a, &b {}" => "&:is(a, b) {}"
// "> &a, > &b {}" => "> &:is(a, b) {}"
nestingSelectorLoc := r.Selectors[0].Selectors[0].NestingSelectorLoc
for i := range r.Selectors {
sel := &r.Selectors[i]
sel.Selectors[0].NestingSelectorLoc = ast.Index32{}
}
merged := p.multipleComplexSelectorsToSingleComplexSelector(r.Selectors)(rule.Loc)
merged.Selectors[0].NestingSelectorLoc = nestingSelectorLoc
r.Selectors = []css_ast.ComplexSelector{merged}
}
// Pass 2: Substitue "&" for the parent selector
if !p.options.unsupportedCSSFeatures.Has(compat.IsPseudoClass) || len(context.parentSelectors) <= 1 {
// If we can use ":is", or we don't have to because there's only one
// parent selector, or we are using ":is()" to match zero parent selectors
// (even if ":is" is unsupported), then substituting "&" for the parent
// selector is easy.
for i := range r.Selectors {
complex := &r.Selectors[i]
results := make([]css_ast.CompoundSelector, 0, len(complex.Selectors))
parent := p.multipleComplexSelectorsToSingleComplexSelector(context.parentSelectors)
for _, compound := range complex.Selectors {
results = p.substituteAmpersandsInCompoundSelector(compound, parent, results, keepLeadingCombinator)
}
complex.Selectors = results
}
} else {
// Otherwise if we can't use ":is", the transform is more complicated.
// Avoiding ":is" can lead to a combinatorial explosion of cases so we
// want to avoid this if possible. For example:
//
// .first, .second, .third {
// & > & {
// color: red;
// }
// }
//
// If we can use ":is" (the easy case above) then we can do this:
//
// :is(.first, .second, .third) > :is(.first, .second, .third) {
// color: red;
// }
//
// But if we can't use ":is" then we have to do this instead:
//
// .first > .first,
// .first > .second,
// .first > .third,
// .second > .first,
// .second > .second,
// .second > .third,
// .third > .first,
// .third > .second,
// .third > .third {
// color: red;
// }
//
// That combinatorial explosion is what the loop below implements. Note
// that PostCSS's implementation of nesting gets this wrong. It generates
// this instead:
//
// .first > .first,
// .second > .second,
// .third > .third {
// color: red;
// }
//
// That's not equivalent, so that's an incorrect transformation.
var selectors []css_ast.ComplexSelector
var indices []int
for {
// Every time we encounter another "&", add another dimension
offset := 0
parent := func(loc logger.Loc) css_ast.ComplexSelector {
if offset == len(indices) {
indices = append(indices, 0)
}
index := indices[offset]
offset++
return context.parentSelectors[index]
}
// Do the substitution for this particular combination
for i := range r.Selectors {
complex := r.Selectors[i]
results := make([]css_ast.CompoundSelector, 0, len(complex.Selectors))
for _, compound := range complex.Selectors {
results = p.substituteAmpersandsInCompoundSelector(compound, parent, results, keepLeadingCombinator)
}
complex.Selectors = results
selectors = append(selectors, complex)
offset = 0
}
// Do addition with carry on the indices across dimensions
carry := len(indices)
for carry > 0 {
index := &indices[carry-1]
if *index+1 < len(context.parentSelectors) {
*index++
break
}
*index = 0
carry--
}
if carry == 0 {
break
}
}
r.Selectors = selectors
}
// Lower all child rules using our newly substituted selector
context.loweredRules = p.lowerNestingInRule(rule, context.loweredRules)
return css_ast.Rule{}
case *css_ast.RKnownAt:
childContext := lowerNestingContext{parentSelectors: context.parentSelectors}
r.Rules = p.lowerNestingInRulesAndReturnRemaining(r.Rules, &childContext)
// "div { @media screen { color: red } }" "@media screen { div { color: red } }"
if len(r.Rules) > 0 {
childContext.loweredRules = append([]css_ast.Rule{{Loc: rule.Loc, Data: &css_ast.RSelector{
Selectors: context.parentSelectors,
Rules: r.Rules,
}}}, childContext.loweredRules...)
}
// "div { @media screen { &:hover { color: red } } }" "@media screen { div:hover { color: red } }"
if len(childContext.loweredRules) > 0 {
r.Rules = childContext.loweredRules
context.loweredRules = append(context.loweredRules, rule)
}
return css_ast.Rule{}
case *css_ast.RAtLayer:
// Lower all children and filter out ones that become empty
childContext := lowerNestingContext{parentSelectors: context.parentSelectors}
r.Rules = p.lowerNestingInRulesAndReturnRemaining(r.Rules, &childContext)
// "div { @layer foo { color: red } }" "@layer foo { div { color: red } }"
if len(r.Rules) > 0 {
childContext.loweredRules = append([]css_ast.Rule{{Loc: rule.Loc, Data: &css_ast.RSelector{
Selectors: context.parentSelectors,
Rules: r.Rules,
}}}, childContext.loweredRules...)
}
// "div { @layer foo { &:hover { color: red } } }" "@layer foo { div:hover { color: red } }"
// "div { @layer foo {} }" => "@layer foo {}" (layers have side effects, so don't remove empty ones)
r.Rules = childContext.loweredRules
context.loweredRules = append(context.loweredRules, rule)
return css_ast.Rule{}
}
return rule
}
type leadingCombinatorStrip uint8
const (
keepLeadingCombinator leadingCombinatorStrip = iota
stripLeadingCombinator
)
func (p *parser) substituteAmpersandsInCompoundSelector(
sel css_ast.CompoundSelector,
replacementFn func(logger.Loc) css_ast.ComplexSelector,
results []css_ast.CompoundSelector,
strip leadingCombinatorStrip,
) []css_ast.CompoundSelector {
if sel.HasNestingSelector() {
nestingSelectorLoc := logger.Loc{Start: int32(sel.NestingSelectorLoc.GetIndex())}
sel.NestingSelectorLoc = ast.Index32{}
replacement := replacementFn(nestingSelectorLoc)
// Convert the replacement to a single compound selector
var single css_ast.CompoundSelector
if sel.Combinator.Byte == 0 && (len(replacement.Selectors) == 1 || len(results) == 0) {
// ".foo { :hover & {} }" => ":hover .foo {}"
// ".foo .bar { &:hover {} }" => ".foo .bar:hover {}"
last := len(replacement.Selectors) - 1
results = append(results, replacement.Selectors[:last]...)
single = replacement.Selectors[last]
if strip == stripLeadingCombinator {
single.Combinator = css_ast.Combinator{}
}
sel.Combinator = single.Combinator
} else if len(replacement.Selectors) == 1 {
// ".foo { > &:hover {} }" => ".foo > .foo:hover {}"
single = replacement.Selectors[0]
if strip == stripLeadingCombinator {
single.Combinator = css_ast.Combinator{}
}
} else {
// ".foo .bar { :hover & {} }" => ":hover :is(.foo .bar) {}"
// ".foo .bar { > &:hover {} }" => ".foo .bar > :is(.foo .bar):hover {}"
p.reportNestingWithGeneratedPseudoClassIs(nestingSelectorLoc)
single = css_ast.CompoundSelector{
SubclassSelectors: []css_ast.SubclassSelector{{
Range: logger.Range{Loc: nestingSelectorLoc},
Data: &css_ast.SSPseudoClassWithSelectorList{
Kind: css_ast.PseudoClassIs,
Selectors: []css_ast.ComplexSelector{replacement.CloneWithoutLeadingCombinator()},
},
}},
}
}
var subclassSelectorPrefix []css_ast.SubclassSelector
// Insert the type selector
if single.TypeSelector != nil {
if sel.TypeSelector != nil {
p.reportNestingWithGeneratedPseudoClassIs(nestingSelectorLoc)
subclassSelectorPrefix = append(subclassSelectorPrefix, css_ast.SubclassSelector{
Range: sel.TypeSelector.Range(),
Data: &css_ast.SSPseudoClassWithSelectorList{
Kind: css_ast.PseudoClassIs,
Selectors: []css_ast.ComplexSelector{{Selectors: []css_ast.CompoundSelector{{TypeSelector: sel.TypeSelector}}}},
},
})
}
sel.TypeSelector = single.TypeSelector
}
// Insert the subclass selectors
subclassSelectorPrefix = append(subclassSelectorPrefix, single.SubclassSelectors...)
// Write the changes back
if len(subclassSelectorPrefix) > 0 {
sel.SubclassSelectors = append(subclassSelectorPrefix, sel.SubclassSelectors...)
}
}
// "div { :is(&.foo) {} }" => ":is(div.foo) {}"
for _, ss := range sel.SubclassSelectors {
if class, ok := ss.Data.(*css_ast.SSPseudoClassWithSelectorList); ok {
outer := make([]css_ast.ComplexSelector, 0, len(class.Selectors))
for _, complex := range class.Selectors {
inner := make([]css_ast.CompoundSelector, 0, len(complex.Selectors))
for _, sel := range complex.Selectors {
inner = p.substituteAmpersandsInCompoundSelector(sel, replacementFn, inner, stripLeadingCombinator)
}
outer = append(outer, css_ast.ComplexSelector{Selectors: inner})
}
class.Selectors = outer
}
}
return append(results, sel)
}
// Turn the list of selectors into a single selector by wrapping lists
// without a single element with ":is(...)". Note that this may result
// in an empty ":is()" selector (which matches nothing).
func (p *parser) multipleComplexSelectorsToSingleComplexSelector(selectors []css_ast.ComplexSelector) func(logger.Loc) css_ast.ComplexSelector {
if len(selectors) == 1 {
return func(logger.Loc) css_ast.ComplexSelector {
return selectors[0]
}
}
var leadingCombinator css_ast.Combinator
clones := make([]css_ast.ComplexSelector, len(selectors))
for i, sel := range selectors {
// "> a, > b" => "> :is(a, b)" (the caller should have already checked that all leading combinators are the same)
leadingCombinator = sel.Selectors[0].Combinator
clones[i] = sel.CloneWithoutLeadingCombinator()
}
return func(loc logger.Loc) css_ast.ComplexSelector {
return css_ast.ComplexSelector{
Selectors: []css_ast.CompoundSelector{{
Combinator: leadingCombinator,
SubclassSelectors: []css_ast.SubclassSelector{{
Range: logger.Range{Loc: loc},
Data: &css_ast.SSPseudoClassWithSelectorList{
Kind: css_ast.PseudoClassIs,
Selectors: clones,
},
}},
}},
}
}
}
func (p *parser) reportNestingWithGeneratedPseudoClassIs(nestingSelectorLoc logger.Loc) {
if p.options.unsupportedCSSFeatures.Has(compat.IsPseudoClass) {
_, didWarn := p.nestingWarnings[nestingSelectorLoc]
if didWarn {
// Only warn at each location once
return
}
if p.nestingWarnings == nil {
p.nestingWarnings = make(map[logger.Loc]struct{})
}
p.nestingWarnings[nestingSelectorLoc] = struct{}{}
text := "Transforming this CSS nesting syntax is not supported in the configured target environment"
if p.options.originalTargetEnv != "" {
text = fmt.Sprintf("%s (%s)", text, p.options.originalTargetEnv)
}
r := logger.Range{Loc: nestingSelectorLoc, Len: 1}
p.log.AddIDWithNotes(logger.MsgID_CSS_UnsupportedCSSNesting, logger.Warning, &p.tracker, r, text, []logger.MsgData{{
Text: "The nesting transform for this case must generate an \":is(...)\" but the configured target environment does not support the \":is\" pseudo-class."}})
}
}