Skip to content

Conversation

@yangxiuxiu1115
Copy link
Contributor

@yangxiuxiu1115 yangxiuxiu1115 commented Nov 16, 2024

fix #12404
fix #12405

Summary by CodeRabbit

  • Bug Fixes

    • Corrected ::v-global behavior in scoped styles. The global segment now properly applies to subsequent selectors while preserving outer context and avoiding unintended scoping on global rules. Improves results for patterns like body h1, nested globals, and mixed selectors (e.g., .baz .qux ::v-global(.foo .bar)).
  • Tests

    • Expanded coverage for ::v-global scenarios and updated snapshots to reflect the corrected scoping behavior.

@github-actions
Copy link

github-actions bot commented Nov 16, 2024

Size Report

Bundles

File Size Gzip Brotli
runtime-dom.global.prod.js 101 kB 38.5 kB 34.6 kB
vue.global.prod.js 159 kB 58.6 kB 52.1 kB

Usages

Name Size Gzip Brotli
createApp (CAPI only) 46.6 kB 18.2 kB 16.7 kB
createApp 54.6 kB 21.3 kB 19.4 kB
createSSRApp 58.9 kB 23 kB 21 kB
defineCustomElement 59.6 kB 22.8 kB 20.9 kB
overall 68.8 kB 26.4 kB 24.2 kB

@pkg-pr-new
Copy link

pkg-pr-new bot commented Nov 16, 2024

Open in Stackblitz

@vue/compiler-core

pnpm add https://pkg.pr.new/@vue/compiler-core@12416

@vue/compiler-dom

pnpm add https://pkg.pr.new/@vue/compiler-dom@12416

@vue/compiler-ssr

pnpm add https://pkg.pr.new/@vue/compiler-ssr@12416

@vue/compiler-sfc

pnpm add https://pkg.pr.new/@vue/compiler-sfc@12416

@vue/reactivity

pnpm add https://pkg.pr.new/@vue/reactivity@12416

@vue/runtime-core

pnpm add https://pkg.pr.new/@vue/runtime-core@12416

@vue/runtime-dom

pnpm add https://pkg.pr.new/@vue/runtime-dom@12416

@vue/server-renderer

pnpm add https://pkg.pr.new/@vue/server-renderer@12416

@vue/shared

pnpm add https://pkg.pr.new/@vue/shared@12416

vue

pnpm add https://pkg.pr.new/vue@12416

@vue/compat

pnpm add https://pkg.pr.new/@vue/compat@12416

commit: 436415a

