vue3-core/packages/shared/src/normalizeProp.ts

74 lines
1.8 KiB
TypeScript
Raw Normal View History

import { isArray, isString, isObject, hyphenate } from './'
import { isNoUnitNumericStyleProp } from './domAttrConfig'
2020-01-28 06:23:42 +08:00
export function normalizeStyle(
value: unknown
2020-01-29 07:48:27 +08:00
): Record<string, string | number> | undefined {
2020-01-28 06:23:42 +08:00
if (isArray(value)) {
const res: Record<string, string | number> = {}
for (let i = 0; i < value.length; i++) {
const styles = isString(value[i]) ? strStyleToObj(value[i]) : value[i]
const normalized = normalizeStyle(styles)
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
}
}
function strStyleToObj(style: string) {
const ret: Record<string, string | number> = {}
style
.replace(/\s*/g, '')
.split(';')
.forEach((item: string) => {
const [key, val] = item.split(':')
ret[key] = isNaN(Number(val)) ? val : Number(val)
})
return ret
}
export function stringifyStyle(
styles: Record<string, string | number> | undefined
): string {
let ret = ''
if (!styles) {
return ret
}
for (const key in styles) {
const value = styles[key]
const normalizedKey = key.startsWith(`--`) ? key : hyphenate(key)
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++) {
res += normalizeClass(value[i]) + ' '
}
} else if (isObject(value)) {
for (const name in value) {
if (value[name]) {
res += name + ' '
}
}
}
return res.trim()
}