wip: simplify useCssVars

This commit is contained in:
Evan You 2020-11-17 13:03:47 -05:00
parent dfac6eee99
commit f92bc5a19a
6 changed files with 46 additions and 77 deletions

View File

@ -5,8 +5,8 @@ exports[`CSS vars injection codegen <script> w/ default export 1`] = `
import { useCssVars as _useCssVars } from 'vue' import { useCssVars as _useCssVars } from 'vue'
const __injectCSSVars__ = () => { const __injectCSSVars__ = () => {
_useCssVars(_ctx => ({ _useCssVars(_ctx => ({
color: (_ctx.color) \\"xxxxxxxx-color\\": (_ctx.color)
}), \\"xxxxxxxx\\")} }))}
const __setup__ = __default__.setup const __setup__ = __default__.setup
__default__.setup = __setup__ __default__.setup = __setup__
? (props, ctx) => { __injectCSSVars__();return __setup__(props, ctx) } ? (props, ctx) => { __injectCSSVars__();return __setup__(props, ctx) }
@ -22,8 +22,8 @@ exports[`CSS vars injection codegen <script> w/ default export in strings/commen
import { useCssVars as _useCssVars } from 'vue' import { useCssVars as _useCssVars } from 'vue'
const __injectCSSVars__ = () => { const __injectCSSVars__ = () => {
_useCssVars(_ctx => ({ _useCssVars(_ctx => ({
color: (_ctx.color) \\"xxxxxxxx-color\\": (_ctx.color)
}), \\"xxxxxxxx\\")} }))}
const __setup__ = __default__.setup const __setup__ = __default__.setup
__default__.setup = __setup__ __default__.setup = __setup__
? (props, ctx) => { __injectCSSVars__();return __setup__(props, ctx) } ? (props, ctx) => { __injectCSSVars__();return __setup__(props, ctx) }
@ -37,8 +37,8 @@ const __default__ = {}
import { useCssVars as _useCssVars } from 'vue' import { useCssVars as _useCssVars } from 'vue'
const __injectCSSVars__ = () => { const __injectCSSVars__ = () => {
_useCssVars(_ctx => ({ _useCssVars(_ctx => ({
color: (_ctx.color) \\"xxxxxxxx-color\\": (_ctx.color)
}), \\"xxxxxxxx\\")} }))}
const __setup__ = __default__.setup const __setup__ = __default__.setup
__default__.setup = __setup__ __default__.setup = __setup__
? (props, ctx) => { __injectCSSVars__();return __setup__(props, ctx) } ? (props, ctx) => { __injectCSSVars__();return __setup__(props, ctx) }
@ -54,8 +54,8 @@ export default {
setup(__props) { setup(__props) {
_useCssVars(_ctx => ({ _useCssVars(_ctx => ({
color: (color) \\"xxxxxxxx-color\\": (color)
}), \\"xxxxxxxx\\") }))
const color = 'red' const color = 'red'
return { color } return { color }
} }
@ -69,9 +69,9 @@ const __default__ = {}
import { useCssVars as _useCssVars } from 'vue' import { useCssVars as _useCssVars } from 'vue'
const __injectCSSVars__ = () => { const __injectCSSVars__ = () => {
_useCssVars(_ctx => ({ _useCssVars(_ctx => ({
color: (_ctx.color), \\"xxxxxxxx-color\\": (_ctx.color),
font_size: (_ctx.font.size) \\"xxxxxxxx-font_size\\": (_ctx.font.size)
}), \\"xxxxxxxx\\")} }))}
const __setup__ = __default__.setup const __setup__ = __default__.setup
__default__.setup = __setup__ __default__.setup = __setup__
? (props, ctx) => { __injectCSSVars__();return __setup__(props, ctx) } ? (props, ctx) => { __injectCSSVars__();return __setup__(props, ctx) }
@ -91,10 +91,10 @@ export default {
setup(__props) { setup(__props) {
_useCssVars(_ctx => ({ _useCssVars(_ctx => ({
color: (color), \\"xxxxxxxx-color\\": (color),
size: (_unref(size)), \\"xxxxxxxx-size\\": (_unref(size)),
foo: (__props.foo) \\"xxxxxxxx-foo\\": (__props.foo)
}), \\"xxxxxxxx\\") }))
const color = 'red' const color = 'red'
const size = ref('10px') const size = ref('10px')

View File

@ -1,5 +1,5 @@
import { compileStyle } from '../src' import { compileStyle } from '../src'
import { compileSFCScript, assertCode } from './utils' import { mockId, compileSFCScript, assertCode } from './utils'
describe('CSS vars injection', () => { describe('CSS vars injection', () => {
test('generating correct code for nested paths', () => { test('generating correct code for nested paths', () => {
@ -11,8 +11,8 @@ describe('CSS vars injection', () => {
}</style>` }</style>`
) )
expect(content).toMatch(`_useCssVars(_ctx => ({ expect(content).toMatch(`_useCssVars(_ctx => ({
color: (_ctx.color), "${mockId}-color": (_ctx.color),
font_size: (_ctx.font.size) "${mockId}-font_size": (_ctx.font.size)
})`) })`)
assertCode(content) assertCode(content)
}) })
@ -42,9 +42,9 @@ describe('CSS vars injection', () => {
// 2. local potential ref bindings // 2. local potential ref bindings
// 3. props bindings (analyzed) // 3. props bindings (analyzed)
expect(content).toMatch(`_useCssVars(_ctx => ({ expect(content).toMatch(`_useCssVars(_ctx => ({
color: (color), "${mockId}-color": (color),
size: (_unref(size)), "${mockId}-size": (_unref(size)),
foo: (__props.foo) "${mockId}-foo": (__props.foo)
})`) })`)
expect(content).toMatch( expect(content).toMatch(
`import { useCssVars as _useCssVars, unref as _unref } from 'vue'` `import { useCssVars as _useCssVars, unref as _unref } from 'vue'`

View File

@ -2,6 +2,8 @@ import { parse, SFCScriptCompileOptions, compileScript } from '../src'
import { parse as babelParse } from '@babel/parser' import { parse as babelParse } from '@babel/parser'
import { babelParserDefaultPlugins } from '@vue/shared' import { babelParserDefaultPlugins } from '@vue/shared'
export const mockId = 'xxxxxxxx'
export function compileSFCScript( export function compileSFCScript(
src: string, src: string,
options?: Partial<SFCScriptCompileOptions> options?: Partial<SFCScriptCompileOptions>
@ -9,7 +11,7 @@ export function compileSFCScript(
const { descriptor } = parse(src) const { descriptor } = parse(src)
return compileScript(descriptor, { return compileScript(descriptor, {
...options, ...options,
id: 'xxxxxxxx' id: mockId
}) })
} }

View File

@ -52,7 +52,7 @@ export function genCssVarsCode(
id: string id: string
) { ) {
const varsExp = `{\n ${vars const varsExp = `{\n ${vars
.map(v => `${convertCssVarCasing(v)}: (${v})`) .map(v => `"${id}-${convertCssVarCasing(v)}": (${v})`)
.join(',\n ')}\n}` .join(',\n ')}\n}`
const exp = createSimpleExpression(varsExp, false) const exp = createSimpleExpression(varsExp, false)
const context = createTransformContext(createRoot([]), { const context = createTransformContext(createRoot([]), {
@ -72,7 +72,7 @@ export function genCssVarsCode(
}) })
.join('') .join('')
return `_${CSS_VARS_HELPER}(_ctx => (${transformedString}), "${id}")` return `_${CSS_VARS_HELPER}(_ctx => (${transformedString}))`
} }
// <script setup> already gets the calls injected as part of the transform // <script setup> already gets the calls injected as part of the transform

View File

@ -10,7 +10,6 @@ import {
} from '@vue/runtime-dom' } from '@vue/runtime-dom'
describe('useCssVars', () => { describe('useCssVars', () => {
const id = 'xxxxxx'
async function assertCssVars(getApp: (state: any) => ComponentOptions) { async function assertCssVars(getApp: (state: any) => ComponentOptions) {
const state = reactive({ color: 'red' }) const state = reactive({ color: 'red' })
const App = getApp(state) const App = getApp(state)
@ -19,17 +18,13 @@ describe('useCssVars', () => {
render(h(App), root) render(h(App), root)
await nextTick() await nextTick()
for (const c of [].slice.call(root.children as any)) { for (const c of [].slice.call(root.children as any)) {
expect((c as HTMLElement).style.getPropertyValue(`--${id}-color`)).toBe( expect((c as HTMLElement).style.getPropertyValue(`--color`)).toBe(`red`)
`red`
)
} }
state.color = 'green' state.color = 'green'
await nextTick() await nextTick()
for (const c of [].slice.call(root.children as any)) { for (const c of [].slice.call(root.children as any)) {
expect((c as HTMLElement).style.getPropertyValue(`--${id}-color`)).toBe( expect((c as HTMLElement).style.getPropertyValue(`--color`)).toBe('green')
'green'
)
} }
} }
@ -37,12 +32,9 @@ describe('useCssVars', () => {
await assertCssVars(state => ({ await assertCssVars(state => ({
setup() { setup() {
// test receiving render context // test receiving render context
useCssVars( useCssVars((ctx: any) => ({
(ctx: any) => ({
color: ctx.color color: ctx.color
}), }))
id
)
return state return state
}, },
render() { render() {
@ -54,7 +46,7 @@ describe('useCssVars', () => {
test('on fragment root', async () => { test('on fragment root', async () => {
await assertCssVars(state => ({ await assertCssVars(state => ({
setup() { setup() {
useCssVars(() => state, id) useCssVars(() => state)
return () => [h('div'), h('div')] return () => [h('div'), h('div')]
} }
})) }))
@ -65,7 +57,7 @@ describe('useCssVars', () => {
await assertCssVars(state => ({ await assertCssVars(state => ({
setup() { setup() {
useCssVars(() => state, id) useCssVars(() => state)
return () => h(Child) return () => h(Child)
} }
})) }))
@ -91,7 +83,7 @@ describe('useCssVars', () => {
const App = { const App = {
setup() { setup() {
useCssVars(() => state, id) useCssVars(() => state)
return () => return () =>
h(Suspense, null, { h(Suspense, null, {
default: h(AsyncComp), default: h(AsyncComp),
@ -104,9 +96,7 @@ describe('useCssVars', () => {
await nextTick() await nextTick()
// css vars use with fallback tree // css vars use with fallback tree
for (const c of [].slice.call(root.children as any)) { for (const c of [].slice.call(root.children as any)) {
expect((c as HTMLElement).style.getPropertyValue(`--${id}-color`)).toBe( expect((c as HTMLElement).style.getPropertyValue(`--color`)).toBe(`red`)
`red`
)
} }
// AsyncComp resolve // AsyncComp resolve
resolveAsync() resolveAsync()
@ -115,30 +105,16 @@ describe('useCssVars', () => {
await nextTick() await nextTick()
// css vars use with default tree // css vars use with default tree
for (const c of [].slice.call(root.children as any)) { for (const c of [].slice.call(root.children as any)) {
expect((c as HTMLElement).style.getPropertyValue(`--${id}-color`)).toBe( expect((c as HTMLElement).style.getPropertyValue(`--color`)).toBe(`red`)
`red`
)
} }
state.color = 'green' state.color = 'green'
await nextTick() await nextTick()
for (const c of [].slice.call(root.children as any)) { for (const c of [].slice.call(root.children as any)) {
expect((c as HTMLElement).style.getPropertyValue(`--${id}-color`)).toBe( expect((c as HTMLElement).style.getPropertyValue(`--color`)).toBe('green')
'green'
)
} }
}) })
test('with <style scoped>', async () => {
await assertCssVars(state => ({
__scopeId: id,
setup() {
useCssVars(() => state, id)
return () => h('div')
}
}))
})
test('with subTree changed', async () => { test('with subTree changed', async () => {
const state = reactive({ color: 'red' }) const state = reactive({ color: 'red' })
const value = ref(true) const value = ref(true)
@ -146,7 +122,7 @@ describe('useCssVars', () => {
const App = { const App = {
setup() { setup() {
useCssVars(() => state, id) useCssVars(() => state)
return () => (value.value ? [h('div')] : [h('div'), h('div')]) return () => (value.value ? [h('div')] : [h('div'), h('div')])
} }
} }
@ -155,17 +131,13 @@ describe('useCssVars', () => {
await nextTick() await nextTick()
// css vars use with fallback tree // css vars use with fallback tree
for (const c of [].slice.call(root.children as any)) { for (const c of [].slice.call(root.children as any)) {
expect((c as HTMLElement).style.getPropertyValue(`--${id}-color`)).toBe( expect((c as HTMLElement).style.getPropertyValue(`--color`)).toBe(`red`)
`red`
)
} }
value.value = false value.value = false
await nextTick() await nextTick()
for (const c of [].slice.call(root.children as any)) { for (const c of [].slice.call(root.children as any)) {
expect((c as HTMLElement).style.getPropertyValue(`--${id}-color`)).toBe( expect((c as HTMLElement).style.getPropertyValue(`--color`)).toBe('red')
'red'
)
} }
}) })
}) })

View File

@ -15,8 +15,7 @@ import { ShapeFlags } from '@vue/shared'
* @private * @private
*/ */
export function useCssVars( export function useCssVars(
getter: (ctx: ComponentPublicInstance) => Record<string, string>, getter: (ctx: ComponentPublicInstance) => Record<string, string>
scopeId: string
) { ) {
const instance = getCurrentInstance() const instance = getCurrentInstance()
/* istanbul ignore next */ /* istanbul ignore next */
@ -27,22 +26,18 @@ export function useCssVars(
} }
const setVars = () => const setVars = () =>
setVarsOnVNode(instance.subTree, getter(instance.proxy!), scopeId) setVarsOnVNode(instance.subTree, getter(instance.proxy!))
onMounted(() => watchEffect(setVars, { flush: 'post' })) onMounted(() => watchEffect(setVars, { flush: 'post' }))
onUpdated(setVars) onUpdated(setVars)
} }
function setVarsOnVNode( function setVarsOnVNode(vnode: VNode, vars: Record<string, string>) {
vnode: VNode,
vars: Record<string, string>,
scopeId: string
) {
if (__FEATURE_SUSPENSE__ && vnode.shapeFlag & ShapeFlags.SUSPENSE) { if (__FEATURE_SUSPENSE__ && vnode.shapeFlag & ShapeFlags.SUSPENSE) {
const suspense = vnode.suspense! const suspense = vnode.suspense!
vnode = suspense.activeBranch! vnode = suspense.activeBranch!
if (suspense.pendingBranch && !suspense.isHydrating) { if (suspense.pendingBranch && !suspense.isHydrating) {
suspense.effects.push(() => { suspense.effects.push(() => {
setVarsOnVNode(suspense.activeBranch!, vars, scopeId) setVarsOnVNode(suspense.activeBranch!, vars)
}) })
} }
} }
@ -55,9 +50,9 @@ function setVarsOnVNode(
if (vnode.shapeFlag & ShapeFlags.ELEMENT && vnode.el) { if (vnode.shapeFlag & ShapeFlags.ELEMENT && vnode.el) {
const style = vnode.el.style const style = vnode.el.style
for (const key in vars) { for (const key in vars) {
style.setProperty(`--${scopeId}-${key}`, vars[key]) style.setProperty(`--${key}`, vars[key])
} }
} else if (vnode.type === Fragment) { } else if (vnode.type === Fragment) {
;(vnode.children as VNode[]).forEach(c => setVarsOnVNode(c, vars, scopeId)) ;(vnode.children as VNode[]).forEach(c => setVarsOnVNode(c, vars))
} }
} }