vnode.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653
  1. import {
  2. isArray,
  3. isFunction,
  4. isString,
  5. isObject,
  6. EMPTY_ARR,
  7. extend,
  8. normalizeClass,
  9. normalizeStyle,
  10. PatchFlags,
  11. ShapeFlags,
  12. SlotFlags,
  13. isOn
  14. } from '@vue/shared'
  15. import {
  16. ComponentInternalInstance,
  17. Data,
  18. ConcreteComponent,
  19. ClassComponent,
  20. Component,
  21. isClassComponent
  22. } from './component'
  23. import { RawSlots } from './componentSlots'
  24. import { isProxy, Ref, toRaw, ReactiveFlags } from '@vue/reactivity'
  25. import { AppContext } from './apiCreateApp'
  26. import {
  27. SuspenseImpl,
  28. isSuspense,
  29. SuspenseBoundary,
  30. normalizeSuspenseChildren
  31. } from './components/Suspense'
  32. import { DirectiveBinding } from './directives'
  33. import { TransitionHooks } from './components/BaseTransition'
  34. import { warn } from './warning'
  35. import { currentScopeId } from './helpers/scopeId'
  36. import { TeleportImpl, isTeleport } from './components/Teleport'
  37. import { currentRenderingInstance } from './componentRenderUtils'
  38. import { RendererNode, RendererElement } from './renderer'
  39. import { NULL_DYNAMIC_COMPONENT } from './helpers/resolveAssets'
  40. import { hmrDirtyComponents } from './hmr'
  41. import { setCompiledSlotRendering } from './helpers/renderSlot'
  42. export const Fragment = (Symbol(__DEV__ ? 'Fragment' : undefined) as any) as {
  43. __isFragment: true
  44. new (): {
  45. $props: VNodeProps
  46. }
  47. }
  48. export const Text = Symbol(__DEV__ ? 'Text' : undefined)
  49. export const Comment = Symbol(__DEV__ ? 'Comment' : undefined)
  50. export const Static = Symbol(__DEV__ ? 'Static' : undefined)
  51. export type VNodeTypes =
  52. | string
  53. | VNode
  54. | Component
  55. | typeof Text
  56. | typeof Static
  57. | typeof Comment
  58. | typeof Fragment
  59. | typeof TeleportImpl
  60. | typeof SuspenseImpl
  61. export type VNodeRef =
  62. | string
  63. | Ref
  64. | ((ref: object | null, refs: Record<string, any>) => void)
  65. export type VNodeNormalizedRefAtom = {
  66. i: ComponentInternalInstance
  67. r: VNodeRef
  68. }
  69. export type VNodeNormalizedRef =
  70. | VNodeNormalizedRefAtom
  71. | (VNodeNormalizedRefAtom)[]
  72. type VNodeMountHook = (vnode: VNode) => void
  73. type VNodeUpdateHook = (vnode: VNode, oldVNode: VNode) => void
  74. export type VNodeHook =
  75. | VNodeMountHook
  76. | VNodeUpdateHook
  77. | VNodeMountHook[]
  78. | VNodeUpdateHook[]
  79. // https://github.com/microsoft/TypeScript/issues/33099
  80. export type VNodeProps = {
  81. key?: string | number
  82. ref?: VNodeRef
  83. // vnode hooks
  84. onVnodeBeforeMount?: VNodeMountHook | VNodeMountHook[]
  85. onVnodeMounted?: VNodeMountHook | VNodeMountHook[]
  86. onVnodeBeforeUpdate?: VNodeUpdateHook | VNodeUpdateHook[]
  87. onVnodeUpdated?: VNodeUpdateHook | VNodeUpdateHook[]
  88. onVnodeBeforeUnmount?: VNodeMountHook | VNodeMountHook[]
  89. onVnodeUnmounted?: VNodeMountHook | VNodeMountHook[]
  90. }
  91. type VNodeChildAtom =
  92. | VNode
  93. | string
  94. | number
  95. | boolean
  96. | null
  97. | undefined
  98. | void
  99. export type VNodeArrayChildren = Array<VNodeArrayChildren | VNodeChildAtom>
  100. export type VNodeChild = VNodeChildAtom | VNodeArrayChildren
  101. export type VNodeNormalizedChildren =
  102. | string
  103. | VNodeArrayChildren
  104. | RawSlots
  105. | null
  106. export interface VNode<
  107. HostNode = RendererNode,
  108. HostElement = RendererElement,
  109. ExtraProps = { [key: string]: any }
  110. > {
  111. /**
  112. * @internal
  113. */
  114. __v_isVNode: true
  115. /**
  116. * @internal
  117. */
  118. [ReactiveFlags.SKIP]: true
  119. type: VNodeTypes
  120. props: (VNodeProps & ExtraProps) | null
  121. key: string | number | null
  122. ref: VNodeNormalizedRef | null
  123. scopeId: string | null // SFC only
  124. children: VNodeNormalizedChildren
  125. component: ComponentInternalInstance | null
  126. dirs: DirectiveBinding[] | null
  127. transition: TransitionHooks<HostElement> | null
  128. // DOM
  129. el: HostNode | null
  130. anchor: HostNode | null // fragment anchor
  131. target: HostElement | null // teleport target
  132. targetAnchor: HostNode | null // teleport target anchor
  133. staticCount: number // number of elements contained in a static vnode
  134. // suspense
  135. suspense: SuspenseBoundary | null
  136. ssContent: VNode | null
  137. ssFallback: VNode | null
  138. // optimization only
  139. shapeFlag: number
  140. patchFlag: number
  141. dynamicProps: string[] | null
  142. dynamicChildren: VNode[] | null
  143. // application root node only
  144. appContext: AppContext | null
  145. }
  146. // Since v-if and v-for are the two possible ways node structure can dynamically
  147. // change, once we consider v-if branches and each v-for fragment a block, we
  148. // can divide a template into nested blocks, and within each block the node
  149. // structure would be stable. This allows us to skip most children diffing
  150. // and only worry about the dynamic nodes (indicated by patch flags).
  151. export const blockStack: (VNode[] | null)[] = []
  152. let currentBlock: VNode[] | null = null
  153. /**
  154. * Open a block.
  155. * This must be called before `createBlock`. It cannot be part of `createBlock`
  156. * because the children of the block are evaluated before `createBlock` itself
  157. * is called. The generated code typically looks like this:
  158. *
  159. * ```js
  160. * function render() {
  161. * return (openBlock(),createBlock('div', null, [...]))
  162. * }
  163. * ```
  164. * disableTracking is true when creating a v-for fragment block, since a v-for
  165. * fragment always diffs its children.
  166. *
  167. * @private
  168. */
  169. export function openBlock(disableTracking = false) {
  170. blockStack.push((currentBlock = disableTracking ? null : []))
  171. }
  172. export function closeBlock() {
  173. blockStack.pop()
  174. currentBlock = blockStack[blockStack.length - 1] || null
  175. }
  176. // Whether we should be tracking dynamic child nodes inside a block.
  177. // Only tracks when this value is > 0
  178. // We are not using a simple boolean because this value may need to be
  179. // incremented/decremented by nested usage of v-once (see below)
  180. let shouldTrack = 1
  181. /**
  182. * Block tracking sometimes needs to be disabled, for example during the
  183. * creation of a tree that needs to be cached by v-once. The compiler generates
  184. * code like this:
  185. *
  186. * ``` js
  187. * _cache[1] || (
  188. * setBlockTracking(-1),
  189. * _cache[1] = createVNode(...),
  190. * setBlockTracking(1),
  191. * _cache[1]
  192. * )
  193. * ```
  194. *
  195. * @private
  196. */
  197. export function setBlockTracking(value: number) {
  198. shouldTrack += value
  199. }
  200. /**
  201. * Create a block root vnode. Takes the same exact arguments as `createVNode`.
  202. * A block root keeps track of dynamic nodes within the block in the
  203. * `dynamicChildren` array.
  204. *
  205. * @private
  206. */
  207. export function createBlock(
  208. type: VNodeTypes | ClassComponent,
  209. props?: Record<string, any> | null,
  210. children?: any,
  211. patchFlag?: number,
  212. dynamicProps?: string[]
  213. ): VNode {
  214. const vnode = createVNode(
  215. type,
  216. props,
  217. children,
  218. patchFlag,
  219. dynamicProps,
  220. true /* isBlock: prevent a block from tracking itself */
  221. )
  222. // save current block children on the block vnode
  223. vnode.dynamicChildren = currentBlock || EMPTY_ARR
  224. // close block
  225. closeBlock()
  226. // a block is always going to be patched, so track it as a child of its
  227. // parent block
  228. if (shouldTrack > 0 && currentBlock) {
  229. currentBlock.push(vnode)
  230. }
  231. return vnode
  232. }
  233. export function isVNode(value: any): value is VNode {
  234. return value ? value.__v_isVNode === true : false
  235. }
  236. export function isSameVNodeType(n1: VNode, n2: VNode): boolean {
  237. if (
  238. __DEV__ &&
  239. n2.shapeFlag & ShapeFlags.COMPONENT &&
  240. hmrDirtyComponents.has(n2.type as ConcreteComponent)
  241. ) {
  242. // HMR only: if the component has been hot-updated, force a reload.
  243. return false
  244. }
  245. return n1.type === n2.type && n1.key === n2.key
  246. }
  247. let vnodeArgsTransformer:
  248. | ((
  249. args: Parameters<typeof _createVNode>,
  250. instance: ComponentInternalInstance | null
  251. ) => Parameters<typeof _createVNode>)
  252. | undefined
  253. /**
  254. * Internal API for registering an arguments transform for createVNode
  255. * used for creating stubs in the test-utils
  256. * It is *internal* but needs to be exposed for test-utils to pick up proper
  257. * typings
  258. */
  259. export function transformVNodeArgs(transformer?: typeof vnodeArgsTransformer) {
  260. vnodeArgsTransformer = transformer
  261. }
  262. const createVNodeWithArgsTransform = (
  263. ...args: Parameters<typeof _createVNode>
  264. ): VNode => {
  265. return _createVNode(
  266. ...(vnodeArgsTransformer
  267. ? vnodeArgsTransformer(args, currentRenderingInstance)
  268. : args)
  269. )
  270. }
  271. export const InternalObjectKey = `__vInternal`
  272. const normalizeKey = ({ key }: VNodeProps): VNode['key'] =>
  273. key != null ? key : null
  274. const normalizeRef = ({ ref }: VNodeProps): VNodeNormalizedRefAtom | null => {
  275. return (ref != null
  276. ? isArray(ref)
  277. ? ref
  278. : { i: currentRenderingInstance, r: ref }
  279. : null) as any
  280. }
  281. export const createVNode = (__DEV__
  282. ? createVNodeWithArgsTransform
  283. : _createVNode) as typeof _createVNode
  284. function _createVNode(
  285. type: VNodeTypes | ClassComponent | typeof NULL_DYNAMIC_COMPONENT,
  286. props: (Data & VNodeProps) | null = null,
  287. children: unknown = null,
  288. patchFlag: number = 0,
  289. dynamicProps: string[] | null = null,
  290. isBlockNode = false
  291. ): VNode {
  292. if (!type || type === NULL_DYNAMIC_COMPONENT) {
  293. if (__DEV__ && !type) {
  294. warn(`Invalid vnode type when creating vnode: ${type}.`)
  295. }
  296. type = Comment
  297. }
  298. if (isVNode(type)) {
  299. // createVNode receiving an existing vnode. This happens in cases like
  300. // <component :is="vnode"/>
  301. // #2078 make sure to merge refs during the clone instead of overwriting it
  302. const cloned = cloneVNode(type, props, true /* mergeRef: true */)
  303. if (children) {
  304. normalizeChildren(cloned, children)
  305. }
  306. return cloned
  307. }
  308. // class component normalization.
  309. if (isClassComponent(type)) {
  310. type = type.__vccOpts
  311. }
  312. // class & style normalization.
  313. if (props) {
  314. // for reactive or proxy objects, we need to clone it to enable mutation.
  315. if (isProxy(props) || InternalObjectKey in props) {
  316. props = extend({}, props)
  317. }
  318. let { class: klass, style } = props
  319. if (klass && !isString(klass)) {
  320. props.class = normalizeClass(klass)
  321. }
  322. if (isObject(style)) {
  323. // reactive state objects need to be cloned since they are likely to be
  324. // mutated
  325. if (isProxy(style) && !isArray(style)) {
  326. style = extend({}, style)
  327. }
  328. props.style = normalizeStyle(style)
  329. }
  330. }
  331. // encode the vnode type information into a bitmap
  332. const shapeFlag = isString(type)
  333. ? ShapeFlags.ELEMENT
  334. : __FEATURE_SUSPENSE__ && isSuspense(type)
  335. ? ShapeFlags.SUSPENSE
  336. : isTeleport(type)
  337. ? ShapeFlags.TELEPORT
  338. : isObject(type)
  339. ? ShapeFlags.STATEFUL_COMPONENT
  340. : isFunction(type)
  341. ? ShapeFlags.FUNCTIONAL_COMPONENT
  342. : 0
  343. if (__DEV__ && shapeFlag & ShapeFlags.STATEFUL_COMPONENT && isProxy(type)) {
  344. type = toRaw(type)
  345. warn(
  346. `Vue received a Component which was made a reactive object. This can ` +
  347. `lead to unnecessary performance overhead, and should be avoided by ` +
  348. `marking the component with \`markRaw\` or using \`shallowRef\` ` +
  349. `instead of \`ref\`.`,
  350. `\nComponent that was made reactive: `,
  351. type
  352. )
  353. }
  354. const vnode: VNode = {
  355. __v_isVNode: true,
  356. [ReactiveFlags.SKIP]: true,
  357. type,
  358. props,
  359. key: props && normalizeKey(props),
  360. ref: props && normalizeRef(props),
  361. scopeId: currentScopeId,
  362. children: null,
  363. component: null,
  364. suspense: null,
  365. ssContent: null,
  366. ssFallback: null,
  367. dirs: null,
  368. transition: null,
  369. el: null,
  370. anchor: null,
  371. target: null,
  372. targetAnchor: null,
  373. staticCount: 0,
  374. shapeFlag,
  375. patchFlag,
  376. dynamicProps,
  377. dynamicChildren: null,
  378. appContext: null
  379. }
  380. // validate key
  381. if (__DEV__ && vnode.key !== vnode.key) {
  382. warn(`VNode created with invalid key (NaN). VNode type:`, vnode.type)
  383. }
  384. normalizeChildren(vnode, children)
  385. // normalize suspense children
  386. if (__FEATURE_SUSPENSE__ && shapeFlag & ShapeFlags.SUSPENSE) {
  387. const { content, fallback } = normalizeSuspenseChildren(vnode)
  388. vnode.ssContent = content
  389. vnode.ssFallback = fallback
  390. }
  391. if (
  392. shouldTrack > 0 &&
  393. // avoid a block node from tracking itself
  394. !isBlockNode &&
  395. // has current parent block
  396. currentBlock &&
  397. // presence of a patch flag indicates this node needs patching on updates.
  398. // component nodes also should always be patched, because even if the
  399. // component doesn't need to update, it needs to persist the instance on to
  400. // the next vnode so that it can be properly unmounted later.
  401. (patchFlag > 0 || shapeFlag & ShapeFlags.COMPONENT) &&
  402. // the EVENTS flag is only for hydration and if it is the only flag, the
  403. // vnode should not be considered dynamic due to handler caching.
  404. patchFlag !== PatchFlags.HYDRATE_EVENTS
  405. ) {
  406. currentBlock.push(vnode)
  407. }
  408. return vnode
  409. }
  410. export function cloneVNode<T, U>(
  411. vnode: VNode<T, U>,
  412. extraProps?: Data & VNodeProps | null,
  413. mergeRef = false
  414. ): VNode<T, U> {
  415. // This is intentionally NOT using spread or extend to avoid the runtime
  416. // key enumeration cost.
  417. const { props, ref, patchFlag } = vnode
  418. const mergedProps = extraProps ? mergeProps(props || {}, extraProps) : props
  419. return {
  420. __v_isVNode: true,
  421. [ReactiveFlags.SKIP]: true,
  422. type: vnode.type,
  423. props: mergedProps,
  424. key: mergedProps && normalizeKey(mergedProps),
  425. ref:
  426. extraProps && extraProps.ref
  427. ? // #2078 in the case of <component :is="vnode" ref="extra"/>
  428. // if the vnode itself already has a ref, cloneVNode will need to merge
  429. // the refs so the single vnode can be set on multiple refs
  430. mergeRef && ref
  431. ? isArray(ref)
  432. ? ref.concat(normalizeRef(extraProps)!)
  433. : [ref, normalizeRef(extraProps)!]
  434. : normalizeRef(extraProps)
  435. : ref,
  436. scopeId: vnode.scopeId,
  437. children: vnode.children,
  438. target: vnode.target,
  439. targetAnchor: vnode.targetAnchor,
  440. staticCount: vnode.staticCount,
  441. shapeFlag: vnode.shapeFlag,
  442. // if the vnode is cloned with extra props, we can no longer assume its
  443. // existing patch flag to be reliable and need to add the FULL_PROPS flag.
  444. // note: perserve flag for fragments since they use the flag for children
  445. // fast paths only.
  446. patchFlag:
  447. extraProps && vnode.type !== Fragment
  448. ? patchFlag === -1 // hoisted node
  449. ? PatchFlags.FULL_PROPS
  450. : patchFlag | PatchFlags.FULL_PROPS
  451. : patchFlag,
  452. dynamicProps: vnode.dynamicProps,
  453. dynamicChildren: vnode.dynamicChildren,
  454. appContext: vnode.appContext,
  455. dirs: vnode.dirs,
  456. transition: vnode.transition,
  457. // These should technically only be non-null on mounted VNodes. However,
  458. // they *should* be copied for kept-alive vnodes. So we just always copy
  459. // them since them being non-null during a mount doesn't affect the logic as
  460. // they will simply be overwritten.
  461. component: vnode.component,
  462. suspense: vnode.suspense,
  463. ssContent: vnode.ssContent && cloneVNode(vnode.ssContent),
  464. ssFallback: vnode.ssFallback && cloneVNode(vnode.ssFallback),
  465. el: vnode.el,
  466. anchor: vnode.anchor
  467. }
  468. }
  469. /**
  470. * @private
  471. */
  472. export function createTextVNode(text: string = ' ', flag: number = 0): VNode {
  473. return createVNode(Text, null, text, flag)
  474. }
  475. /**
  476. * @private
  477. */
  478. export function createStaticVNode(
  479. content: string,
  480. numberOfNodes: number
  481. ): VNode {
  482. // A static vnode can contain multiple stringified elements, and the number
  483. // of elements is necessary for hydration.
  484. const vnode = createVNode(Static, null, content)
  485. vnode.staticCount = numberOfNodes
  486. return vnode
  487. }
  488. /**
  489. * @private
  490. */
  491. export function createCommentVNode(
  492. text: string = '',
  493. // when used as the v-else branch, the comment node must be created as a
  494. // block to ensure correct updates.
  495. asBlock: boolean = false
  496. ): VNode {
  497. return asBlock
  498. ? (openBlock(), createBlock(Comment, null, text))
  499. : createVNode(Comment, null, text)
  500. }
  501. export function normalizeVNode(child: VNodeChild): VNode {
  502. if (child == null || typeof child === 'boolean') {
  503. // empty placeholder
  504. return createVNode(Comment)
  505. } else if (isArray(child)) {
  506. // fragment
  507. return createVNode(Fragment, null, child)
  508. } else if (typeof child === 'object') {
  509. // already vnode, this should be the most common since compiled templates
  510. // always produce all-vnode children arrays
  511. return child.el === null ? child : cloneVNode(child)
  512. } else {
  513. // strings and numbers
  514. return createVNode(Text, null, String(child))
  515. }
  516. }
  517. // optimized normalization for template-compiled render fns
  518. export function cloneIfMounted(child: VNode): VNode {
  519. return child.el === null ? child : cloneVNode(child)
  520. }
  521. export function normalizeChildren(vnode: VNode, children: unknown) {
  522. let type = 0
  523. const { shapeFlag } = vnode
  524. if (children == null) {
  525. children = null
  526. } else if (isArray(children)) {
  527. type = ShapeFlags.ARRAY_CHILDREN
  528. } else if (typeof children === 'object') {
  529. if (shapeFlag & ShapeFlags.ELEMENT || shapeFlag & ShapeFlags.TELEPORT) {
  530. // Normalize slot to plain children for plain element and Teleport
  531. const slot = (children as any).default
  532. if (slot) {
  533. // _c marker is added by withCtx() indicating this is a compiled slot
  534. slot._c && setCompiledSlotRendering(1)
  535. normalizeChildren(vnode, slot())
  536. slot._c && setCompiledSlotRendering(-1)
  537. }
  538. return
  539. } else {
  540. type = ShapeFlags.SLOTS_CHILDREN
  541. const slotFlag = (children as RawSlots)._
  542. if (!slotFlag && !(InternalObjectKey in children!)) {
  543. // if slots are not normalized, attach context instance
  544. // (compiled / normalized slots already have context)
  545. ;(children as RawSlots)._ctx = currentRenderingInstance
  546. } else if (slotFlag === SlotFlags.FORWARDED && currentRenderingInstance) {
  547. // a child component receives forwarded slots from the parent.
  548. // its slot type is determined by its parent's slot type.
  549. if (
  550. currentRenderingInstance.vnode.patchFlag & PatchFlags.DYNAMIC_SLOTS
  551. ) {
  552. ;(children as RawSlots)._ = SlotFlags.DYNAMIC
  553. vnode.patchFlag |= PatchFlags.DYNAMIC_SLOTS
  554. } else {
  555. ;(children as RawSlots)._ = SlotFlags.STABLE
  556. }
  557. }
  558. }
  559. } else if (isFunction(children)) {
  560. children = { default: children, _ctx: currentRenderingInstance }
  561. type = ShapeFlags.SLOTS_CHILDREN
  562. } else {
  563. children = String(children)
  564. // force teleport children to array so it can be moved around
  565. if (shapeFlag & ShapeFlags.TELEPORT) {
  566. type = ShapeFlags.ARRAY_CHILDREN
  567. children = [createTextVNode(children as string)]
  568. } else {
  569. type = ShapeFlags.TEXT_CHILDREN
  570. }
  571. }
  572. vnode.children = children as VNodeNormalizedChildren
  573. vnode.shapeFlag |= type
  574. }
  575. export function mergeProps(...args: (Data & VNodeProps)[]) {
  576. const ret = extend({}, args[0])
  577. for (let i = 1; i < args.length; i++) {
  578. const toMerge = args[i]
  579. for (const key in toMerge) {
  580. if (key === 'class') {
  581. if (ret.class !== toMerge.class) {
  582. ret.class = normalizeClass([ret.class, toMerge.class])
  583. }
  584. } else if (key === 'style') {
  585. ret.style = normalizeStyle([ret.style, toMerge.style])
  586. } else if (isOn(key)) {
  587. const existing = ret[key]
  588. const incoming = toMerge[key]
  589. if (existing !== incoming) {
  590. ret[key] = existing
  591. ? [].concat(existing as any, toMerge[key] as any)
  592. : incoming
  593. }
  594. } else {
  595. ret[key] = toMerge[key]
  596. }
  597. }
  598. }
  599. return ret
  600. }