Improve handling of @scope related at-rules - #20369
Conversation
Confidence Score: 5/5The PR appears safe to merge. No blocking failure remains within the scope of the follow-up review. Reviews (2): Last reviewed commit: "update changelog references" | Re-trigger Greptile |
WalkthroughAdded full 🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (3)
packages/tailwindcss/src/index.test.ts (1)
4898-4924: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd a unit snapshot for
&in the<scope-end>limit.The PR resolves
&differently inscope-startvsscope-end, andui.spec.tsrelies on build-time resolution ofto (& .limit), but no snapshot here pins that output. A case such as.parent {@scope(& > .a) to (& .b) { … } }would lock the distinct resolution rules in a fast unit test rather than only in the browser suite.packages/tailwindcss/tests/ui.spec.ts (1)
2320-2357: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winThe inner
to (.…-inner-limit)limit is never exercised.No element with class
${prefix}-inner-limitexists instructure(), so the inner scope's limit is inert in this test. Adding a probe nested inside an*-inner-limitelement would actually validate that the inner limit survives nesting/hoisting.🧪 Suggested fixture addition
<!-- Middle is beyond the outer limit --> <div class="${prefix}-outer"> <div class="${prefix}-outer-limit"> <div class="${prefix}-middle"> <div class="${prefix}-inner" id="${prefix}-beyond">beyond</div> </div> </div> </div> + + <!-- Probe beyond the inner limit --> + <div class="${prefix}-outer"> + <div class="${prefix}-middle"> + <div class="${prefix}-inner"> + <div class="${prefix}-inner-limit"> + <div class="${prefix}-inner" id="${prefix}-inner-beyond">inner beyond</div> + </div> + </div> + </div> + </div>packages/tailwindcss/src/compat/plugin-api.ts (1)
611-623: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDerive
usesAtScopefrom the parsed AST instead of a substring test.
r.includes('@scope')also matches@scopeinside a string/attribute value or comment, which then restructures the output with inertcontextwrappers. Sinceris parsed on the next line anyway, detect it structurally — the same wayVariants.fromAstdoes inpackages/tailwindcss/src/variants.ts(lines 93-103).♻️ Proposed refactor
if (r.trim().endsWith('}')) { - let usesAtScope = r.includes('`@scope`') let updatedCSS = r.replace('}', '{`@slot`}}') let ast = CSS.parse(updatedCSS) + + let usesAtScope = false + walk(ast, (node) => { + if (node.kind === 'at-rule' && node.name === '`@scope`') { + usesAtScope = true + return WalkAction.Stop + } + }) if (usesAtScope) {
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 6a5f16dc-b903-4cff-98b0-856f63db807e
📒 Files selected for processing (10)
CHANGELOG.mdpackages/tailwindcss/src/ast.test.tspackages/tailwindcss/src/ast.tspackages/tailwindcss/src/compat/plugin-api.test.tspackages/tailwindcss/src/compat/plugin-api.tspackages/tailwindcss/src/compile.tspackages/tailwindcss/src/index.test.tspackages/tailwindcss/src/index.tspackages/tailwindcss/src/variants.tspackages/tailwindcss/tests/ui.spec.ts
Custom variants defined with an @scope at-rule emitted the @scope block nested inside the generated utility class instead of wrapping it, so the resulting CSS had no effect in browsers. Treat @scope like other conditional at-rules (@media, @supports, @container) when resolving nesting, so it is hoisted above the generated style rules. Fixes #18961
We need to work in 2 modes here:
1. For when we use `@custom-variant`. This is because we built up the
rule with nesting, e.g.:
```css
@custom-variant scoped {
@scope (.from) to (.to) {
@slot;
}
}
```
If you use it, you can use `scoped:flex`, then we essentially build:
```css
.scoped\:flex {
@scope (.from) to (.to) {
display: flex;
}
}
```
The problem with this is that the `.scoped\:flex` is not inside the
`@scope`, and therefore the `.from` → `.to` sandwich doesn't work.
For this reason, we will mark all CSS defined by the
`@custom-variant` with a special `source: 'variant'` flag. And all
the other CSS is defined by `source: 'user'`.
The shorthand `@custom-variant` without `@slot`, the arbitrary
variants `[@scope…]:flex`, and variants defined by the `addVariant`
and `matchVariant` APIs will all have this additional treatment.
2. When using `@scope` in user-defined CSS (aka, not via a Tailwind
variant), then we don't want to swap this `@scope` at-rule, and the
rule with the class selector because it will change its meaning.
We will still handle the `@scope` nesting because Lightning CSS will
otherwise generate invalid CSS.
Input:
```css
.parent {
@scope (.from) to (.to) {
.sandwhich {
color: red;
}
}
}
```
Lightning CSS will turn this into:
```css
@scope (.from) to (.to) {
:scope .sandwhich {
color: red;
}
}
```
Losing the concept of the `.parent` class. Instead we will apply our
flattening rules and hoist the `@scope` out. This also requires us to
update the `<scope-start>` with the parent information:
```css
@scope (.parent .from) to (.to) {
.sandwhich {
color: red;
}
}
```
Another fix for Lightning CSS is to ensure that we introduce
`:where(:scope)` rules for when there are bare declarations in the
`@scope` at-rule. Otherwise Lightning CSS would crash.
```css
.parent {
@scope (.from) to (.to) {
color: red;
}
}
```
This would crash, so we make sure that this turns into:
```css
@scope (.parent .from) to (.to) {
:where(:scope) {
color: red;
}
}
```
675f446 to
b725360
Compare
Continuation of #20344, original commits of that PR are present in this PR as well.
Before we talk about the issues, there is some jargon I'll be using that might be unfamiliar:
This PR contains multiple fixes, but they are all related to the
@scopeat-rule. The@scopeat-rule is a beast, it's an at-rule where we do have multiple selectors in the prelude, which in turn can contain&rules. If you use&inside of an@scoperule, its meaning changes compared to what&typically means and it is even different whether it exists inscope-startorscope-end.Let's start with the original issue, if you define a custom variant like:
Then using
blue:bg-blue-500used to generate:This is because internally we start with the AST node representing
bg-blue-500, then we wrap all thevariantrelated nodes around it (blue), and then wrap everything in the final rule with a selector representing the class (.blue\:bg-blue-500).This is incorrect because you want that sandwich effect where any
.blue\:bg-blue-500class between an element with the[data-theme="blue"]attribute and another nested[data-theme]attribute.The other PR solved this by simply making sure that the
@scoperule gets hoisted to the top. For this particular example that was enough.However, that would result in a ton more issues. This hoisting or swapping with the rule is only "safe" in a
custom-variant.So similar to the other PR, this PR wraps this properly:
The tricky part is that the nesting pass runs on all CSS, custom variants and your own CSS. Hoisting an
@scoperule out of the rule it is nested in changes its meaning.Take a look at this example:
This says that you need a structure roughly like this:
If we had switched it:
Then this requires that an element with a class of
.parentlives between the.fromscope-start and.toscope-end:Subtle, but it's definitely wrong.
Instead, we will apply our flattening rules, such that the
@scopegets hoisted, but we have to bring that.parentselector requirement inside of the@scopeprelude, more specifically inside thescope-start:We could have left this as-is, but there is a Lightning CSS bug where the original CSS:
gets turned into:
Notice how the
.parentclass is not found at all? (I will open some issues on the Lightning CSS repo (and PRs to fix this). But it's a good fix to have in Tailwind CSS as well, just because a lot of tooling is already using Lightning CSS on top of Tailwind CSS, so we need an entire chain to be updated for this to work.)Side note: the version we generate is untouched by Lightning CSS.
Resolving
&in the prelude&resolves differently depending on which scope selector you're looking at (spec):<scope-start>selector,&refers to the elements matched by the nearest ancestor style rule (the utility, for variants).<scope-end>selector,&refers to the scoping root and behaves like:where(:scope).:scopemight work, but that has a specificity of0,1,0instead of0,0,0.So this input:
compiles to:
The substitution uses the exact same logic as
&in nested style rule selectors::is(…)semantics by default, dropping the:is(…)whenever the substitution is provably equivalent.So a complex parent compiles to
@scope (.a .b > .from)rather than@scope (:is(.a .b) > .from), while.card&inside amainrule keeps it (@scope (.card:is(main))) because substituting the type selector as-is would produce invalid CSS.For user CSS, every selector in a
<scope-start>selector list is relative to the parent rule, whether it uses&or not, just like nested style rule selectors:compiles to:
Controlling the composition with
&Because
&in the<scope-start>selector refers to the utility, variant authors can control where the utility ends up:generates:
Note that when the utility becomes the scoping root, the
<scope-end>limit no longer affects the utility itself (a scoping root is never beyond its own limits), and the declarations apply to the root with zero specificity. The default composition is usually what you want to get the sandwich effect, but now you can get the other behavior if you want.Bare declarations
There is another small Lightning CSS bug that we want to fix. If you have the following CSS:
Then Lightning CSS crashes with an unexpected input. The spec says that:
So this is what we will do as well:
One more small detail about the implementation: we do have to track which CSS is coming from the custom variant, and what is user defined CSS. To do this, we insert some internal
contextnodes with a{ source: 'user' }or{ source: 'variant' }so we know when we can just swap this@scopearound, or if we just have to handle the nesting and&substitutions.Fixes: #18961
Closes: #20344
Test plan
@scopein user-land@scopein custom variants@custom-variantshorthand syntax@custom-variantsyntax with@slot[@scope_(.from)_to_(.to)]:flexaddVariant()andmatchVariant()APIs&selectorsLast but not least, looking at the reproduction provided in the issue:

Before:
After:

Sorry about all the sandwiches, I'm hungry myself.