Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(css-vars): nullish v-bind in style should not lead to unexpected inheritance #12461

Open
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

Justineo
Copy link
Member

@Justineo Justineo commented Nov 23, 2024

Currently, we generate CSS custom properties on component roots for each v-bind in SFC <style> blocks. When one component instance is nested inside another, the nested instance can inherit values from the outer instance, even if its own binding value is undefined or null. Ideally, style bindings should be scoped per component instance since they depend on the instance's state. However, with the current approach using CSS custom properties, we can't generate unique hashed names for each instance because CSS can only reference a single property.

To address this, the improvement here is to "reset" these custom properties when the binding value is nullish.

Current Behavior:

This PR:

  • Ensures both CSR and SSR generate --<hash>-<name>:initial for nullish values. This properly resets the custom property, as explained in the CSS spec. It behaves as if no custom property is defined in ancestor elements.

SSR Note:

  • Added a special : prefix to distinguish style entries coming from v-bind in styles. This allows us to process them separately from user-defined custom properties in ssrRenderStyle. Alternatively, we can also create a new runtime helper and modify the codegen here:
image

Not sure if my current approach is preferred. Let me know if you have other opinions.

Copy link

github-actions bot commented Nov 23, 2024

Size Report

Bundles

File Size Gzip Brotli
runtime-dom.global.prod.js 100 kB (+74 B) 38 kB (+34 B) 34.2 kB (-10 B)
vue.global.prod.js 158 kB (+74 B) 57.8 kB (+32 B) 51.5 kB (+53 B)

Usages

Name Size Gzip Brotli
createApp (CAPI only) 47.2 kB 18.3 kB 16.8 kB
createApp 55.2 kB 21.3 kB 19.5 kB
createSSRApp 59.3 kB 23.1 kB 21 kB
defineCustomElement 60.1 kB 22.9 kB 20.8 kB
overall 69.1 kB 26.5 kB 24.1 kB

Copy link

pkg-pr-new bot commented Nov 23, 2024

Open in Stackblitz

@vue/compiler-core

npm i https://pkg.pr.new/@vue/compiler-core@12461

@vue/compiler-dom

npm i https://pkg.pr.new/@vue/compiler-dom@12461

@vue/compiler-ssr

npm i https://pkg.pr.new/@vue/compiler-ssr@12461

@vue/compiler-sfc

npm i https://pkg.pr.new/@vue/compiler-sfc@12461

@vue/reactivity

npm i https://pkg.pr.new/@vue/reactivity@12461

@vue/runtime-core

npm i https://pkg.pr.new/@vue/runtime-core@12461

@vue/runtime-dom

npm i https://pkg.pr.new/@vue/runtime-dom@12461

@vue/server-renderer

npm i https://pkg.pr.new/@vue/server-renderer@12461

@vue/shared

npm i https://pkg.pr.new/@vue/shared@12461

vue

npm i https://pkg.pr.new/vue@12461

@vue/compat

npm i https://pkg.pr.new/@vue/compat@12461

commit: 8567a73

@Justineo
Copy link
Member Author

/ecosystem-ci run

@vue-bot
Copy link
Contributor

vue-bot commented Nov 23, 2024

📝 Ran ecosystem CI: Open

suite result latest scheduled
language-tools success success
nuxt success success
pinia success success
primevue success success
quasar success success
radix-vue success success
router success success
test-utils success success
vant success success
vite-plugin-vue success success
vitepress success success
vue-i18n success success
vue-macros success success
vuetify success success
vueuse failure failure
vue-simple-compiler success success

@skirtles-code
Copy link
Contributor

I think this would also close #7474 and the associated PR #7475.


There's an underlying question here about whether we consider undefined and null to be valid values for CSS v-bind(). Should we support them, or should we just log a warning? It is possible to handle them in userland code instead, e.g. using v-bind(c ?? 'initial').

Then there's a follow up decision about where to draw the line. What about an empty string (Playground)? Or a white-space value like " "? Or an empty array (Playground)? Etc.

I don't want to expand the scope of this PR unnecessarily, but I do think it's important to be clear why we're drawing the line at nullish values.

@Justineo
Copy link
Member Author

Justineo commented Nov 24, 2024

@skirtles-code Thanks for the feedback! Great questions!

