vnode.ts 16 KB

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