vnode.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857
  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. } from '@vue/shared'
  15. import {
  16. ComponentInternalInstance,
  17. Data,
  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(__DEV__ ? 'Fragment' : undefined) as any as {
  49. __isFragment: true
  50. new (): {
  51. $props: VNodeProps
  52. }
  53. }
  54. export const Text = Symbol(__DEV__ ? 'Text' : undefined)
  55. export const Comment = Symbol(__DEV__ ? 'Comment' : undefined)
  56. export const Static = Symbol(__DEV__ ? 'Static' : undefined)
  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. return (
  371. ref != null
  372. ? isString(ref) || isRef(ref) || isFunction(ref)
  373. ? { i: currentRenderingInstance, r: ref, k: ref_key, f: !!ref_for }
  374. : ref
  375. : null
  376. ) as any
  377. }
  378. function createBaseVNode(
  379. type: VNodeTypes | ClassComponent | typeof NULL_DYNAMIC_COMPONENT,
  380. props: (Data & VNodeProps) | null = null,
  381. children: unknown = null,
  382. patchFlag = 0,
  383. dynamicProps: string[] | null = null,
  384. shapeFlag = type === Fragment ? 0 : ShapeFlags.ELEMENT,
  385. isBlockNode = false,
  386. needFullChildrenNormalization = false
  387. ) {
  388. const vnode = {
  389. __v_isVNode: true,
  390. __v_skip: true,
  391. type,
  392. props,
  393. key: props && normalizeKey(props),
  394. ref: props && normalizeRef(props),
  395. scopeId: currentScopeId,
  396. slotScopeIds: null,
  397. children,
  398. component: null,
  399. suspense: null,
  400. ssContent: null,
  401. ssFallback: null,
  402. dirs: null,
  403. transition: null,
  404. el: null,
  405. anchor: null,
  406. target: null,
  407. targetAnchor: null,
  408. staticCount: 0,
  409. shapeFlag,
  410. patchFlag,
  411. dynamicProps,
  412. dynamicChildren: null,
  413. appContext: null,
  414. ctx: currentRenderingInstance
  415. } as VNode
  416. if (needFullChildrenNormalization) {
  417. normalizeChildren(vnode, children)
  418. // normalize suspense children
  419. if (__FEATURE_SUSPENSE__ && shapeFlag & ShapeFlags.SUSPENSE) {
  420. ;(type as typeof SuspenseImpl).normalize(vnode)
  421. }
  422. } else if (children) {
  423. // compiled element vnode - if children is passed, only possible types are
  424. // string or Array.
  425. vnode.shapeFlag |= isString(children)
  426. ? ShapeFlags.TEXT_CHILDREN
  427. : ShapeFlags.ARRAY_CHILDREN
  428. }
  429. // validate key
  430. if (__DEV__ && vnode.key !== vnode.key) {
  431. warn(`VNode created with invalid key (NaN). VNode type:`, vnode.type)
  432. }
  433. // track vnode for block tree
  434. if (
  435. isBlockTreeEnabled > 0 &&
  436. // avoid a block node from tracking itself
  437. !isBlockNode &&
  438. // has current parent block
  439. currentBlock &&
  440. // presence of a patch flag indicates this node needs patching on updates.
  441. // component nodes also should always be patched, because even if the
  442. // component doesn't need to update, it needs to persist the instance on to
  443. // the next vnode so that it can be properly unmounted later.
  444. (vnode.patchFlag > 0 || shapeFlag & ShapeFlags.COMPONENT) &&
  445. // the EVENTS flag is only for hydration and if it is the only flag, the
  446. // vnode should not be considered dynamic due to handler caching.
  447. vnode.patchFlag !== PatchFlags.HYDRATE_EVENTS
  448. ) {
  449. currentBlock.push(vnode)
  450. }
  451. if (__COMPAT__) {
  452. convertLegacyVModelProps(vnode)
  453. defineLegacyVNodeProperties(vnode)
  454. }
  455. return vnode
  456. }
  457. export { createBaseVNode as createElementVNode }
  458. export const createVNode = (
  459. __DEV__ ? createVNodeWithArgsTransform : _createVNode
  460. ) as typeof _createVNode
  461. function _createVNode(
  462. type: VNodeTypes | ClassComponent | typeof NULL_DYNAMIC_COMPONENT,
  463. props: (Data & VNodeProps) | null = null,
  464. children: unknown = null,
  465. patchFlag: number = 0,
  466. dynamicProps: string[] | null = null,
  467. isBlockNode = false
  468. ): VNode {
  469. if (!type || type === NULL_DYNAMIC_COMPONENT) {
  470. if (__DEV__ && !type) {
  471. warn(`Invalid vnode type when creating vnode: ${type}.`)
  472. }
  473. type = Comment
  474. }
  475. if (isVNode(type)) {
  476. // createVNode receiving an existing vnode. This happens in cases like
  477. // <component :is="vnode"/>
  478. // #2078 make sure to merge refs during the clone instead of overwriting it
  479. const cloned = cloneVNode(type, props, true /* mergeRef: true */)
  480. if (children) {
  481. normalizeChildren(cloned, children)
  482. }
  483. if (isBlockTreeEnabled > 0 && !isBlockNode && currentBlock) {
  484. if (cloned.shapeFlag & ShapeFlags.COMPONENT) {
  485. currentBlock[currentBlock.indexOf(type)] = cloned
  486. } else {
  487. currentBlock.push(cloned)
  488. }
  489. }
  490. cloned.patchFlag |= PatchFlags.BAIL
  491. return cloned
  492. }
  493. // class component normalization.
  494. if (isClassComponent(type)) {
  495. type = type.__vccOpts
  496. }
  497. // 2.x async/functional component compat
  498. if (__COMPAT__) {
  499. type = convertLegacyComponent(type, currentRenderingInstance)
  500. }
  501. // class & style normalization.
  502. if (props) {
  503. // for reactive or proxy objects, we need to clone it to enable mutation.
  504. props = guardReactiveProps(props)!
  505. let { class: klass, style } = props
  506. if (klass && !isString(klass)) {
  507. props.class = normalizeClass(klass)
  508. }
  509. if (isObject(style)) {
  510. // reactive state objects need to be cloned since they are likely to be
  511. // mutated
  512. if (isProxy(style) && !isArray(style)) {
  513. style = extend({}, style)
  514. }
  515. props.style = normalizeStyle(style)
  516. }
  517. }
  518. // encode the vnode type information into a bitmap
  519. const shapeFlag = isString(type)
  520. ? ShapeFlags.ELEMENT
  521. : __FEATURE_SUSPENSE__ && isSuspense(type)
  522. ? ShapeFlags.SUSPENSE
  523. : isTeleport(type)
  524. ? ShapeFlags.TELEPORT
  525. : isObject(type)
  526. ? ShapeFlags.STATEFUL_COMPONENT
  527. : isFunction(type)
  528. ? ShapeFlags.FUNCTIONAL_COMPONENT
  529. : 0
  530. if (__DEV__ && shapeFlag & ShapeFlags.STATEFUL_COMPONENT && isProxy(type)) {
  531. type = toRaw(type)
  532. warn(
  533. `Vue received a Component which was made a reactive object. This can ` +
  534. `lead to unnecessary performance overhead, and should be avoided by ` +
  535. `marking the component with \`markRaw\` or using \`shallowRef\` ` +
  536. `instead of \`ref\`.`,
  537. `\nComponent that was made reactive: `,
  538. type
  539. )
  540. }
  541. return createBaseVNode(
  542. type,
  543. props,
  544. children,
  545. patchFlag,
  546. dynamicProps,
  547. shapeFlag,
  548. isBlockNode,
  549. true
  550. )
  551. }
  552. export function guardReactiveProps(props: (Data & VNodeProps) | null) {
  553. if (!props) return null
  554. return isProxy(props) || InternalObjectKey in props
  555. ? extend({}, props)
  556. : props
  557. }
  558. export function cloneVNode<T, U>(
  559. vnode: VNode<T, U>,
  560. extraProps?: (Data & VNodeProps) | null,
  561. mergeRef = false
  562. ): VNode<T, U> {
  563. // This is intentionally NOT using spread or extend to avoid the runtime
  564. // key enumeration cost.
  565. const { props, ref, patchFlag, children } = vnode
  566. const mergedProps = extraProps ? mergeProps(props || {}, extraProps) : props
  567. const cloned: VNode<T, U> = {
  568. __v_isVNode: true,
  569. __v_skip: true,
  570. type: vnode.type,
  571. props: mergedProps,
  572. key: mergedProps && normalizeKey(mergedProps),
  573. ref:
  574. extraProps && extraProps.ref
  575. ? // #2078 in the case of <component :is="vnode" ref="extra"/>
  576. // if the vnode itself already has a ref, cloneVNode will need to merge
  577. // the refs so the single vnode can be set on multiple refs
  578. mergeRef && ref
  579. ? isArray(ref)
  580. ? ref.concat(normalizeRef(extraProps)!)
  581. : [ref, normalizeRef(extraProps)!]
  582. : normalizeRef(extraProps)
  583. : ref,
  584. scopeId: vnode.scopeId,
  585. slotScopeIds: vnode.slotScopeIds,
  586. children:
  587. __DEV__ && patchFlag === PatchFlags.HOISTED && isArray(children)
  588. ? (children as VNode[]).map(deepCloneVNode)
  589. : children,
  590. target: vnode.target,
  591. targetAnchor: vnode.targetAnchor,
  592. staticCount: vnode.staticCount,
  593. shapeFlag: vnode.shapeFlag,
  594. // if the vnode is cloned with extra props, we can no longer assume its
  595. // existing patch flag to be reliable and need to add the FULL_PROPS flag.
  596. // note: preserve flag for fragments since they use the flag for children
  597. // fast paths only.
  598. patchFlag:
  599. extraProps && vnode.type !== Fragment
  600. ? patchFlag === -1 // hoisted node
  601. ? PatchFlags.FULL_PROPS
  602. : patchFlag | PatchFlags.FULL_PROPS
  603. : patchFlag,
  604. dynamicProps: vnode.dynamicProps,
  605. dynamicChildren: vnode.dynamicChildren,
  606. appContext: vnode.appContext,
  607. dirs: vnode.dirs,
  608. transition: vnode.transition,
  609. // These should technically only be non-null on mounted VNodes. However,
  610. // they *should* be copied for kept-alive vnodes. So we just always copy
  611. // them since them being non-null during a mount doesn't affect the logic as
  612. // they will simply be overwritten.
  613. component: vnode.component,
  614. suspense: vnode.suspense,
  615. ssContent: vnode.ssContent && cloneVNode(vnode.ssContent),
  616. ssFallback: vnode.ssFallback && cloneVNode(vnode.ssFallback),
  617. el: vnode.el,
  618. anchor: vnode.anchor,
  619. ctx: vnode.ctx,
  620. ce: vnode.ce
  621. }
  622. if (__COMPAT__) {
  623. defineLegacyVNodeProperties(cloned as VNode)
  624. }
  625. return cloned as any
  626. }
  627. /**
  628. * Dev only, for HMR of hoisted vnodes reused in v-for
  629. * https://github.com/vitejs/vite/issues/2022
  630. */
  631. function deepCloneVNode(vnode: VNode): VNode {
  632. const cloned = cloneVNode(vnode)
  633. if (isArray(vnode.children)) {
  634. cloned.children = (vnode.children as VNode[]).map(deepCloneVNode)
  635. }
  636. return cloned
  637. }
  638. /**
  639. * @private
  640. */
  641. export function createTextVNode(text: string = ' ', flag: number = 0): VNode {
  642. return createVNode(Text, null, text, flag)
  643. }
  644. /**
  645. * @private
  646. */
  647. export function createStaticVNode(
  648. content: string,
  649. numberOfNodes: number
  650. ): VNode {
  651. // A static vnode can contain multiple stringified elements, and the number
  652. // of elements is necessary for hydration.
  653. const vnode = createVNode(Static, null, content)
  654. vnode.staticCount = numberOfNodes
  655. return vnode
  656. }
  657. /**
  658. * @private
  659. */
  660. export function createCommentVNode(
  661. text: string = '',
  662. // when used as the v-else branch, the comment node must be created as a
  663. // block to ensure correct updates.
  664. asBlock: boolean = false
  665. ): VNode {
  666. return asBlock
  667. ? (openBlock(), createBlock(Comment, null, text))
  668. : createVNode(Comment, null, text)
  669. }
  670. export function normalizeVNode(child: VNodeChild): VNode {
  671. if (child == null || typeof child === 'boolean') {
  672. // empty placeholder
  673. return createVNode(Comment)
  674. } else if (isArray(child)) {
  675. // fragment
  676. return createVNode(
  677. Fragment,
  678. null,
  679. // #3666, avoid reference pollution when reusing vnode
  680. child.slice()
  681. )
  682. } else if (typeof child === 'object') {
  683. // already vnode, this should be the most common since compiled templates
  684. // always produce all-vnode children arrays
  685. return cloneIfMounted(child)
  686. } else {
  687. // strings and numbers
  688. return createVNode(Text, null, String(child))
  689. }
  690. }
  691. // optimized normalization for template-compiled render fns
  692. export function cloneIfMounted(child: VNode): VNode {
  693. return (child.el === null && child.patchFlag !== PatchFlags.HOISTED) ||
  694. child.memo
  695. ? child
  696. : cloneVNode(child)
  697. }
  698. export function normalizeChildren(vnode: VNode, children: unknown) {
  699. let type = 0
  700. const { shapeFlag } = vnode
  701. if (children == null) {
  702. children = null
  703. } else if (isArray(children)) {
  704. type = ShapeFlags.ARRAY_CHILDREN
  705. } else if (typeof children === 'object') {
  706. if (shapeFlag & (ShapeFlags.ELEMENT | ShapeFlags.TELEPORT)) {
  707. // Normalize slot to plain children for plain element and Teleport
  708. const slot = (children as any).default
  709. if (slot) {
  710. // _c marker is added by withCtx() indicating this is a compiled slot
  711. slot._c && (slot._d = false)
  712. normalizeChildren(vnode, slot())
  713. slot._c && (slot._d = true)
  714. }
  715. return
  716. } else {
  717. type = ShapeFlags.SLOTS_CHILDREN
  718. const slotFlag = (children as RawSlots)._
  719. if (!slotFlag && !(InternalObjectKey in children!)) {
  720. // if slots are not normalized, attach context instance
  721. // (compiled / normalized slots already have context)
  722. ;(children as RawSlots)._ctx = currentRenderingInstance
  723. } else if (slotFlag === SlotFlags.FORWARDED && currentRenderingInstance) {
  724. // a child component receives forwarded slots from the parent.
  725. // its slot type is determined by its parent's slot type.
  726. if (
  727. (currentRenderingInstance.slots as RawSlots)._ === SlotFlags.STABLE
  728. ) {
  729. ;(children as RawSlots)._ = SlotFlags.STABLE
  730. } else {
  731. ;(children as RawSlots)._ = SlotFlags.DYNAMIC
  732. vnode.patchFlag |= PatchFlags.DYNAMIC_SLOTS
  733. }
  734. }
  735. }
  736. } else if (isFunction(children)) {
  737. children = { default: children, _ctx: currentRenderingInstance }
  738. type = ShapeFlags.SLOTS_CHILDREN
  739. } else {
  740. children = String(children)
  741. // force teleport children to array so it can be moved around
  742. if (shapeFlag & ShapeFlags.TELEPORT) {
  743. type = ShapeFlags.ARRAY_CHILDREN
  744. children = [createTextVNode(children as string)]
  745. } else {
  746. type = ShapeFlags.TEXT_CHILDREN
  747. }
  748. }
  749. vnode.children = children as VNodeNormalizedChildren
  750. vnode.shapeFlag |= type
  751. }
  752. export function mergeProps(...args: (Data & VNodeProps)[]) {
  753. const ret: Data = {}
  754. for (let i = 0; i < args.length; i++) {
  755. const toMerge = args[i]
  756. for (const key in toMerge) {
  757. if (key === 'class') {
  758. if (ret.class !== toMerge.class) {
  759. ret.class = normalizeClass([ret.class, toMerge.class])
  760. }
  761. } else if (key === 'style') {
  762. ret.style = normalizeStyle([ret.style, toMerge.style])
  763. } else if (isOn(key)) {
  764. const existing = ret[key]
  765. const incoming = toMerge[key]
  766. if (
  767. incoming &&
  768. existing !== incoming &&
  769. !(isArray(existing) && existing.includes(incoming))
  770. ) {
  771. ret[key] = existing
  772. ? [].concat(existing as any, incoming as any)
  773. : incoming
  774. }
  775. } else if (key !== '') {
  776. ret[key] = toMerge[key]
  777. }
  778. }
  779. }
  780. return ret
  781. }
  782. export function invokeVNodeHook(
  783. hook: VNodeHook,
  784. instance: ComponentInternalInstance | null,
  785. vnode: VNode,
  786. prevVNode: VNode | null = null
  787. ) {
  788. callWithAsyncErrorHandling(hook, instance, ErrorCodes.VNODE_HOOK, [
  789. vnode,
  790. prevVNode
  791. ])
  792. }