2020-02-21 20:10:13 +08:00
|
|
|
import { isArray, isString, isObject, hyphenate } from './'
|
|
|
|
import { isNoUnitNumericStyleProp } from './domAttrConfig'
|
2020-01-28 06:23:42 +08:00
|
|
|
|
2020-05-06 23:22:49 +08:00
|
|
|
export type NormalizedStyle = Record<string, string | number>
|
|
|
|
|
|
|
|
export function normalizeStyle(value: unknown): NormalizedStyle | undefined {
|
2020-01-28 06:23:42 +08:00
|
|
|
if (isArray(value)) {
|
2021-04-01 11:29:24 +08:00
|
|
|
const res: NormalizedStyle = {}
|
2020-01-28 06:23:42 +08:00
|
|
|
for (let i = 0; i < value.length; i++) {
|
2020-05-06 23:22:49 +08:00
|
|
|
const item = value[i]
|
|
|
|
const normalized = normalizeStyle(
|
|
|
|
isString(item) ? parseStringStyle(item) : item
|
|
|
|
)
|
2020-01-28 06:23:42 +08:00
|
|
|
if (normalized) {
|
|
|
|
for (const key in normalized) {
|
|
|
|
res[key] = normalized[key]
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return res
|
|
|
|
} else if (isObject(value)) {
|
|
|
|
return value
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-05-06 23:22:49 +08:00
|
|
|
const listDelimiterRE = /;(?![^(]*\))/g
|
|
|
|
const propertyDelimiterRE = /:(.+)/
|
|
|
|
|
|
|
|
export function parseStringStyle(cssText: string): NormalizedStyle {
|
|
|
|
const ret: NormalizedStyle = {}
|
|
|
|
cssText.split(listDelimiterRE).forEach(item => {
|
|
|
|
if (item) {
|
|
|
|
const tmp = item.split(propertyDelimiterRE)
|
|
|
|
tmp.length > 1 && (ret[tmp[0].trim()] = tmp[1].trim())
|
|
|
|
}
|
|
|
|
})
|
2020-05-06 23:14:07 +08:00
|
|
|
return ret
|
|
|
|
}
|
|
|
|
|
2020-05-06 23:22:49 +08:00
|
|
|
export function stringifyStyle(styles: NormalizedStyle | undefined): string {
|
2020-02-21 20:10:13 +08:00
|
|
|
let ret = ''
|
|
|
|
if (!styles) {
|
|
|
|
return ret
|
|
|
|
}
|
|
|
|
for (const key in styles) {
|
|
|
|
const value = styles[key]
|
2020-04-21 03:44:20 +08:00
|
|
|
const normalizedKey = key.startsWith(`--`) ? key : hyphenate(key)
|
2020-02-21 20:10:13 +08:00
|
|
|
if (
|
|
|
|
isString(value) ||
|
|
|
|
(typeof value === 'number' && isNoUnitNumericStyleProp(normalizedKey))
|
|
|
|
) {
|
|
|
|
// only render valid values
|
|
|
|
ret += `${normalizedKey}:${value};`
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return ret
|
|
|
|
}
|
|
|
|
|
2020-01-28 06:23:42 +08:00
|
|
|
export function normalizeClass(value: unknown): string {
|
|
|
|
let res = ''
|
|
|
|
if (isString(value)) {
|
|
|
|
res = value
|
|
|
|
} else if (isArray(value)) {
|
|
|
|
for (let i = 0; i < value.length; i++) {
|
2021-02-04 21:41:46 +08:00
|
|
|
const normalized = normalizeClass(value[i])
|
|
|
|
if (normalized) {
|
|
|
|
res += normalized + ' '
|
|
|
|
}
|
2020-01-28 06:23:42 +08:00
|
|
|
}
|
|
|
|
} else if (isObject(value)) {
|
|
|
|
for (const name in value) {
|
|
|
|
if (value[name]) {
|
|
|
|
res += name + ' '
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return res.trim()
|
|
|
|
}
|