Here’s what I thought:

  1. Why not handle them in userland?
    Theoretically, using CSS custom properties for v-bind in <style> blocks is an implementation detail that users are not supposed to be aware of. However, there are notable differences in behavior between color: v-bind('"initial"') and color: initial. The former binds initial to the custom property, making it functionally equivalent to color: unset, whereas the latter directly applies the initial keyword as intended in CSS. Making users to write initial to reset values while it actually behaves like unset can be quite frustrating, so I would prefer to make it more transparent.
  2. Why only convert nullish values?
    You're absolutely right—more values should be considered. I think it's kind of similar to our props coercion, where we are removing a binding with nullish values. For CSS custom properties, "removing" in this context means resetting to their initial value, which is the guaranteed invalid value, which can be explicitly set with the keyword initial.
    Per the CSS specification, empty strings and white spaces for custom properties behave differently from initial, as they prevent fallback values from taking effect. Currently, we are removing the custom property for empty strings, but retaining white spaces. This creates an inconsistency if users are binding the value to a custom property themselves (Playground).
    To address this, I believe we should treat empty strings and white spaces as-is, maintaining consistency and aligning better with user expectations. I reconsidered and think we should handle it comprehensively as outlined in the table below. Could you kindly help review it? Thank you!

The situation is more complicated than I expected. I'm investigating the current behavior of Vue and CSS custom properties.

Current behavior:

v-bind value SSR output CSR output Mismatch
null / /
undefined / --foo: undefined ⚠️
empty string --foo:; / ⚠️
white spaces --foo: ; --foo: ;

For Vue, undefined and empty string will cause SSR/CSR mismatch

For CSS custom properties:

  • The cssText, code in <style>, and style attribute behave differently from style.setProperty. During SSR, we use the former, while during CSR, we use both.
  • The behavior of --foo:; differs from style.setProperty('--foo', ''). The former acts like white spaces, while the latter effectively removes the declaration.

Since we are binding values to CSS, we should align with CSS behavior, where an empty string is treated as equivalent to white spaces. To fix the SSR/CSR mismatch and ensure consistent resetting, I propose handling values as follows:

v-bind value SSR CSR
null --foo: initial style.setProperty('--foo', 'initial')
undefined --foo: initial style.setProperty('--foo', 'initial')
empty string --foo: ; style.setProperty('--foo', ' ')
white spaces --foo: ; style.setProperty('--foo', ' ')

For other string values, we should output them as-is. For unsupported types of values, we should warn about the binding and retain the current behavior (rendering everything as a string, likely using String(value)).

WDYT? /cc @adamdehaven @skirtles-code @edison1105

@adamdehaven
Copy link

@Justineo I thought we determined that a whitespace character would be ideal?

@Justineo
Copy link
Member Author

After rereading the spec, I believe that only the initial value truly resets the custom property to its default state, as if it were never set.

@Justineo Justineo marked this pull request as draft November 25, 2024 04:38
@adamdehaven
Copy link

After rereading the spec, I believe that only the initial value truly resets the custom property to its default state, as if it were never set.

The white space character seems to work in practice if you can try?

@Justineo
Copy link
Member Author

Justineo commented Nov 25, 2024

The white space character seems to work in practice if you can try?

White space sets a valid empty value, which will prevent fallback value to take effect. initial resets the custom property to its initial value–the guaranteed invalid value, which is the same as it’s not declared. I have tested and can confirm the implementation is aligned with the spec in all major browsers.

@adamdehaven
Copy link

The white space character seems to work in practice if you can try?

White space sets a valid empty value, which will prevent fallback value to take effect. initial resets the custom property to its initial value–the guaranteed invalid value, which is the same as it’s not declared. I have tested and can confirm the implementation is aligned with the spec in all major browsers.

I'm not sure injecting initial in all those places though is desirable. Do you have a reproduction with this behavior?

In my testing, initial and a white space character behave differently.

See the example taken from here

image

@Justineo
Copy link
Member Author

Justineo commented Nov 25, 2024

I'm not sure injecting initial in all those places though is desirable.

It is the standard way to reset a custom property.

Do you have a reproduction with this behavior?

https://codepen.io/Justineo/pen/VYZZPOz

As shown in this pen, initial works the same as not setting the value.

In my testing, initial and a white space character behave differently.

That’s why we should use initial instead of white spaces…

See the example taken from here

We certainly don’t want to invalidate the fallback value red in var(--foo, red) when no valid value is bound to --foo. Therefore, using initial is the only appropriate solution.

@adamdehaven
Copy link

https://codepen.io/Justineo/pen/VYZZPOz

The reproduction looks correct; thanks for putting that together

