vnode.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  1. import {
  2. isArray,
  3. isFunction,
  4. isString,
  5. isObject,
  6. EMPTY_ARR,
  7. extend,
  8. normalizeClass,
  9. normalizeStyle,
  10. PatchFlags,
  11. ShapeFlags
  12. } from '@vue/shared'
  13. import {
  14. ComponentInternalInstance,
  15. Data,
  16. Component,
  17. ClassComponent
  18. } from './component'
  19. import { RawSlots } from './componentSlots'
  20. import { isProxy, Ref, toRaw } from '@vue/reactivity'
  21. import { AppContext } from './apiCreateApp'
  22. import {
  23. SuspenseImpl,
  24. isSuspense,
  25. SuspenseBoundary
  26. } from './components/Suspense'
  27. import { DirectiveBinding } from './directives'
  28. import { TransitionHooks } from './components/BaseTransition'
  29. import { warn } from './warning'
  30. import { currentScopeId } from './helpers/scopeId'
  31. import { TeleportImpl, isTeleport } from './components/Teleport'
  32. import { currentRenderingInstance } from './componentRenderUtils'
  33. import { RendererNode, RendererElement } from './renderer'
  34. export const Fragment = (Symbol(__DEV__ ? 'Fragment' : undefined) as any) as {
  35. __isFragment: true
  36. new (): {
  37. $props: VNodeProps
  38. }
  39. }
  40. export const Text = Symbol(__DEV__ ? 'Text' : undefined)
  41. export const Comment = Symbol(__DEV__ ? 'Comment' : undefined)
  42. export const Static = Symbol(__DEV__ ? 'Static' : undefined)
  43. export type VNodeTypes =
  44. | string
  45. | Component
  46. | typeof Text
  47. | typeof Static
  48. | typeof Comment
  49. | typeof Fragment
  50. | typeof TeleportImpl
  51. | typeof SuspenseImpl
  52. export type VNodeRef =
  53. | string
  54. | Ref
  55. | ((ref: object | null, refs: Record<string, any>) => void)
  56. export type VNodeNormalizedRef = [ComponentInternalInstance, VNodeRef]
  57. type VNodeMountHook = (vnode: VNode) => void
  58. type VNodeUpdateHook = (vnode: VNode, oldVNode: VNode) => void
  59. export type VNodeHook =
  60. | VNodeMountHook
  61. | VNodeUpdateHook
  62. | VNodeMountHook[]
  63. | VNodeUpdateHook[]
  64. export interface VNodeProps {
  65. [key: string]: any
  66. key?: string | number
  67. ref?: VNodeRef
  68. // vnode hooks
  69. onVnodeBeforeMount?: VNodeMountHook | VNodeMountHook[]
  70. onVnodeMounted?: VNodeMountHook | VNodeMountHook[]
  71. onVnodeBeforeUpdate?: VNodeUpdateHook | VNodeUpdateHook[]
  72. onVnodeUpdated?: VNodeUpdateHook | VNodeUpdateHook[]
  73. onVnodeBeforeUnmount?: VNodeMountHook | VNodeMountHook[]
  74. onVnodeUnmounted?: VNodeMountHook | VNodeMountHook[]
  75. }
  76. type VNodeChildAtom = VNode | string | number | boolean | null | void
  77. export interface VNodeArrayChildren<
  78. HostNode = RendererNode,
  79. HostElement = RendererElement
  80. > extends Array<VNodeArrayChildren | VNodeChildAtom> {}
  81. export type VNodeChild = VNodeChildAtom | VNodeArrayChildren
  82. export type VNodeNormalizedChildren =
  83. | string
  84. | VNodeArrayChildren
  85. | RawSlots
  86. | null
  87. export interface VNode<HostNode = RendererNode, HostElement = RendererElement> {
  88. _isVNode: true
  89. type: VNodeTypes
  90. props: VNodeProps | null
  91. key: string | number | null
  92. ref: VNodeNormalizedRef | null
  93. scopeId: string | null // SFC only
  94. children: VNodeNormalizedChildren
  95. component: ComponentInternalInstance | null
  96. suspense: SuspenseBoundary | null
  97. dirs: DirectiveBinding[] | null
  98. transition: TransitionHooks | null
  99. // DOM
  100. el: HostNode | null
  101. anchor: HostNode | null // fragment anchor
  102. target: HostElement | null // teleport target
  103. targetAnchor: HostNode | null // teleport target anchor
  104. // optimization only
  105. shapeFlag: number
  106. patchFlag: number
  107. dynamicProps: string[] | null
  108. dynamicChildren: VNode[] | null
  109. // application root node only
  110. appContext: AppContext | null
  111. }
  112. // Since v-if and v-for are the two possible ways node structure can dynamically
  113. // change, once we consider v-if branches and each v-for fragment a block, we
  114. // can divide a template into nested blocks, and within each block the node
  115. // structure would be stable. This allows us to skip most children diffing
  116. // and only worry about the dynamic nodes (indicated by patch flags).
  117. const blockStack: (VNode[] | null)[] = []
  118. let currentBlock: VNode[] | null = null
  119. // Open a block.
  120. // This must be called before `createBlock`. It cannot be part of `createBlock`
  121. // because the children of the block are evaluated before `createBlock` itself
  122. // is called. The generated code typically looks like this:
  123. //
  124. // function render() {
  125. // return (openBlock(),createBlock('div', null, [...]))
  126. // }
  127. //
  128. // disableTracking is true when creating a fragment block, since a fragment
  129. // always diffs its children.
  130. export function openBlock(disableTracking = false) {
  131. blockStack.push((currentBlock = disableTracking ? null : []))
  132. }
  133. // Whether we should be tracking dynamic child nodes inside a block.
  134. // Only tracks when this value is > 0
  135. // We are not using a simple boolean because this value may need to be
  136. // incremented/decremented by nested usage of v-once (see below)
  137. let shouldTrack = 1
  138. // Block tracking sometimes needs to be disabled, for example during the
  139. // creation of a tree that needs to be cached by v-once. The compiler generates
  140. // code like this:
  141. // _cache[1] || (
  142. // setBlockTracking(-1),
  143. // _cache[1] = createVNode(...),
  144. // setBlockTracking(1),
  145. // _cache[1]
  146. // )
  147. export function setBlockTracking(value: number) {
  148. shouldTrack += value
  149. }
  150. // Create a block root vnode. Takes the same exact arguments as `createVNode`.
  151. // A block root keeps track of dynamic nodes within the block in the
  152. // `dynamicChildren` array.
  153. export function createBlock(
  154. type: VNodeTypes | ClassComponent,
  155. props?: { [key: string]: any } | null,
  156. children?: any,
  157. patchFlag?: number,
  158. dynamicProps?: string[]
  159. ): VNode {
  160. const vnode = createVNode(
  161. type,
  162. props,
  163. children,
  164. patchFlag,
  165. dynamicProps,
  166. true /* isBlock: prevent a block from tracking itself */
  167. )
  168. // save current block children on the block vnode
  169. vnode.dynamicChildren = currentBlock || EMPTY_ARR
  170. // close block
  171. blockStack.pop()
  172. currentBlock = blockStack[blockStack.length - 1] || null
  173. // a block is always going to be patched, so track it as a child of its
  174. // parent block
  175. if (currentBlock) {
  176. currentBlock.push(vnode)
  177. }
  178. return vnode
  179. }
  180. export function isVNode(value: any): value is VNode {
  181. return value ? value._isVNode === true : false
  182. }
  183. export function isSameVNodeType(n1: VNode, n2: VNode): boolean {
  184. if (
  185. __DEV__ &&
  186. n2.shapeFlag & ShapeFlags.COMPONENT &&
  187. (n2.type as Component).__hmrUpdated
  188. ) {
  189. // HMR only: if the component has been hot-updated, force a reload.
  190. return false
  191. }
  192. return n1.type === n2.type && n1.key === n2.key
  193. }
  194. let vnodeArgsTransformer:
  195. | ((
  196. args: Parameters<typeof _createVNode>,
  197. instance: ComponentInternalInstance | null
  198. ) => Parameters<typeof _createVNode>)
  199. | undefined
  200. // Internal API for registering an arguments transform for createVNode
  201. // used for creating stubs in the test-utils
  202. export function transformVNodeArgs(transformer?: typeof vnodeArgsTransformer) {
  203. vnodeArgsTransformer = transformer
  204. }
  205. const createVNodeWithArgsTransform = (
  206. ...args: Parameters<typeof _createVNode>
  207. ): VNode => {
  208. return _createVNode(
  209. ...(vnodeArgsTransformer
  210. ? vnodeArgsTransformer(args, currentRenderingInstance)
  211. : args)
  212. )
  213. }
  214. export const InternalObjectKey = `__vInternal`
  215. export const createVNode = (__DEV__
  216. ? createVNodeWithArgsTransform
  217. : _createVNode) as typeof _createVNode
  218. function _createVNode(
  219. type: VNodeTypes | ClassComponent,
  220. props: (Data & VNodeProps) | null = null,
  221. children: unknown = null,
  222. patchFlag: number = 0,
  223. dynamicProps: string[] | null = null,
  224. isBlockNode = false
  225. ): VNode {
  226. if (!type) {
  227. if (__DEV__) {
  228. warn(`Invalid vnode type when creating vnode: ${type}.`)
  229. }
  230. type = Comment
  231. }
  232. // class component normalization.
  233. if (isFunction(type) && '__vccOpts' in type) {
  234. type = type.__vccOpts
  235. }
  236. // class & style normalization.
  237. if (props) {
  238. // for reactive or proxy objects, we need to clone it to enable mutation.
  239. if (isProxy(props) || InternalObjectKey in props) {
  240. props = extend({}, props)
  241. }
  242. let { class: klass, style } = props
  243. if (klass && !isString(klass)) {
  244. props.class = normalizeClass(klass)
  245. }
  246. if (isObject(style)) {
  247. // reactive state objects need to be cloned since they are likely to be
  248. // mutated
  249. if (isProxy(style) && !isArray(style)) {
  250. style = extend({}, style)
  251. }
  252. props.style = normalizeStyle(style)
  253. }
  254. }
  255. // encode the vnode type information into a bitmap
  256. const shapeFlag = isString(type)
  257. ? ShapeFlags.ELEMENT
  258. : __FEATURE_SUSPENSE__ && isSuspense(type)
  259. ? ShapeFlags.SUSPENSE
  260. : isTeleport(type)
  261. ? ShapeFlags.TELEPORT
  262. : isObject(type)
  263. ? ShapeFlags.STATEFUL_COMPONENT
  264. : isFunction(type)
  265. ? ShapeFlags.FUNCTIONAL_COMPONENT
  266. : 0
  267. if (__DEV__ && shapeFlag & ShapeFlags.STATEFUL_COMPONENT && isProxy(type)) {
  268. type = toRaw(type)
  269. warn(
  270. `Vue received a Component which was made a reactive object. This can ` +
  271. `lead to unnecessary performance overhead, and should be avoided by ` +
  272. `marking the component with \`markRaw\` or using \`shallowRef\` ` +
  273. `instead of \`ref\`.`,
  274. `\nComponent that was made reactive: `,
  275. type
  276. )
  277. }
  278. const vnode: VNode = {
  279. _isVNode: true,
  280. type,
  281. props,
  282. key: props && props.key !== undefined ? props.key : null,
  283. ref:
  284. props && props.ref !== undefined
  285. ? [currentRenderingInstance!, props.ref]
  286. : null,
  287. scopeId: currentScopeId,
  288. children: null,
  289. component: null,
  290. suspense: null,
  291. dirs: null,
  292. transition: null,
  293. el: null,
  294. anchor: null,
  295. target: null,
  296. targetAnchor: null,
  297. shapeFlag,
  298. patchFlag,
  299. dynamicProps,
  300. dynamicChildren: null,
  301. appContext: null
  302. }
  303. normalizeChildren(vnode, children)
  304. // presence of a patch flag indicates this node needs patching on updates.
  305. // component nodes also should always be patched, because even if the
  306. // component doesn't need to update, it needs to persist the instance on to
  307. // the next vnode so that it can be properly unmounted later.
  308. if (
  309. shouldTrack > 0 &&
  310. !isBlockNode &&
  311. currentBlock &&
  312. // the EVENTS flag is only for hydration and if it is the only flag, the
  313. // vnode should not be considered dynamic due to handler caching.
  314. patchFlag !== PatchFlags.HYDRATE_EVENTS &&
  315. (patchFlag > 0 ||
  316. shapeFlag & ShapeFlags.SUSPENSE ||
  317. shapeFlag & ShapeFlags.STATEFUL_COMPONENT ||
  318. shapeFlag & ShapeFlags.FUNCTIONAL_COMPONENT)
  319. ) {
  320. currentBlock.push(vnode)
  321. }
  322. return vnode
  323. }
  324. export function cloneVNode<T, U>(
  325. vnode: VNode<T, U>,
  326. extraProps?: Data & VNodeProps
  327. ): VNode<T, U> {
  328. // This is intentionally NOT using spread or extend to avoid the runtime
  329. // key enumeration cost.
  330. return {
  331. _isVNode: true,
  332. type: vnode.type,
  333. props: extraProps
  334. ? vnode.props
  335. ? mergeProps(vnode.props, extraProps)
  336. : extend({}, extraProps)
  337. : vnode.props,
  338. key: vnode.key,
  339. ref: vnode.ref,
  340. scopeId: vnode.scopeId,
  341. children: vnode.children,
  342. target: vnode.target,
  343. targetAnchor: vnode.targetAnchor,
  344. shapeFlag: vnode.shapeFlag,
  345. patchFlag: vnode.patchFlag,
  346. dynamicProps: vnode.dynamicProps,
  347. dynamicChildren: vnode.dynamicChildren,
  348. appContext: vnode.appContext,
  349. dirs: vnode.dirs,
  350. transition: vnode.transition,
  351. // These should technically only be non-null on mounted VNodes. However,
  352. // they *should* be copied for kept-alive vnodes. So we just always copy
  353. // them since them being non-null during a mount doesn't affect the logic as
  354. // they will simply be overwritten.
  355. component: vnode.component,
  356. suspense: vnode.suspense,
  357. el: vnode.el,
  358. anchor: vnode.anchor
  359. }
  360. }
  361. export function createTextVNode(text: string = ' ', flag: number = 0): VNode {
  362. return createVNode(Text, null, text, flag)
  363. }
  364. export function createStaticVNode(content: string): VNode {
  365. return createVNode(Static, null, content)
  366. }
  367. export function createCommentVNode(
  368. text: string = '',
  369. // when used as the v-else branch, the comment node must be created as a
  370. // block to ensure correct updates.
  371. asBlock: boolean = false
  372. ): VNode {
  373. return asBlock
  374. ? (openBlock(), createBlock(Comment, null, text))
  375. : createVNode(Comment, null, text)
  376. }
  377. export function normalizeVNode(child: VNodeChild): VNode {
  378. if (child == null || typeof child === 'boolean') {
  379. // empty placeholder
  380. return createVNode(Comment)
  381. } else if (isArray(child)) {
  382. // fragment
  383. return createVNode(Fragment, null, child)
  384. } else if (typeof child === 'object') {
  385. // already vnode, this should be the most common since compiled templates
  386. // always produce all-vnode children arrays
  387. return child.el === null ? child : cloneVNode(child)
  388. } else {
  389. // strings and numbers
  390. return createVNode(Text, null, String(child))
  391. }
  392. }
  393. // optimized normalization for template-compiled render fns
  394. export function cloneIfMounted(child: VNode): VNode {
  395. return child.el === null ? child : cloneVNode(child)
  396. }
  397. export function normalizeChildren(vnode: VNode, children: unknown) {
  398. let type = 0
  399. const { shapeFlag } = vnode
  400. if (children == null) {
  401. children = null
  402. } else if (isArray(children)) {
  403. type = ShapeFlags.ARRAY_CHILDREN
  404. } else if (typeof children === 'object') {
  405. // Normalize slot to plain children
  406. if (
  407. (shapeFlag & ShapeFlags.ELEMENT || shapeFlag & ShapeFlags.TELEPORT) &&
  408. (children as any).default
  409. ) {
  410. normalizeChildren(vnode, (children as any).default())
  411. return
  412. } else {
  413. type = ShapeFlags.SLOTS_CHILDREN
  414. if (!(children as RawSlots)._ && !(InternalObjectKey in children!)) {
  415. // if slots are not normalized, attach context instance
  416. // (compiled / normalized slots already have context)
  417. ;(children as RawSlots)._ctx = currentRenderingInstance
  418. }
  419. }
  420. } else if (isFunction(children)) {
  421. children = { default: children, _ctx: currentRenderingInstance }
  422. type = ShapeFlags.SLOTS_CHILDREN
  423. } else {
  424. children = String(children)
  425. // force teleport children to array so it can be moved around
  426. if (shapeFlag & ShapeFlags.TELEPORT) {
  427. type = ShapeFlags.ARRAY_CHILDREN
  428. children = [createTextVNode(children as string)]
  429. } else {
  430. type = ShapeFlags.TEXT_CHILDREN
  431. }
  432. }
  433. vnode.children = children as VNodeNormalizedChildren
  434. vnode.shapeFlag |= type
  435. }
  436. const handlersRE = /^on|^vnode/
  437. export function mergeProps(...args: (Data & VNodeProps)[]) {
  438. const ret: Data = {}
  439. extend(ret, args[0])
  440. for (let i = 1; i < args.length; i++) {
  441. const toMerge = args[i]
  442. for (const key in toMerge) {
  443. if (key === 'class') {
  444. if (ret.class !== toMerge.class) {
  445. ret.class = normalizeClass([ret.class, toMerge.class])
  446. }
  447. } else if (key === 'style') {
  448. ret.style = normalizeStyle([ret.style, toMerge.style])
  449. } else if (handlersRE.test(key)) {
  450. // on*, vnode*
  451. const existing = ret[key]
  452. const incoming = toMerge[key]
  453. if (existing !== incoming) {
  454. ret[key] = existing
  455. ? [].concat(existing as any, toMerge[key] as any)
  456. : incoming
  457. }
  458. } else {
  459. ret[key] = toMerge[key]
  460. }
  461. }
  462. }
  463. return ret
  464. }