vnode.ts 25 KB

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