@edison1105 edison1105 requested a review from Copilot November 27, 2024 13:36

Choose a reason for hiding this comment

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

Copilot reviewed 5 out of 9 changed files in this pull request and generated no suggestions.

Files not reviewed (4)
  • packages/compiler-sfc/tests/snapshots/compileScript.spec.ts.snap: Language not supported
  • packages/runtime-core/src/component.ts: Evaluated as low risk
  • packages/compiler-sfc/tests/compileScript.spec.ts: Evaluated as low risk
  • packages/runtime-dom/src/helpers/useCssVars.ts: Evaluated as low risk
@skirtles-code
Copy link
Contributor

TLDR: I think the latest proposal looks good.


I wasn't initially clear about the difference between initial and v-bind('"initial"'), so I put together a Playground to help demonstrate:

v-bind('"initial"') does indeed behave like unset, not initial. I concur that this does make handling undefined/null in userland less appealing.


Using initial for undefined and null makes sense to me.

I also like the idea of treating an empty string as a space. That prevents the variable being inherited from the parent component and also seems consistent with vanilla CSS. It wasn't immediately clear to me why a space character would be better than initial in that case, so I put together another Playground to show an example where it would actually make a difference:

In that example, we would want v-bind('""') to behave like .bar and .baz, not .foo, so a space character seems to give us what we want.

@Justineo
Copy link
Member Author

@skirtles-code Thank you for the demos! I’ll update the code to align with our latest conclusions.

@Justineo
Copy link
Member Author

/ecosystem-ci run

@Justineo Justineo marked this pull request as ready for review November 30, 2024 17:10
@vue-bot
Copy link
Contributor

vue-bot commented Nov 30, 2024

📝 Ran ecosystem CI: Open

suite result latest scheduled
language-tools success success
nuxt success success
pinia success success
primevue success success
quasar success success
radix-vue success success
router success success
test-utils success success
vant success success
vite-plugin-vue success success
vitepress success success
vue-i18n success success
vue-macros failure success
vuetify success success
vueuse success success
vue-simple-compiler success success

return value === '' ? ' ' : value
}

if (typeof value !== 'number' || !Number.isFinite(value)) {
Copy link
Member Author

@Justineo Justineo Nov 30, 2024

Choose a reason for hiding this comment

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

Note for reviewers: Apart from the proposed solution at #12461 (comment), I believe it is reasonable to allow finite numbers to be bound to CSS properties. For other data types, I couldn’t determine any clear expected behavior so a development-time warning is added.

if (__DEV__) {
console.warn(
'[Vue warn] Invalid value used for CSS binding. Expected a string or a finite number but received:',
value,
Copy link
Member Author

Choose a reason for hiding this comment

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

Note: The value is not converted to a string in the warning message because it may include empty arrays, and excessive effort to stringify the value is unnecessary in this context.

@Justineo
Copy link
Member Author

Justineo commented Dec 3, 2024

/ecosystem-ci run

@vue-bot
Copy link
Contributor

vue-bot commented Dec 3, 2024

📝 Ran ecosystem CI: Open

suite result latest scheduled
language-tools failure success
nuxt failure success
pinia success success
primevue success success
quasar success success
radix-vue success success
router success success
test-utils success success
vant success success
vite-plugin-vue success success
vitepress success success
vue-i18n success success
vue-macros success success
vuetify success success
vueuse success success
vue-simple-compiler success success

@Justineo
Copy link
Member Author

Justineo commented Dec 4, 2024

/ecosystem-ci run

@vue-bot
Copy link
Contributor

vue-bot commented Dec 4, 2024

📝 Ran ecosystem CI: Open

suite result latest scheduled
language-tools failure success
nuxt success success
pinia success success
primevue success success
quasar success success
radix-vue success success
router success success
test-utils success success
vant success success
vite-plugin-vue success success
vitepress success success
vue-i18n success success
vue-macros success success
vuetify success success
vueuse success success
vue-simple-compiler success success

@Justineo
Copy link
Member Author

Justineo commented Dec 4, 2024

language-tools ❌ failure

Doesn't seem to be related to this PR.

@adamdehaven
Copy link

@edison1105 is there anything else myself or @Justineo can provide here to help this PR along?

I have a workaround in my project in a draft PR; however, it's definitely "messy" requiring me to manually inject initial all over the place in my userland code.

@edison1105
Copy link
Member

@adamdehaven
I've approved this PR. then, we need to wait for Evan's review. It should be included in the next release.

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