vnode.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860
  1. import {
  2. isArray,
  3. isFunction,
  4. isString,
  5. isObject,
  6. EMPTY_ARR,
  7. extend,
  8. normalizeClass,
  9. normalizeStyle,
  10. PatchFlags,
  11. ShapeFlags,
  12. SlotFlags,
  13. isOn,
  14. Data
  15. } from '@vue/shared'
  16. import {
  17. ComponentInternalInstance,
  18. ConcreteComponent,
  19. ClassComponent,
  20. Component,
  21. isClassComponent
  22. } from './component'
  23. import { RawSlots } from './componentSlots'
  24. import { isProxy, Ref, toRaw, ReactiveFlags, isRef } from '@vue/reactivity'
  25. import { AppContext } from './apiCreateApp'
  26. import {
  27. Suspense,
  28. SuspenseImpl,
  29. isSuspense,
  30. SuspenseBoundary
  31. } from './components/Suspense'
  32. import { DirectiveBinding } from './directives'
  33. import { TransitionHooks } from './components/BaseTransition'
  34. import { warn } from './warning'
  35. import { Teleport, TeleportImpl, isTeleport } from './components/Teleport'
  36. import {
  37. currentRenderingInstance,
  38. currentScopeId
  39. } from './componentRenderContext'
  40. import { RendererNode, RendererElement } from './renderer'
  41. import { NULL_DYNAMIC_COMPONENT } from './helpers/resolveAssets'
  42. import { hmrDirtyComponents } from './hmr'
  43. import { convertLegacyComponent } from './compat/component'
  44. import { convertLegacyVModelProps } from './compat/componentVModel'
  45. import { defineLegacyVNodeProperties } from './compat/renderFn'
  46. import { callWithAsyncErrorHandling, ErrorCodes } from './errorHandling'
  47. import { ComponentPublicInstance } from './componentPublicInstance'
  48. export const Fragment = Symbol.for('v-fgt') as any as {
  49. __isFragment: true
  50. new (): {
  51. $props: VNodeProps
  52. }
  53. }
  54. export const Text = Symbol.for('v-txt')
  55. export const Comment = Symbol.for('v-cmt')
  56. export const Static = Symbol.for('v-stc')
  57. export type VNodeTypes =
  58. | string
  59. | VNode
  60. | Component
  61. | typeof Text
  62. | typeof Static
  63. | typeof Comment
  64. | typeof Fragment
  65. | typeof Teleport
  66. | typeof TeleportImpl
  67. | typeof Suspense
  68. | typeof SuspenseImpl
  69. export type VNodeRef =
  70. | string
  71. | Ref
  72. | ((
  73. ref: Element | ComponentPublicInstance | null,
  74. refs: Record<string, any>
  75. ) => void)
  76. export type VNodeNormalizedRefAtom = {
  77. i: ComponentInternalInstance
  78. r: VNodeRef
  79. k?: string // setup ref key
  80. f?: boolean // refInFor marker
  81. }
  82. export type VNodeNormalizedRef =
  83. | VNodeNormalizedRefAtom
  84. | VNodeNormalizedRefAtom[]
  85. type VNodeMountHook = (vnode: VNode) => void
  86. type VNodeUpdateHook = (vnode: VNode, oldVNode: VNode) => void
  87. export type VNodeHook =
  88. | VNodeMountHook
  89. | VNodeUpdateHook
  90. | VNodeMountHook[]
  91. | VNodeUpdateHook[]
  92. // https://github.com/microsoft/TypeScript/issues/33099
  93. export type VNodeProps = {
  94. key?: string | number | symbol
  95. ref?: VNodeRef
  96. ref_for?: boolean
  97. ref_key?: string
  98. // vnode hooks
  99. onVnodeBeforeMount?: VNodeMountHook | VNodeMountHook[]
  100. onVnodeMounted?: VNodeMountHook | VNodeMountHook[]
  101. onVnodeBeforeUpdate?: VNodeUpdateHook | VNodeUpdateHook[]
  102. onVnodeUpdated?: VNodeUpdateHook | VNodeUpdateHook[]
  103. onVnodeBeforeUnmount?: VNodeMountHook | VNodeMountHook[]
  104. onVnodeUnmounted?: VNodeMountHook | VNodeMountHook[]
  105. }
  106. type VNodeChildAtom =
  107. | VNode
  108. | string
  109. | number
  110. | boolean
  111. | null
  112. | undefined
  113. | void
  114. export type VNodeArrayChildren = Array<VNodeArrayChildren | VNodeChildAtom>
  115. export type VNodeChild = VNodeChildAtom | VNodeArrayChildren
  116. export type VNodeNormalizedChildren =
  117. | string
  118. | VNodeArrayChildren
  119. | RawSlots
  120. | null
  121. export interface VNode<
  122. HostNode = RendererNode,
  123. HostElement = RendererElement,
  124. ExtraProps = { [key: string]: any }
  125. > {
  126. /**
  127. * @internal
  128. */
  129. __v_isVNode: true
  130. /**
  131. * @internal
  132. */
  133. [ReactiveFlags.SKIP]: true
  134. type: VNodeTypes
  135. props: (VNodeProps & ExtraProps) | null
  136. key: string | number | symbol | null
  137. ref: VNodeNormalizedRef | null
  138. /**
  139. * SFC only. This is assigned on vnode creation using currentScopeId
  140. * which is set alongside currentRenderingInstance.
  141. */
  142. scopeId: string | null
  143. /**
  144. * SFC only. This is assigned to:
  145. * - Slot fragment vnodes with :slotted SFC styles.
  146. * - Component vnodes (during patch/hydration) so that its root node can
  147. * inherit the component's slotScopeIds
  148. * @internal
  149. */
  150. slotScopeIds: string[] | null
  151. children: VNodeNormalizedChildren
  152. component: ComponentInternalInstance | null
  153. dirs: DirectiveBinding[] | null
  154. transition: TransitionHooks<HostElement> | null
  155. // DOM
  156. el: HostNode | null
  157. anchor: HostNode | null // fragment anchor
  158. target: HostElement | null // teleport target
  159. targetAnchor: HostNode | null // teleport target anchor
  160. /**
  161. * number of elements contained in a static vnode
  162. * @internal
  163. */
  164. staticCount: number
  165. // suspense
  166. suspense: SuspenseBoundary | null
  167. /**
  168. * @internal
  169. */
  170. ssContent: VNode | null
  171. /**
  172. * @internal
  173. */
  174. ssFallback: VNode | null
  175. // optimization only
  176. shapeFlag: number
  177. patchFlag: number
  178. /**
  179. * @internal
  180. */
  181. dynamicProps: string[] | null
  182. /**
  183. * @internal
  184. */
  185. dynamicChildren: VNode[] | null
  186. // application root node only
  187. appContext: AppContext | null
  188. /**
  189. * @internal lexical scope owner instance
  190. */
  191. ctx: ComponentInternalInstance | null
  192. /**
  193. * @internal attached by v-memo
  194. */
  195. memo?: any[]
  196. /**
  197. * @internal __COMPAT__ only
  198. */
  199. isCompatRoot?: true
  200. /**
  201. * @internal custom element interception hook
  202. */
  203. ce?: (instance: ComponentInternalInstance) => void
  204. }
  205. // Since v-if and v-for are the two possible ways node structure can dynamically
  206. // change, once we consider v-if branches and each v-for fragment a block, we
  207. // can divide a template into nested blocks, and within each block the node
  208. // structure would be stable. This allows us to skip most children diffing
  209. // and only worry about the dynamic nodes (indicated by patch flags).
  210. export const blockStack: (VNode[] | null)[] = []
  211. export let currentBlock: VNode[] | null = null
  212. /**
  213. * Open a block.
  214. * This must be called before `createBlock`. It cannot be part of `createBlock`
  215. * because the children of the block are evaluated before `createBlock` itself
  216. * is called. The generated code typically looks like this:
  217. *
  218. * ```js
  219. * function render() {
  220. * return (openBlock(),createBlock('div', null, [...]))
  221. * }
  222. * ```
  223. * disableTracking is true when creating a v-for fragment block, since a v-for
  224. * fragment always diffs its children.
  225. *
  226. * @private
  227. */
  228. export function openBlock(disableTracking = false) {
  229. blockStack.push((currentBlock = disableTracking ? null : []))
  230. }
  231. export function closeBlock() {
  232. blockStack.pop()
  233. currentBlock = blockStack[blockStack.length - 1] || null
  234. }
  235. // Whether we should be tracking dynamic child nodes inside a block.
  236. // Only tracks when this value is > 0
  237. // We are not using a simple boolean because this value may need to be
  238. // incremented/decremented by nested usage of v-once (see below)
  239. export let isBlockTreeEnabled = 1
  240. /**
  241. * Block tracking sometimes needs to be disabled, for example during the
  242. * creation of a tree that needs to be cached by v-once. The compiler generates
  243. * code like this:
  244. *
  245. * ``` js
  246. * _cache[1] || (
  247. * setBlockTracking(-1),
  248. * _cache[1] = createVNode(...),
  249. * setBlockTracking(1),
  250. * _cache[1]
  251. * )
  252. * ```
  253. *
  254. * @private
  255. */
  256. export function setBlockTracking(value: number) {
  257. isBlockTreeEnabled += value
  258. }
  259. function setupBlock(vnode: VNode) {
  260. // save current block children on the block vnode
  261. vnode.dynamicChildren =
  262. isBlockTreeEnabled > 0 ? currentBlock || (EMPTY_ARR as any) : null
  263. // close block
  264. closeBlock()
  265. // a block is always going to be patched, so track it as a child of its
  266. // parent block
  267. if (isBlockTreeEnabled > 0 && currentBlock) {
  268. currentBlock.push(vnode)
  269. }
  270. return vnode
  271. }
  272. /**
  273. * @private
  274. */
  275. export function createElementBlock(
  276. type: string | typeof Fragment,
  277. props?: Record<string, any> | null,
  278. children?: any,
  279. patchFlag?: number,
  280. dynamicProps?: string[],
  281. shapeFlag?: number
  282. ) {
  283. return setupBlock(
  284. createBaseVNode(
  285. type,
  286. props,
  287. children,
  288. patchFlag,
  289. dynamicProps,
  290. shapeFlag,
  291. true /* isBlock */
  292. )
  293. )
  294. }
  295. /**
  296. * Create a block root vnode. Takes the same exact arguments as `createVNode`.
  297. * A block root keeps track of dynamic nodes within the block in the
  298. * `dynamicChildren` array.
  299. *
  300. * @private
  301. */
  302. export function createBlock(
  303. type: VNodeTypes | ClassComponent,
  304. props?: Record<string, any> | null,
  305. children?: any,
  306. patchFlag?: number,
  307. dynamicProps?: string[]
  308. ): VNode {
  309. return setupBlock(
  310. createVNode(
  311. type,
  312. props,
  313. children,
  314. patchFlag,
  315. dynamicProps,
  316. true /* isBlock: prevent a block from tracking itself */
  317. )
  318. )
  319. }
  320. export function isVNode(value: any): value is VNode {
  321. return value ? value.__v_isVNode === true : false
  322. }
  323. export function isSameVNodeType(n1: VNode, n2: VNode): boolean {
  324. if (
  325. __DEV__ &&
  326. n2.shapeFlag & ShapeFlags.COMPONENT &&
  327. hmrDirtyComponents.has(n2.type as ConcreteComponent)
  328. ) {
  329. // #7042, ensure the vnode being unmounted during HMR
  330. // bitwise operations to remove keep alive flags
  331. n1.shapeFlag &= ~ShapeFlags.COMPONENT_SHOULD_KEEP_ALIVE
  332. n2.shapeFlag &= ~ShapeFlags.COMPONENT_KEPT_ALIVE
  333. // HMR only: if the component has been hot-updated, force a reload.
  334. return false
  335. }
  336. return n1.type === n2.type && n1.key === n2.key
  337. }
  338. let vnodeArgsTransformer:
  339. | ((
  340. args: Parameters<typeof _createVNode>,
  341. instance: ComponentInternalInstance | null
  342. ) => Parameters<typeof _createVNode>)
  343. | undefined
  344. /**
  345. * Internal API for registering an arguments transform for createVNode
  346. * used for creating stubs in the test-utils
  347. * It is *internal* but needs to be exposed for test-utils to pick up proper
  348. * typings
  349. */
  350. export function transformVNodeArgs(transformer?: typeof vnodeArgsTransformer) {
  351. vnodeArgsTransformer = transformer
  352. }
  353. const createVNodeWithArgsTransform = (
  354. ...args: Parameters<typeof _createVNode>
  355. ): VNode => {
  356. return _createVNode(
  357. ...(vnodeArgsTransformer
  358. ? vnodeArgsTransformer(args, currentRenderingInstance)
  359. : args)
  360. )
  361. }
  362. export const InternalObjectKey = `__vInternal`
  363. const normalizeKey = ({ key }: VNodeProps): VNode['key'] =>
  364. key != null ? key : null
  365. const normalizeRef = ({
  366. ref,
  367. ref_key,
  368. ref_for
  369. }: VNodeProps): VNodeNormalizedRefAtom | null => {
  370. if (typeof ref === 'number') {
  371. ref = '' + ref
  372. }
  373. return (
  374. ref != null
  375. ? isString(ref) || isRef(ref) || isFunction(ref)
  376. ? { i: currentRenderingInstance, r: ref, k: ref_key, f: !!ref_for }
  377. : ref
  378. : null
  379. ) as any
  380. }
  381. function createBaseVNode(
  382. type: VNodeTypes | ClassComponent | typeof NULL_DYNAMIC_COMPONENT,
  383. props: (Data & VNodeProps) | null = null,
  384. children: unknown = null,
  385. patchFlag = 0,
  386. dynamicProps: string[] | null = null,
  387. shapeFlag = type === Fragment ? 0 : ShapeFlags.ELEMENT,
  388. isBlockNode = false,
  389. needFullChildrenNormalization = false
  390. ) {
  391. const vnode = {
  392. __v_isVNode: true,
  393. __v_skip: true,
  394. type,
  395. props,
  396. key: props && normalizeKey(props),
  397. ref: props && normalizeRef(props),
  398. scopeId: currentScopeId,
  399. slotScopeIds: null,
  400. children,
  401. component: null,
  402. suspense: null,
  403. ssContent: null,
  404. ssFallback: null,
  405. dirs: null,
  406. transition: null,
  407. el: null,
  408. anchor: null,
  409. target: null,
  410. targetAnchor: null,
  411. staticCount: 0,
  412. shapeFlag,
  413. patchFlag,
  414. dynamicProps,
  415. dynamicChildren: null,
  416. appContext: null,
  417. ctx: currentRenderingInstance
  418. } as VNode
  419. if (needFullChildrenNormalization) {
  420. normalizeChildren(vnode, children)
  421. // normalize suspense children
  422. if (__FEATURE_SUSPENSE__ && shapeFlag & ShapeFlags.SUSPENSE) {
  423. ;(type as typeof SuspenseImpl).normalize(vnode)
  424. }
  425. } else if (children) {
  426. // compiled element vnode - if children is passed, only possible types are
  427. // string or Array.
  428. vnode.shapeFlag |= isString(children)
  429. ? ShapeFlags.TEXT_CHILDREN
  430. : ShapeFlags.ARRAY_CHILDREN
  431. }
  432. // validate key
  433. if (__DEV__ && vnode.key !== vnode.key) {
  434. warn(`VNode created with invalid key (NaN). VNode type:`, vnode.type)
  435. }
  436. // track vnode for block tree
  437. if (
  438. isBlockTreeEnabled > 0 &&
  439. // avoid a block node from tracking itself
  440. !isBlockNode &&
  441. // has current parent block
  442. currentBlock &&
  443. // presence of a patch flag indicates this node needs patching on updates.
  444. // component nodes also should always be patched, because even if the
  445. // component doesn't need to update, it needs to persist the instance on to
  446. // the next vnode so that it can be properly unmounted later.
  447. (vnode.patchFlag > 0 || shapeFlag & ShapeFlags.COMPONENT) &&
  448. // the EVENTS flag is only for hydration and if it is the only flag, the
  449. // vnode should not be considered dynamic due to handler caching.
  450. vnode.patchFlag !== PatchFlags.NEED_HYDRATION
  451. ) {
  452. currentBlock.push(vnode)
  453. }
  454. if (__COMPAT__) {
  455. convertLegacyVModelProps(vnode)
  456. defineLegacyVNodeProperties(vnode)
  457. }
  458. return vnode
  459. }
  460. export { createBaseVNode as createElementVNode }
  461. export const createVNode = (
  462. __DEV__ ? createVNodeWithArgsTransform : _createVNode
  463. ) as typeof _createVNode
  464. function _createVNode(
  465. type: VNodeTypes | ClassComponent | typeof NULL_DYNAMIC_COMPONENT,
  466. props: (Data & VNodeProps) | null = null,
  467. children: unknown = null,
  468. patchFlag: number = 0,
  469. dynamicProps: string[] | null = null,
  470. isBlockNode = false
  471. ): VNode {
  472. if (!type || type === NULL_DYNAMIC_COMPONENT) {
  473. if (__DEV__ && !type) {
  474. warn(`Invalid vnode type when creating vnode: ${type}.`)
  475. }
  476. type = Comment
  477. }
  478. if (isVNode(type)) {
  479. // createVNode receiving an existing vnode. This happens in cases like
  480. // <component :is="vnode"/>
  481. // #2078 make sure to merge refs during the clone instead of overwriting it
  482. const cloned = cloneVNode(type, props, true /* mergeRef: true */)
  483. if (children) {
  484. normalizeChildren(cloned, children)
  485. }
  486. if (isBlockTreeEnabled > 0 && !isBlockNode && currentBlock) {
  487. if (cloned.shapeFlag & ShapeFlags.COMPONENT) {
  488. currentBlock[currentBlock.indexOf(type)] = cloned
  489. } else {
  490. currentBlock.push(cloned)
  491. }
  492. }
  493. cloned.patchFlag |= PatchFlags.BAIL
  494. return cloned
  495. }
  496. // class component normalization.
  497. if (isClassComponent(type)) {
  498. type = type.__vccOpts
  499. }
  500. // 2.x async/functional component compat
  501. if (__COMPAT__) {
  502. type = convertLegacyComponent(type, currentRenderingInstance)
  503. }
  504. // class & style normalization.
  505. if (props) {
  506. // for reactive or proxy objects, we need to clone it to enable mutation.
  507. props = guardReactiveProps(props)!
  508. let { class: klass, style } = props
  509. if (klass && !isString(klass)) {
  510. props.class = normalizeClass(klass)
  511. }
  512. if (isObject(style)) {
  513. // reactive state objects need to be cloned since they are likely to be
  514. // mutated
  515. if (isProxy(style) && !isArray(style)) {
  516. style = extend({}, style)
  517. }
  518. props.style = normalizeStyle(style)
  519. }
  520. }
  521. // encode the vnode type information into a bitmap
  522. const shapeFlag = isString(type)
  523. ? ShapeFlags.ELEMENT
  524. : __FEATURE_SUSPENSE__ && isSuspense(type)
  525. ? ShapeFlags.SUSPENSE
  526. : isTeleport(type)
  527. ? ShapeFlags.TELEPORT
  528. : isObject(type)
  529. ? ShapeFlags.STATEFUL_COMPONENT
  530. : isFunction(type)
  531. ? ShapeFlags.FUNCTIONAL_COMPONENT
  532. : 0
  533. if (__DEV__ && shapeFlag & ShapeFlags.STATEFUL_COMPONENT && isProxy(type)) {
  534. type = toRaw(type)
  535. warn(
  536. `Vue received a Component that was made a reactive object. This can ` +
  537. `lead to unnecessary performance overhead and should be avoided by ` +
  538. `marking the component with \`markRaw\` or using \`shallowRef\` ` +
  539. `instead of \`ref\`.`,
  540. `\nComponent that was made reactive: `,
  541. type
  542. )
  543. }
  544. return createBaseVNode(
  545. type,
  546. props,
  547. children,
  548. patchFlag,
  549. dynamicProps,
  550. shapeFlag,
  551. isBlockNode,
  552. true
  553. )
  554. }
  555. export function guardReactiveProps(props: (Data & VNodeProps) | null) {
  556. if (!props) return null
  557. return isProxy(props) || InternalObjectKey in props
  558. ? extend({}, props)
  559. : props
  560. }
  561. export function cloneVNode<T, U>(
  562. vnode: VNode<T, U>,
  563. extraProps?: (Data & VNodeProps) | null,
  564. mergeRef = false
  565. ): VNode<T, U> {
  566. // This is intentionally NOT using spread or extend to avoid the runtime
  567. // key enumeration cost.
  568. const { props, ref, patchFlag, children } = vnode
  569. const mergedProps = extraProps ? mergeProps(props || {}, extraProps) : props
  570. const cloned: VNode<T, U> = {
  571. __v_isVNode: true,
  572. __v_skip: true,
  573. type: vnode.type,
  574. props: mergedProps,
  575. key: mergedProps && normalizeKey(mergedProps),
  576. ref:
  577. extraProps && extraProps.ref
  578. ? // #2078 in the case of <component :is="vnode" ref="extra"/>
  579. // if the vnode itself already has a ref, cloneVNode will need to merge
  580. // the refs so the single vnode can be set on multiple refs
  581. mergeRef && ref
  582. ? isArray(ref)
  583. ? ref.concat(normalizeRef(extraProps)!)
  584. : [ref, normalizeRef(extraProps)!]
  585. : normalizeRef(extraProps)
  586. : ref,
  587. scopeId: vnode.scopeId,
  588. slotScopeIds: vnode.slotScopeIds,
  589. children:
  590. __DEV__ && patchFlag === PatchFlags.HOISTED && isArray(children)
  591. ? (children as VNode[]).map(deepCloneVNode)
  592. : children,
  593. target: vnode.target,
  594. targetAnchor: vnode.targetAnchor,
  595. staticCount: vnode.staticCount,
  596. shapeFlag: vnode.shapeFlag,
  597. // if the vnode is cloned with extra props, we can no longer assume its
  598. // existing patch flag to be reliable and need to add the FULL_PROPS flag.
  599. // note: preserve flag for fragments since they use the flag for children
  600. // fast paths only.
  601. patchFlag:
  602. extraProps && vnode.type !== Fragment
  603. ? patchFlag === -1 // hoisted node
  604. ? PatchFlags.FULL_PROPS
  605. : patchFlag | PatchFlags.FULL_PROPS
  606. : patchFlag,
  607. dynamicProps: vnode.dynamicProps,
  608. dynamicChildren: vnode.dynamicChildren,
  609. appContext: vnode.appContext,
  610. dirs: vnode.dirs,
  611. transition: vnode.transition,
  612. // These should technically only be non-null on mounted VNodes. However,
  613. // they *should* be copied for kept-alive vnodes. So we just always copy
  614. // them since them being non-null during a mount doesn't affect the logic as
  615. // they will simply be overwritten.
  616. component: vnode.component,
  617. suspense: vnode.suspense,
  618. ssContent: vnode.ssContent && cloneVNode(vnode.ssContent),
  619. ssFallback: vnode.ssFallback && cloneVNode(vnode.ssFallback),
  620. el: vnode.el,
  621. anchor: vnode.anchor,
  622. ctx: vnode.ctx,
  623. ce: vnode.ce
  624. }
  625. if (__COMPAT__) {
  626. defineLegacyVNodeProperties(cloned as VNode)
  627. }
  628. return cloned
  629. }
  630. /**
  631. * Dev only, for HMR of hoisted vnodes reused in v-for
  632. * https://github.com/vitejs/vite/issues/2022
  633. */
  634. function deepCloneVNode(vnode: VNode): VNode {
  635. const cloned = cloneVNode(vnode)
  636. if (isArray(vnode.children)) {
  637. cloned.children = (vnode.children as VNode[]).map(deepCloneVNode)
  638. }
  639. return cloned
  640. }
  641. /**
  642. * @private
  643. */
  644. export function createTextVNode(text: string = ' ', flag: number = 0): VNode {
  645. return createVNode(Text, null, text, flag)
  646. }
  647. /**
  648. * @private
  649. */
  650. export function createStaticVNode(
  651. content: string,
  652. numberOfNodes: number
  653. ): VNode {
  654. // A static vnode can contain multiple stringified elements, and the number
  655. // of elements is necessary for hydration.
  656. const vnode = createVNode(Static, null, content)
  657. vnode.staticCount = numberOfNodes
  658. return vnode
  659. }
  660. /**
  661. * @private
  662. */
  663. export function createCommentVNode(
  664. text: string = '',
  665. // when used as the v-else branch, the comment node must be created as a
  666. // block to ensure correct updates.
  667. asBlock: boolean = false
  668. ): VNode {
  669. return asBlock
  670. ? (openBlock(), createBlock(Comment, null, text))
  671. : createVNode(Comment, null, text)
  672. }
  673. export function normalizeVNode(child: VNodeChild): VNode {
  674. if (child == null || typeof child === 'boolean') {
  675. // empty placeholder
  676. return createVNode(Comment)
  677. } else if (isArray(child)) {
  678. // fragment
  679. return createVNode(
  680. Fragment,
  681. null,
  682. // #3666, avoid reference pollution when reusing vnode
  683. child.slice()
  684. )
  685. } else if (typeof child === 'object') {
  686. // already vnode, this should be the most common since compiled templates
  687. // always produce all-vnode children arrays
  688. return cloneIfMounted(child)
  689. } else {
  690. // strings and numbers
  691. return createVNode(Text, null, String(child))
  692. }
  693. }
  694. // optimized normalization for template-compiled render fns
  695. export function cloneIfMounted(child: VNode): VNode {
  696. return (child.el === null && child.patchFlag !== PatchFlags.HOISTED) ||
  697. child.memo
  698. ? child
  699. : cloneVNode(child)
  700. }
  701. export function normalizeChildren(vnode: VNode, children: unknown) {
  702. let type = 0
  703. const { shapeFlag } = vnode
  704. if (children == null) {
  705. children = null
  706. } else if (isArray(children)) {
  707. type = ShapeFlags.ARRAY_CHILDREN
  708. } else if (typeof children === 'object') {
  709. if (shapeFlag & (ShapeFlags.ELEMENT | ShapeFlags.TELEPORT)) {
  710. // Normalize slot to plain children for plain element and Teleport
  711. const slot = (children as any).default
  712. if (slot) {
  713. // _c marker is added by withCtx() indicating this is a compiled slot
  714. slot._c && (slot._d = false)
  715. normalizeChildren(vnode, slot())
  716. slot._c && (slot._d = true)
  717. }
  718. return
  719. } else {
  720. type = ShapeFlags.SLOTS_CHILDREN
  721. const slotFlag = (children as RawSlots)._
  722. if (!slotFlag && !(InternalObjectKey in children!)) {
  723. // if slots are not normalized, attach context instance
  724. // (compiled / normalized slots already have context)
  725. ;(children as RawSlots)._ctx = currentRenderingInstance
  726. } else if (slotFlag === SlotFlags.FORWARDED && currentRenderingInstance) {
  727. // a child component receives forwarded slots from the parent.
  728. // its slot type is determined by its parent's slot type.
  729. if (
  730. (currentRenderingInstance.slots as RawSlots)._ === SlotFlags.STABLE
  731. ) {
  732. ;(children as RawSlots)._ = SlotFlags.STABLE
  733. } else {
  734. ;(children as RawSlots)._ = SlotFlags.DYNAMIC
  735. vnode.patchFlag |= PatchFlags.DYNAMIC_SLOTS
  736. }
  737. }
  738. }
  739. } else if (isFunction(children)) {
  740. children = { default: children, _ctx: currentRenderingInstance }
  741. type = ShapeFlags.SLOTS_CHILDREN
  742. } else {
  743. children = String(children)
  744. // force teleport children to array so it can be moved around
  745. if (shapeFlag & ShapeFlags.TELEPORT) {
  746. type = ShapeFlags.ARRAY_CHILDREN
  747. children = [createTextVNode(children as string)]
  748. } else {
  749. type = ShapeFlags.TEXT_CHILDREN
  750. }
  751. }
  752. vnode.children = children as VNodeNormalizedChildren
  753. vnode.shapeFlag |= type
  754. }
  755. export function mergeProps(...args: (Data & VNodeProps)[]) {
  756. const ret: Data = {}
  757. for (let i = 0; i < args.length; i++) {
  758. const toMerge = args[i]
  759. for (const key in toMerge) {
  760. if (key === 'class') {
  761. if (ret.class !== toMerge.class) {
  762. ret.class = normalizeClass([ret.class, toMerge.class])
  763. }
  764. } else if (key === 'style') {
  765. ret.style = normalizeStyle([ret.style, toMerge.style])
  766. } else if (isOn(key)) {
  767. const existing = ret[key]
  768. const incoming = toMerge[key]
  769. if (
  770. incoming &&
  771. existing !== incoming &&
  772. !(isArray(existing) && existing.includes(incoming))
  773. ) {
  774. ret[key] = existing
  775. ? [].concat(existing as any, incoming as any)
  776. : incoming
  777. }
  778. } else if (key !== '') {
  779. ret[key] = toMerge[key]
  780. }
  781. }
  782. }
  783. return ret
  784. }
  785. export function invokeVNodeHook(
  786. hook: VNodeHook,
  787. instance: ComponentInternalInstance | null,
  788. vnode: VNode,
  789. prevVNode: VNode | null = null
  790. ) {
  791. callWithAsyncErrorHandling(hook, instance, ErrorCodes.VNODE_HOOK, [
  792. vnode,
  793. prevVNode
  794. ])
  795. }