vnode.ts 16 KB

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