testUtils.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. import {
  2. type ElementNode,
  3. ElementTypes,
  4. Namespaces,
  5. NodeTypes,
  6. type Property,
  7. type SimpleExpressionNode,
  8. type VNodeCall,
  9. locStub,
  10. } from '../src'
  11. import {
  12. PatchFlagNames,
  13. type PatchFlags,
  14. type ShapeFlags,
  15. isArray,
  16. isString,
  17. } from '@vue/shared'
  18. const leadingBracketRE = /^\[/
  19. const bracketsRE = /^\[|\]$/g
  20. // Create a matcher for an object
  21. // where non-static expressions should be wrapped in []
  22. // e.g.
  23. // - createObjectMatcher({ 'foo': '[bar]' }) matches { foo: bar }
  24. // - createObjectMatcher({ '[foo]': 'bar' }) matches { [foo]: "bar" }
  25. export function createObjectMatcher(obj: Record<string, any>): {
  26. type: NodeTypes
  27. properties: Partial<Property>[]
  28. } {
  29. return {
  30. type: NodeTypes.JS_OBJECT_EXPRESSION,
  31. properties: Object.keys(obj).map(key => ({
  32. type: NodeTypes.JS_PROPERTY,
  33. key: {
  34. type: NodeTypes.SIMPLE_EXPRESSION,
  35. content: key.replace(bracketsRE, ''),
  36. isStatic: !leadingBracketRE.test(key),
  37. } as SimpleExpressionNode,
  38. value: isString(obj[key])
  39. ? {
  40. type: NodeTypes.SIMPLE_EXPRESSION,
  41. content: obj[key].replace(bracketsRE, ''),
  42. isStatic: !leadingBracketRE.test(obj[key]),
  43. }
  44. : obj[key],
  45. })),
  46. }
  47. }
  48. export function createElementWithCodegen(
  49. tag: VNodeCall['tag'],
  50. props?: VNodeCall['props'],
  51. children?: VNodeCall['children'],
  52. patchFlag?: VNodeCall['patchFlag'],
  53. dynamicProps?: VNodeCall['dynamicProps'],
  54. ): ElementNode {
  55. return {
  56. type: NodeTypes.ELEMENT,
  57. loc: locStub,
  58. ns: Namespaces.HTML,
  59. tag: 'div',
  60. tagType: ElementTypes.ELEMENT,
  61. props: [],
  62. children: [],
  63. codegenNode: {
  64. type: NodeTypes.VNODE_CALL,
  65. tag,
  66. props,
  67. children,
  68. patchFlag,
  69. dynamicProps,
  70. directives: undefined,
  71. isBlock: false,
  72. disableTracking: false,
  73. isComponent: false,
  74. loc: locStub,
  75. },
  76. }
  77. }
  78. type Flags = PatchFlags | ShapeFlags
  79. export function genFlagText(
  80. flag: Flags | Flags[],
  81. names: { [k: number]: string } = PatchFlagNames,
  82. ): string {
  83. if (isArray(flag)) {
  84. let f = 0
  85. flag.forEach(ff => {
  86. f |= ff
  87. })
  88. return `${f} /* ${flag.map(f => names[f]).join(', ')} */`
  89. } else {
  90. return `${flag} /* ${names[flag]} */`
  91. }
  92. }