testUtils.ts 2.1 KB

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