expect(compileScoped(`.baz .qux ::v-global(.foo .bar) { color: red; }`))
.toMatchInlineSnapshot(`
".foo .bar { color: red;
".baz .qux[data-v-test] .foo .bar { color: red;
Copy link
Member

@edison1105 edison1105 Nov 18, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The original behavior was that global would ignore the preceding rules, but it will no longer do so after this PR. this will introduce some edge cases. see:

@edison1105 edison1105 added scope: sfc 🔨 p3-minor-bug Priority 3: this fixes a bug, but is an edge case that only affects very specific usage. ready for review This PR requires more reviews ready to merge The PR is ready to be merged. and removed ready for review This PR requires more reviews labels Nov 18, 2024
Copy link
Contributor

@skirtles-code skirtles-code left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've been experimenting with this and I'm wondering about some apparent inconsistencies in how selectors are handled. For example:

The background-color is applied to some of the headings, but not others. It's not really clear to me what would be considered correct here, but I can't really justify the differences.

@GrantGryczan
Copy link

GrantGryczan commented Sep 14, 2025

@skirtles-code The intended behavior seems to be that the compiler always scopes the deepest part of the selector. So in :global(x) y z, z would be scoped. This makes sense because the deepest selector directly represents the element actually being selected, so that's the element that should be scoped. Note that the same logic applies to other selector types, like >, +, and ~.

But what if the deepest element is global, like in x y :global(z)? Then it can't be scoped. Currently, x y :global(z) just compiles to z unscoped. This is fine because it's semantically nonsensical to put a global selector under a non-global selector, so I don't think it really matters what that does. If the developer does that, they probably meant to use :deep instead. It could be considered undefined behavior, but it's probably a good idea to maintain the existing behavior for backwards compatibility in non-nested CSS (which is just to omit any ancestor selectors before the :global).

Extending this logic to CSS nesting, it doesn't matter what happens when you use a :global selector inside a nested selector, because semantically that doesn't even make sense. The developer should be using :deep for that instead. And naturally, that's why you can't justify any differences. For nested CSS, the results of that playground don't matter. And for non-nested CSS, the results of that playground only possibly matter for backwards compatibility.

Side note: I think it would have been nice if Vue 3 were originally designed with only :global, not :deep, and then :global under another selector would semantically represent what :deep currently does. Then it'd be impossible to represent semantically nonsensical selectors with non-global ancestors of :global. Really, I'd argue :global and :deep are for the same purpose: removing the scoping from a selector. But this is beside the point, just a side note on the topic of the semantics here.

@coderabbitai
Copy link

coderabbitai bot commented Sep 23, 2025

Walkthrough

This change updates scoped CSS rewriting to correctly handle ::v-global so that following selectors are scoped appropriately while preserving outer context. It adds a wrapped-global state, propagates it through wrappers, skips attribute injection for globally wrapped rules, and expands tests to cover nested and combination selectors.

Changes

Cohort / File(s) Summary
Scoped CSS global handling
packages/compiler-sfc/src/style/pluginScoped.ts
Introduces wrapped-global state in rewriteSelector; spreads ::v-global inner nodes; propagates a __global marker via extractAndWrapNodes(parentNode, wrappedGlobal); short-circuits attribute injection when __global is present; updates extractAndWrapNodes signature to accept wrappedGlobal.
Tests for ::v-global semantics
packages/compiler-sfc/__tests__/compileStyle.spec.ts
Expands test cases for ::v-global with body/element combos, nested globals, and mixed selectors; updates inline snapshots to reflect new scoping where the global portion influences subsequent selectors while preserving preceding context; removes an outdated comment.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Dev as SFC Author
  participant SFC as SFC Compiler
  participant PS as pluginScoped.rewriteSelector
  participant Wrap as extractAndWrapNodes
  note over Dev,SFC: <style scoped> with selectors using ::v-global(...)
  Dev->>SFC: Submit SFC for compilation
  SFC->>PS: Rewrite each selector (scoped attrs)
  alt Selector contains ::v-global(...)
    PS->>PS: Replace ::v-global with its inner nodes
    PS->>PS: Determine if resulting selector is a single node
    alt Single node (globally wrapped)
      PS->>Wrap: extractAndWrapNodes(rule, wrappedGlobal=true)
      Wrap-->>PS: Wrapper with __global=true
      note right of PS: Mark rule as globally wrapped
      PS->>PS: Skip attribute injection (due to __global)
    else Multiple nodes
      PS->>Wrap: extractAndWrapNodes(rule, wrappedGlobal=false)
      Wrap-->>PS: Wrapper with __global=false
      PS->>PS: Continue normal injection on non-global parts
    end
  else No ::v-global
    PS->>PS: Perform normal scoped attribute injection
  end
  PS-->>SFC: Rewritten CSS AST
  SFC-->>Dev: Emitted scoped CSS
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • Doctor-wu

Poem

I twitch my whiskers at global’s call,
From body to h1, I scope it all.
A hop, a wrap—__global marked—
No stray attrs where global sparked.
Nesting aligned, snapshots true—
Carrot-commits for CSS that grew. 🥕

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title "fix(compiler-sfc): support global selector nesting" is concise, single-line, and directly describes the primary change in this changeset—fixes to compiler-sfc scoped-style handling to support nested/global selectors (::v-global/:global). It is specific enough for a reviewer scanning history to understand the PR's main intent without listing files or extraneous detail.
Linked Issues Check ✅ Passed The diffs implement wrappedGlobal propagation in rewriteSelector and extractAndWrapNodes, attach an __global flag to wrapped rules, and short-circuit attribute injection for global selectors while expanding compileStyle.spec.ts tests to cover ancestor/descendant and nested :global/::v-global scenarios (e.g., body h1, html ::v-global(body) h1, nested rules and preceding-selector cases). These code and test changes directly address issue #12404 by preserving descendant selectors (producing outputs like "body h1[data-v-...]") and issue #12405 by correctly wrapping nested :global blocks so nested rules compile with the intended scoped/global behavior. Based on the provided implementation and updated snapshots, the PR meets the linked issues' coding objectives.
Out of Scope Changes Check ✅ Passed The changes are localized to packages/compiler-sfc/src/style/pluginScoped.ts and its tests; the only signature change is an internal extractAndWrapNodes parameter to propagate wrappedGlobal and the wrapper receives a non-exported __global flag, so there are no public API or unrelated feature modifications. No other files or unrelated subsystems were touched, indicating the patch is focused on the stated bug fixes.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/compiler-sfc/src/style/pluginScoped.ts (1)

241-249: Propagate global-wrapped state into @rules to avoid accidental scoping.

When wrapping declarations under nested at‑rules inside a global block, the wrapper created from the at‑rule should inherit wrappedGlobal. Today it doesn’t, so declarations under @media (or similar) inside ::v-global(...) { ... } may get scoped incorrectly.

Apply:

-      const atruleNodes = rule.nodes.filter(node => node.type === 'atrule')
+      const atruleNodes = rule.nodes.filter(node => node.type === 'atrule')
       for (const atnode of atruleNodes) {
-        extractAndWrapNodes(atnode)
+        extractAndWrapNodes(atnode, wrappedGlobal)
       }
🧹 Nitpick comments (3)
packages/compiler-sfc/src/style/pluginScoped.ts (2)

104-111: Global-wrapped early-exit is correct; consider bailing earlier.

Instead of checking __global on every selector node, short‑circuit before selector.each(...) when rule.__global === true to avoid needless iteration on wrapper rules like &. Behavior stays identical; it’s a small readability/efficiency win.


292-308: Wrapper flagging looks good; add a brief doc note.

extractAndWrapNodes(..., wrappedGlobal) + (wrappedRule as any).__global = wrappedGlobal is clear. Add a short comment explaining this prevents id injection on the “&” wrapper only, while allowing nested rules (e.g., h1) to be scoped under a global ancestor.

packages/compiler-sfc/__tests__/compileStyle.spec.ts (1)

227-235: Nested global behavior is validated; add @media/combinator cases too.

Please add:

  • ::v-global(body){ @media (max-width:600px){ color:red } } (ensure no id on wrapper under @media).
  • :global(body) > h1 and .a :global(.b) > .c (combinators).
  • :global(.a, .b) .c (comma list) to lock behavior discussed above.

I can draft these test cases if helpful.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b555f02 and 98f57ef.

📒 Files selected for processing (2)
  • packages/compiler-sfc/__tests__/compileStyle.spec.ts (1 hunks)
  • packages/compiler-sfc/src/style/pluginScoped.ts (5 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: continuous-release
🔇 Additional comments (5)
packages/compiler-sfc/src/style/pluginScoped.ts (1)

196-202: Confirm behavior for multiple inner selectors in :global().

For :global(.a, .b), n.replaceWith(...n.nodes) will inject multiple inner selectors. Please confirm the intended scoping result and add a test (comma list + with/without trailing descendants), as selector list flattening here can be tricky in postcss-selector-parser.

packages/compiler-sfc/__tests__/compileStyle.spec.ts (4)

203-207: Correct: scope the deepest non-global segment before a trailing global.

Expectation .baz .qux[data-v-test] .foo .bar { ... } matches the intended rule.


209-214: Good: :global(body) h1 scopes h1 while preserving body.

This guards the core regression from #12404.


215-220: Good: pure-global selector remains unscoped.

:global(body h1) compiling to body h1 (no id) is correct.


221-226: Good: preserves outer context before global.

html ::v-global(body) h1html body h1[data-v-test] is consistent with “scope the right‑most non‑global”.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🔨 p3-minor-bug Priority 3: this fixes a bug, but is an edge case that only affects very specific usage. ready to merge The PR is ready to be merged. scope: sfc

Projects

None yet

Development

Successfully merging this pull request may close these issues.

:global doesn't work with CSS nesting :global(A) B incorrectly compiles to just A

4 participants