style.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /* @flow */
  2. import { cached, extend, toObject } from 'shared/util'
  3. export const parseStyleText = cached(function (cssText) {
  4. const res = {}
  5. const listDelimiter = /;(?![^(]*\))/g
  6. const propertyDelimiter = /:(.+)/
  7. cssText.split(listDelimiter).forEach(function (item) {
  8. if (item) {
  9. var tmp = item.split(propertyDelimiter)
  10. tmp.length > 1 && (res[tmp[0].trim()] = tmp[1].trim())
  11. }
  12. })
  13. return res
  14. })
  15. // merge static and dynamic style data on the same vnode
  16. function normalizeStyleData (data: VNodeData): ?Object {
  17. const style = normalizeStyleBinding(data.style)
  18. // static style is pre-processed into an object during compilation
  19. // and is always a fresh object, so it's safe to merge into it
  20. return data.staticStyle
  21. ? extend(data.staticStyle, style)
  22. : style
  23. }
  24. // normalize possible array / string values into Object
  25. export function normalizeStyleBinding (bindingStyle: any): ?Object {
  26. if (Array.isArray(bindingStyle)) {
  27. return toObject(bindingStyle)
  28. }
  29. if (typeof bindingStyle === 'string') {
  30. return parseStyleText(bindingStyle)
  31. }
  32. return bindingStyle
  33. }
  34. /**
  35. * parent component style should be after child's
  36. * so that parent component's style could override it
  37. */
  38. export function getStyle (vnode: VNode, checkChild: boolean): Object {
  39. const res = {}
  40. let styleData
  41. if (checkChild) {
  42. let childNode = vnode
  43. while (childNode.child) {
  44. childNode = childNode.child._vnode
  45. if (childNode.data && (styleData = normalizeStyleData(childNode.data))) {
  46. extend(res, styleData)
  47. }
  48. }
  49. }
  50. if ((styleData = normalizeStyleData(vnode.data))) {
  51. extend(res, styleData)
  52. }
  53. let parentNode = vnode
  54. while ((parentNode = parentNode.parent)) {
  55. if (parentNode.data && (styleData = normalizeStyleData(parentNode.data))) {
  56. extend(res, styleData)
  57. }
  58. }
  59. return res
  60. }