2
0

vnode.ts 25 KB

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