normalizeProp.ts 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import { isArray, isString, isObject, hyphenate } from './'
  2. import { isNoUnitNumericStyleProp } from './domAttrConfig'
  3. export function normalizeStyle(
  4. value: unknown
  5. ): Record<string, string | number> | undefined {
  6. if (isArray(value)) {
  7. const res: Record<string, string | number> = {}
  8. for (let i = 0; i < value.length; i++) {
  9. const normalized = normalizeStyle(value[i])
  10. if (normalized) {
  11. for (const key in normalized) {
  12. res[key] = normalized[key]
  13. }
  14. }
  15. }
  16. return res
  17. } else if (isObject(value)) {
  18. return value
  19. }
  20. }
  21. export function stringifyStyle(
  22. styles: Record<string, string | number> | undefined
  23. ): string {
  24. let ret = ''
  25. if (!styles) {
  26. return ret
  27. }
  28. for (const key in styles) {
  29. const value = styles[key]
  30. const normalizedKey = key.indexOf(`--`) === 0 ? key : hyphenate(key)
  31. if (
  32. isString(value) ||
  33. (typeof value === 'number' && isNoUnitNumericStyleProp(normalizedKey))
  34. ) {
  35. // only render valid values
  36. ret += `${normalizedKey}:${value};`
  37. }
  38. }
  39. return ret
  40. }
  41. export function normalizeClass(value: unknown): string {
  42. let res = ''
  43. if (isString(value)) {
  44. res = value
  45. } else if (isArray(value)) {
  46. for (let i = 0; i < value.length; i++) {
  47. res += normalizeClass(value[i]) + ' '
  48. }
  49. } else if (isObject(value)) {
  50. for (const name in value) {
  51. if (value[name]) {
  52. res += name + ' '
  53. }
  54. }
  55. }
  56. return res.trim()
  57. }