refactor: reuse parseStringStyle across compiler and runtime

This commit is contained in:
Evan You
2020-05-06 11:22:49 -04:00
parent 2d9f136077
commit 8df6bc0132
3 changed files with 28 additions and 33 deletions

View File

@@ -1,14 +1,16 @@
import { isArray, isString, isObject, hyphenate } from './'
import { isNoUnitNumericStyleProp } from './domAttrConfig'
export function normalizeStyle(
value: unknown
): Record<string, string | number> | undefined {
export type NormalizedStyle = Record<string, string | number>
export function normalizeStyle(value: unknown): NormalizedStyle | undefined {
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)
const item = value[i]
const normalized = normalizeStyle(
isString(item) ? parseStringStyle(item) : item
)
if (normalized) {
for (const key in normalized) {
res[key] = normalized[key]
@@ -21,21 +23,21 @@ export function normalizeStyle(
}
}
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)
})
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())
}
})
return ret
}
export function stringifyStyle(
styles: Record<string, string | number> | undefined
): string {
export function stringifyStyle(styles: NormalizedStyle | undefined): string {
let ret = ''
if (!styles) {
return ret