testUtils.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. import {
  2. NodeTypes,
  3. ElementNode,
  4. locStub,
  5. Namespaces,
  6. ElementTypes,
  7. VNodeCall
  8. } from '../src'
  9. import {
  10. isString,
  11. PatchFlags,
  12. PatchFlagNames,
  13. isArray,
  14. ShapeFlags
  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. isSelfClosing: false,
  57. props: [],
  58. children: [],
  59. codegenNode: {
  60. type: NodeTypes.VNODE_CALL,
  61. tag,
  62. props,
  63. children,
  64. patchFlag,
  65. dynamicProps,
  66. directives: undefined,
  67. isBlock: false,
  68. disableTracking: false,
  69. isComponent: false,
  70. loc: locStub
  71. }
  72. }
  73. }
  74. type Flags = PatchFlags | ShapeFlags
  75. export function genFlagText(
  76. flag: Flags | Flags[],
  77. names: { [k: number]: string } = PatchFlagNames
  78. ) {
  79. if (isArray(flag)) {
  80. let f = 0
  81. flag.forEach(ff => {
  82. f |= ff
  83. })
  84. return `${f} /* ${flag.map(f => names[f]).join(', ')} */`
  85. } else {
  86. return `${flag} /* ${names[flag]} */`
  87. }
  88. }