vnode.ts 17 KB

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