feat(runtime-dom/style): support CSS variables and auto prefixing
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
import { isString, hyphenate } from '@vue/shared'
|
||||
import { isString, hyphenate, capitalize } from '@vue/shared'
|
||||
import { camelize } from '@vue/runtime-core'
|
||||
|
||||
type Style = string | Partial<CSSStyleDeclaration> | null
|
||||
|
||||
@@ -25,16 +26,42 @@ export function patchStyle(el: Element, prev: Style, next: Style) {
|
||||
const importantRE = /\s*!important$/
|
||||
|
||||
function setStyle(style: CSSStyleDeclaration, name: string, val: string) {
|
||||
let rawName = hyphenate(name)
|
||||
if (importantRE.test(val)) {
|
||||
style.setProperty(rawName, val.replace(importantRE, ''), 'important')
|
||||
if (name.startsWith('--')) {
|
||||
// custom property definition
|
||||
style.setProperty(name, val)
|
||||
} else {
|
||||
/**
|
||||
* TODO:
|
||||
* 1. support values array created by autoprefixer.
|
||||
* 2. support css variable, maybe should import 'csstype'.
|
||||
* similar to https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react/index.d.ts#L1450
|
||||
*/
|
||||
style.setProperty(rawName, val)
|
||||
const prefixed = autoPrefix(style, name)
|
||||
if (importantRE.test(val)) {
|
||||
// !important
|
||||
style.setProperty(
|
||||
hyphenate(prefixed),
|
||||
val.replace(importantRE, ''),
|
||||
'important'
|
||||
)
|
||||
} else {
|
||||
style[prefixed as any] = val
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const prefixes = ['Webkit', 'Moz', 'ms']
|
||||
const prefixCache: Record<string, string> = {}
|
||||
|
||||
function autoPrefix(style: CSSStyleDeclaration, rawName: string): string {
|
||||
const cached = prefixCache[rawName]
|
||||
if (cached) {
|
||||
return cached
|
||||
}
|
||||
let name = camelize(rawName)
|
||||
if (name !== 'filter' && name in style) {
|
||||
return (prefixCache[rawName] = name)
|
||||
}
|
||||
name = capitalize(name)
|
||||
for (let i = 0; i < prefixes.length; i++) {
|
||||
const prefixed = prefixes[i] + name
|
||||
if (prefixed in style) {
|
||||
return (prefixCache[rawName] = prefixed)
|
||||
}
|
||||
}
|
||||
return rawName
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user