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(runtime-dom): useCssVars work with static vnode #3847

Merged
merged 3 commits into from
Jul 14, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions packages/runtime-dom/__tests__/helpers/useCssVars.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import {
ref,
render,
useCssVars,
createStaticVNode,
h,
reactive,
nextTick,
Expand Down Expand Up @@ -140,4 +141,26 @@ describe('useCssVars', () => {
expect((c as HTMLElement).style.getPropertyValue(`--color`)).toBe('red')
}
})

test('with createStaticVNode', async () => {
const state = reactive({ color: 'red' })
const root = document.createElement('div')

const App = {
setup() {
useCssVars(() => state)
return () => [
h('div'),
createStaticVNode('<div>1</div><div><span>2</span></div>', 2),
h('div')
]
}
}

render(h(App), root)
await nextTick()
for (const c of [].slice.call(root.children as any)) {
expect((c as HTMLElement).style.getPropertyValue(`--color`)).toBe('red')
}
})
})
21 changes: 21 additions & 0 deletions packages/runtime-dom/src/helpers/useCssVars.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
warn,
VNode,
Fragment,
Static,
onUpdated,
watchEffect
} from '@vue/runtime-core'
Expand Down Expand Up @@ -53,5 +54,25 @@ function setVarsOnVNode(vnode: VNode, vars: Record<string, string>) {
}
} else if (vnode.type === Fragment) {
;(vnode.children as VNode[]).forEach(c => setVarsOnVNode(c, vars))
} else if (vnode.type === Static) {
const { el, anchor } = vnode
let current: HTMLElement | null = el as HTMLElement
while (current) {
setVarsOnElement(current, vars)
if (current === anchor) break
current = current.nextSibling as HTMLElement
}
}

function setVarsOnElement(el: HTMLElement, vars: Record<string, string>) {
const style = el.style
for (const key in vars) {
style.setProperty(`--${key}`, vars[key])
}

for (var i = 0; i < el.children.length; i++) {
Copy link
Member

Choose a reason for hiding this comment

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

Deep recursion here is unnecessary - CSS vars only need to be set on root level elements.

Choose a reason for hiding this comment

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

🤔

const n = el.children[i]
setVarsOnElement(n as HTMLElement, vars)
}
}
}