vnode.ts 25 KB

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