renderer.ts 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534
  1. import {
  2. Comment,
  3. Fragment,
  4. Static,
  5. Text,
  6. type VNode,
  7. type VNodeArrayChildren,
  8. type VNodeHook,
  9. type VNodeProps,
  10. cloneIfMounted,
  11. createVNode,
  12. invokeVNodeHook,
  13. isSameVNodeType,
  14. normalizeVNode,
  15. } from './vnode'
  16. import {
  17. type ComponentInternalInstance,
  18. type ComponentOptions,
  19. type Data,
  20. createComponentInstance,
  21. setupComponent,
  22. } from './component'
  23. import {
  24. filterSingleRoot,
  25. renderComponentRoot,
  26. shouldUpdateComponent,
  27. updateHOCHostEl,
  28. } from './componentRenderUtils'
  29. import {
  30. EMPTY_ARR,
  31. EMPTY_OBJ,
  32. NOOP,
  33. PatchFlags,
  34. ShapeFlags,
  35. getGlobalThis,
  36. invokeArrayFns,
  37. isArray,
  38. isReservedProp,
  39. } from '@vue/shared'
  40. import {
  41. type SchedulerJob,
  42. flushPostFlushCbs,
  43. flushPreFlushCbs,
  44. invalidateJob,
  45. queueJob,
  46. queuePostFlushCb,
  47. } from './scheduler'
  48. import { ReactiveEffect, pauseTracking, resetTracking } from '@vue/reactivity'
  49. import { updateProps } from './componentProps'
  50. import { updateSlots } from './componentSlots'
  51. import { popWarningContext, pushWarningContext, warn } from './warning'
  52. import { type CreateAppFunction, createAppAPI } from './apiCreateApp'
  53. import { setRef } from './rendererTemplateRef'
  54. import {
  55. type SuspenseBoundary,
  56. type SuspenseImpl,
  57. queueEffectWithSuspense,
  58. } from './components/Suspense'
  59. import type { TeleportImpl, TeleportVNode } from './components/Teleport'
  60. import { type KeepAliveContext, isKeepAlive } from './components/KeepAlive'
  61. import { isHmrUpdating, registerHMR, unregisterHMR } from './hmr'
  62. import { type RootHydrateFunction, createHydrationFunctions } from './hydration'
  63. import { invokeDirectiveHook } from './directives'
  64. import { endMeasure, startMeasure } from './profiling'
  65. import {
  66. devtoolsComponentAdded,
  67. devtoolsComponentRemoved,
  68. devtoolsComponentUpdated,
  69. setDevtoolsHook,
  70. } from './devtools'
  71. import { initFeatureFlags } from './featureFlags'
  72. import { isAsyncWrapper } from './apiAsyncComponent'
  73. import { isCompatEnabled } from './compat/compatConfig'
  74. import { DeprecationTypes } from './compat/compatConfig'
  75. import type { TransitionHooks } from './components/BaseTransition'
  76. export interface Renderer<HostElement = RendererElement> {
  77. render: RootRenderFunction<HostElement>
  78. createApp: CreateAppFunction<HostElement>
  79. }
  80. export interface HydrationRenderer extends Renderer<Element | ShadowRoot> {
  81. hydrate: RootHydrateFunction
  82. }
  83. export type ElementNamespace = 'svg' | 'mathml' | undefined
  84. export type RootRenderFunction<HostElement = RendererElement> = (
  85. vnode: VNode | null,
  86. container: HostElement,
  87. namespace?: ElementNamespace,
  88. ) => void
  89. export interface RendererOptions<
  90. HostNode = RendererNode,
  91. HostElement = RendererElement,
  92. > {
  93. patchProp(
  94. el: HostElement,
  95. key: string,
  96. prevValue: any,
  97. nextValue: any,
  98. namespace?: ElementNamespace,
  99. prevChildren?: VNode<HostNode, HostElement>[],
  100. parentComponent?: ComponentInternalInstance | null,
  101. parentSuspense?: SuspenseBoundary | null,
  102. unmountChildren?: UnmountChildrenFn,
  103. ): void
  104. insert(el: HostNode, parent: HostElement, anchor?: HostNode | null): void
  105. remove(el: HostNode): void
  106. createElement(
  107. type: string,
  108. namespace?: ElementNamespace,
  109. isCustomizedBuiltIn?: string,
  110. vnodeProps?: (VNodeProps & { [key: string]: any }) | null,
  111. ): HostElement
  112. createText(text: string): HostNode
  113. createComment(text: string): HostNode
  114. setText(node: HostNode, text: string): void
  115. setElementText(node: HostElement, text: string): void
  116. parentNode(node: HostNode): HostElement | null
  117. nextSibling(node: HostNode): HostNode | null
  118. querySelector?(selector: string): HostElement | null
  119. setScopeId?(el: HostElement, id: string): void
  120. cloneNode?(node: HostNode): HostNode
  121. insertStaticContent?(
  122. content: string,
  123. parent: HostElement,
  124. anchor: HostNode | null,
  125. namespace: ElementNamespace,
  126. start?: HostNode | null,
  127. end?: HostNode | null,
  128. ): [HostNode, HostNode]
  129. }
  130. // Renderer Node can technically be any object in the context of core renderer
  131. // logic - they are never directly operated on and always passed to the node op
  132. // functions provided via options, so the internal constraint is really just
  133. // a generic object.
  134. export interface RendererNode {
  135. [key: string]: any
  136. }
  137. export interface RendererElement extends RendererNode {}
  138. // An object exposing the internals of a renderer, passed to tree-shakeable
  139. // features so that they can be decoupled from this file. Keys are shortened
  140. // to optimize bundle size.
  141. export interface RendererInternals<
  142. HostNode = RendererNode,
  143. HostElement = RendererElement,
  144. > {
  145. p: PatchFn
  146. um: UnmountFn
  147. r: RemoveFn
  148. m: MoveFn
  149. mt: MountComponentFn
  150. mc: MountChildrenFn
  151. pc: PatchChildrenFn
  152. pbc: PatchBlockChildrenFn
  153. n: NextFn
  154. o: RendererOptions<HostNode, HostElement>
  155. }
  156. // These functions are created inside a closure and therefore their types cannot
  157. // be directly exported. In order to avoid maintaining function signatures in
  158. // two places, we declare them once here and use them inside the closure.
  159. type PatchFn = (
  160. n1: VNode | null, // null means this is a mount
  161. n2: VNode,
  162. container: RendererElement,
  163. anchor?: RendererNode | null,
  164. parentComponent?: ComponentInternalInstance | null,
  165. parentSuspense?: SuspenseBoundary | null,
  166. namespace?: ElementNamespace,
  167. slotScopeIds?: string[] | null,
  168. optimized?: boolean,
  169. ) => void
  170. type MountChildrenFn = (
  171. children: VNodeArrayChildren,
  172. container: RendererElement,
  173. anchor: RendererNode | null,
  174. parentComponent: ComponentInternalInstance | null,
  175. parentSuspense: SuspenseBoundary | null,
  176. namespace: ElementNamespace,
  177. slotScopeIds: string[] | null,
  178. optimized: boolean,
  179. start?: number,
  180. ) => void
  181. type PatchChildrenFn = (
  182. n1: VNode | null,
  183. n2: VNode,
  184. container: RendererElement,
  185. anchor: RendererNode | null,
  186. parentComponent: ComponentInternalInstance | null,
  187. parentSuspense: SuspenseBoundary | null,
  188. namespace: ElementNamespace,
  189. slotScopeIds: string[] | null,
  190. optimized: boolean,
  191. ) => void
  192. type PatchBlockChildrenFn = (
  193. oldChildren: VNode[],
  194. newChildren: VNode[],
  195. fallbackContainer: RendererElement,
  196. parentComponent: ComponentInternalInstance | null,
  197. parentSuspense: SuspenseBoundary | null,
  198. namespace: ElementNamespace,
  199. slotScopeIds: string[] | null,
  200. ) => void
  201. type MoveFn = (
  202. vnode: VNode,
  203. container: RendererElement,
  204. anchor: RendererNode | null,
  205. type: MoveType,
  206. parentSuspense?: SuspenseBoundary | null,
  207. ) => void
  208. type NextFn = (vnode: VNode) => RendererNode | null
  209. type UnmountFn = (
  210. vnode: VNode,
  211. parentComponent: ComponentInternalInstance | null,
  212. parentSuspense: SuspenseBoundary | null,
  213. doRemove?: boolean,
  214. optimized?: boolean,
  215. ) => void
  216. type RemoveFn = (vnode: VNode) => void
  217. type UnmountChildrenFn = (
  218. children: VNode[],
  219. parentComponent: ComponentInternalInstance | null,
  220. parentSuspense: SuspenseBoundary | null,
  221. doRemove?: boolean,
  222. optimized?: boolean,
  223. start?: number,
  224. ) => void
  225. export type MountComponentFn = (
  226. initialVNode: VNode,
  227. container: RendererElement,
  228. anchor: RendererNode | null,
  229. parentComponent: ComponentInternalInstance | null,
  230. parentSuspense: SuspenseBoundary | null,
  231. namespace: ElementNamespace,
  232. optimized: boolean,
  233. ) => void
  234. type ProcessTextOrCommentFn = (
  235. n1: VNode | null,
  236. n2: VNode,
  237. container: RendererElement,
  238. anchor: RendererNode | null,
  239. ) => void
  240. export type SetupRenderEffectFn = (
  241. instance: ComponentInternalInstance,
  242. initialVNode: VNode,
  243. container: RendererElement,
  244. anchor: RendererNode | null,
  245. parentSuspense: SuspenseBoundary | null,
  246. namespace: ElementNamespace,
  247. optimized: boolean,
  248. ) => void
  249. export enum MoveType {
  250. ENTER,
  251. LEAVE,
  252. REORDER,
  253. }
  254. export const queuePostRenderEffect = __FEATURE_SUSPENSE__
  255. ? __TEST__
  256. ? // vitest can't seem to handle eager circular dependency
  257. (fn: Function | Function[], suspense: SuspenseBoundary | null) =>
  258. queueEffectWithSuspense(fn, suspense)
  259. : queueEffectWithSuspense
  260. : queuePostFlushCb
  261. /**
  262. * The createRenderer function accepts two generic arguments:
  263. * HostNode and HostElement, corresponding to Node and Element types in the
  264. * host environment. For example, for runtime-dom, HostNode would be the DOM
  265. * `Node` interface and HostElement would be the DOM `Element` interface.
  266. *
  267. * Custom renderers can pass in the platform specific types like this:
  268. *
  269. * ``` js
  270. * const { render, createApp } = createRenderer<Node, Element>({
  271. * patchProp,
  272. * ...nodeOps
  273. * })
  274. * ```
  275. */
  276. export function createRenderer<
  277. HostNode = RendererNode,
  278. HostElement = RendererElement,
  279. >(options: RendererOptions<HostNode, HostElement>) {
  280. return baseCreateRenderer<HostNode, HostElement>(options)
  281. }
  282. // Separate API for creating hydration-enabled renderer.
  283. // Hydration logic is only used when calling this function, making it
  284. // tree-shakable.
  285. export function createHydrationRenderer(
  286. options: RendererOptions<Node, Element>,
  287. ) {
  288. return baseCreateRenderer(options, createHydrationFunctions)
  289. }
  290. // overload 1: no hydration
  291. function baseCreateRenderer<
  292. HostNode = RendererNode,
  293. HostElement = RendererElement,
  294. >(options: RendererOptions<HostNode, HostElement>): Renderer<HostElement>
  295. // overload 2: with hydration
  296. function baseCreateRenderer(
  297. options: RendererOptions<Node, Element>,
  298. createHydrationFns: typeof createHydrationFunctions,
  299. ): HydrationRenderer
  300. // implementation
  301. function baseCreateRenderer(
  302. options: RendererOptions,
  303. createHydrationFns?: typeof createHydrationFunctions,
  304. ): any {
  305. // compile-time feature flags check
  306. if (__ESM_BUNDLER__ && !__TEST__) {
  307. initFeatureFlags()
  308. }
  309. const target = getGlobalThis()
  310. target.__VUE__ = true
  311. if (__DEV__ || __FEATURE_PROD_DEVTOOLS__) {
  312. setDevtoolsHook(target.__VUE_DEVTOOLS_GLOBAL_HOOK__, target)
  313. }
  314. const {
  315. insert: hostInsert,
  316. remove: hostRemove,
  317. patchProp: hostPatchProp,
  318. createElement: hostCreateElement,
  319. createText: hostCreateText,
  320. createComment: hostCreateComment,
  321. setText: hostSetText,
  322. setElementText: hostSetElementText,
  323. parentNode: hostParentNode,
  324. nextSibling: hostNextSibling,
  325. setScopeId: hostSetScopeId = NOOP,
  326. insertStaticContent: hostInsertStaticContent,
  327. } = options
  328. // Note: functions inside this closure should use `const xxx = () => {}`
  329. // style in order to prevent being inlined by minifiers.
  330. const patch: PatchFn = (
  331. n1,
  332. n2,
  333. container,
  334. anchor = null,
  335. parentComponent = null,
  336. parentSuspense = null,
  337. namespace = undefined,
  338. slotScopeIds = null,
  339. optimized = __DEV__ && isHmrUpdating ? false : !!n2.dynamicChildren,
  340. ) => {
  341. if (n1 === n2) {
  342. return
  343. }
  344. // patching & not same type, unmount old tree
  345. if (n1 && !isSameVNodeType(n1, n2)) {
  346. anchor = getNextHostNode(n1)
  347. unmount(n1, parentComponent, parentSuspense, true)
  348. n1 = null
  349. }
  350. if (n2.patchFlag === PatchFlags.BAIL) {
  351. optimized = false
  352. n2.dynamicChildren = null
  353. }
  354. const { type, ref, shapeFlag } = n2
  355. switch (type) {
  356. case Text:
  357. processText(n1, n2, container, anchor)
  358. break
  359. case Comment:
  360. processCommentNode(n1, n2, container, anchor)
  361. break
  362. case Static:
  363. if (n1 == null) {
  364. mountStaticNode(n2, container, anchor, namespace)
  365. } else if (__DEV__) {
  366. patchStaticNode(n1, n2, container, namespace)
  367. }
  368. break
  369. case Fragment:
  370. processFragment(
  371. n1,
  372. n2,
  373. container,
  374. anchor,
  375. parentComponent,
  376. parentSuspense,
  377. namespace,
  378. slotScopeIds,
  379. optimized,
  380. )
  381. break
  382. default:
  383. if (shapeFlag & ShapeFlags.ELEMENT) {
  384. processElement(
  385. n1,
  386. n2,
  387. container,
  388. anchor,
  389. parentComponent,
  390. parentSuspense,
  391. namespace,
  392. slotScopeIds,
  393. optimized,
  394. )
  395. } else if (shapeFlag & ShapeFlags.COMPONENT) {
  396. processComponent(
  397. n1,
  398. n2,
  399. container,
  400. anchor,
  401. parentComponent,
  402. parentSuspense,
  403. namespace,
  404. slotScopeIds,
  405. optimized,
  406. )
  407. } else if (shapeFlag & ShapeFlags.TELEPORT) {
  408. ;(type as typeof TeleportImpl).process(
  409. n1 as TeleportVNode,
  410. n2 as TeleportVNode,
  411. container,
  412. anchor,
  413. parentComponent,
  414. parentSuspense,
  415. namespace,
  416. slotScopeIds,
  417. optimized,
  418. internals,
  419. )
  420. } else if (__FEATURE_SUSPENSE__ && shapeFlag & ShapeFlags.SUSPENSE) {
  421. ;(type as typeof SuspenseImpl).process(
  422. n1,
  423. n2,
  424. container,
  425. anchor,
  426. parentComponent,
  427. parentSuspense,
  428. namespace,
  429. slotScopeIds,
  430. optimized,
  431. internals,
  432. )
  433. } else if (__DEV__) {
  434. warn('Invalid VNode type:', type, `(${typeof type})`)
  435. }
  436. }
  437. // set ref
  438. if (ref != null && parentComponent) {
  439. setRef(ref, n1 && n1.ref, parentSuspense, n2 || n1, !n2)
  440. }
  441. }
  442. const processText: ProcessTextOrCommentFn = (n1, n2, container, anchor) => {
  443. if (n1 == null) {
  444. hostInsert(
  445. (n2.el = hostCreateText(n2.children as string)),
  446. container,
  447. anchor,
  448. )
  449. } else {
  450. const el = (n2.el = n1.el!)
  451. if (n2.children !== n1.children) {
  452. hostSetText(el, n2.children as string)
  453. }
  454. }
  455. }
  456. const processCommentNode: ProcessTextOrCommentFn = (
  457. n1,
  458. n2,
  459. container,
  460. anchor,
  461. ) => {
  462. if (n1 == null) {
  463. hostInsert(
  464. (n2.el = hostCreateComment((n2.children as string) || '')),
  465. container,
  466. anchor,
  467. )
  468. } else {
  469. // there's no support for dynamic comments
  470. n2.el = n1.el
  471. }
  472. }
  473. const mountStaticNode = (
  474. n2: VNode,
  475. container: RendererElement,
  476. anchor: RendererNode | null,
  477. namespace: ElementNamespace,
  478. ) => {
  479. // static nodes are only present when used with compiler-dom/runtime-dom
  480. // which guarantees presence of hostInsertStaticContent.
  481. ;[n2.el, n2.anchor] = hostInsertStaticContent!(
  482. n2.children as string,
  483. container,
  484. anchor,
  485. namespace,
  486. n2.el,
  487. n2.anchor,
  488. )
  489. }
  490. /**
  491. * Dev / HMR only
  492. */
  493. const patchStaticNode = (
  494. n1: VNode,
  495. n2: VNode,
  496. container: RendererElement,
  497. namespace: ElementNamespace,
  498. ) => {
  499. // static nodes are only patched during dev for HMR
  500. if (n2.children !== n1.children) {
  501. const anchor = hostNextSibling(n1.anchor!)
  502. // remove existing
  503. removeStaticNode(n1)
  504. // insert new
  505. ;[n2.el, n2.anchor] = hostInsertStaticContent!(
  506. n2.children as string,
  507. container,
  508. anchor,
  509. namespace,
  510. )
  511. } else {
  512. n2.el = n1.el
  513. n2.anchor = n1.anchor
  514. }
  515. }
  516. const moveStaticNode = (
  517. { el, anchor }: VNode,
  518. container: RendererElement,
  519. nextSibling: RendererNode | null,
  520. ) => {
  521. let next
  522. while (el && el !== anchor) {
  523. next = hostNextSibling(el)
  524. hostInsert(el, container, nextSibling)
  525. el = next
  526. }
  527. hostInsert(anchor!, container, nextSibling)
  528. }
  529. const removeStaticNode = ({ el, anchor }: VNode) => {
  530. let next
  531. while (el && el !== anchor) {
  532. next = hostNextSibling(el)
  533. hostRemove(el)
  534. el = next
  535. }
  536. hostRemove(anchor!)
  537. }
  538. const processElement = (
  539. n1: VNode | null,
  540. n2: VNode,
  541. container: RendererElement,
  542. anchor: RendererNode | null,
  543. parentComponent: ComponentInternalInstance | null,
  544. parentSuspense: SuspenseBoundary | null,
  545. namespace: ElementNamespace,
  546. slotScopeIds: string[] | null,
  547. optimized: boolean,
  548. ) => {
  549. if (n2.type === 'svg') {
  550. namespace = 'svg'
  551. } else if (n2.type === 'math') {
  552. namespace = 'mathml'
  553. }
  554. if (n1 == null) {
  555. mountElement(
  556. n2,
  557. container,
  558. anchor,
  559. parentComponent,
  560. parentSuspense,
  561. namespace,
  562. slotScopeIds,
  563. optimized,
  564. )
  565. } else {
  566. patchElement(
  567. n1,
  568. n2,
  569. parentComponent,
  570. parentSuspense,
  571. namespace,
  572. slotScopeIds,
  573. optimized,
  574. )
  575. }
  576. }
  577. const mountElement = (
  578. vnode: VNode,
  579. container: RendererElement,
  580. anchor: RendererNode | null,
  581. parentComponent: ComponentInternalInstance | null,
  582. parentSuspense: SuspenseBoundary | null,
  583. namespace: ElementNamespace,
  584. slotScopeIds: string[] | null,
  585. optimized: boolean,
  586. ) => {
  587. let el: RendererElement
  588. let vnodeHook: VNodeHook | undefined | null
  589. const { props, shapeFlag, transition, dirs } = vnode
  590. el = vnode.el = hostCreateElement(
  591. vnode.type as string,
  592. namespace,
  593. props && props.is,
  594. props,
  595. )
  596. // mount children first, since some props may rely on child content
  597. // being already rendered, e.g. `<select value>`
  598. if (shapeFlag & ShapeFlags.TEXT_CHILDREN) {
  599. hostSetElementText(el, vnode.children as string)
  600. } else if (shapeFlag & ShapeFlags.ARRAY_CHILDREN) {
  601. mountChildren(
  602. vnode.children as VNodeArrayChildren,
  603. el,
  604. null,
  605. parentComponent,
  606. parentSuspense,
  607. resolveChildrenNamespace(vnode, namespace),
  608. slotScopeIds,
  609. optimized,
  610. )
  611. }
  612. if (dirs) {
  613. invokeDirectiveHook(vnode, null, parentComponent, 'created')
  614. }
  615. // scopeId
  616. setScopeId(el, vnode, vnode.scopeId, slotScopeIds, parentComponent)
  617. // props
  618. if (props) {
  619. for (const key in props) {
  620. if (key !== 'value' && !isReservedProp(key)) {
  621. hostPatchProp(
  622. el,
  623. key,
  624. null,
  625. props[key],
  626. namespace,
  627. vnode.children as VNode[],
  628. parentComponent,
  629. parentSuspense,
  630. unmountChildren,
  631. )
  632. }
  633. }
  634. /**
  635. * Special case for setting value on DOM elements:
  636. * - it can be order-sensitive (e.g. should be set *after* min/max, #2325, #4024)
  637. * - it needs to be forced (#1471)
  638. * #2353 proposes adding another renderer option to configure this, but
  639. * the properties affects are so finite it is worth special casing it
  640. * here to reduce the complexity. (Special casing it also should not
  641. * affect non-DOM renderers)
  642. */
  643. if ('value' in props) {
  644. hostPatchProp(el, 'value', null, props.value, namespace)
  645. }
  646. if ((vnodeHook = props.onVnodeBeforeMount)) {
  647. invokeVNodeHook(vnodeHook, parentComponent, vnode)
  648. }
  649. }
  650. if (__DEV__ || __FEATURE_PROD_DEVTOOLS__) {
  651. Object.defineProperty(el, '__vnode', {
  652. value: vnode,
  653. enumerable: false,
  654. })
  655. Object.defineProperty(el, '__vueParentComponent', {
  656. value: parentComponent,
  657. enumerable: false,
  658. })
  659. }
  660. if (dirs) {
  661. invokeDirectiveHook(vnode, null, parentComponent, 'beforeMount')
  662. }
  663. // #1583 For inside suspense + suspense not resolved case, enter hook should call when suspense resolved
  664. // #1689 For inside suspense + suspense resolved case, just call it
  665. const needCallTransitionHooks = needTransition(parentSuspense, transition)
  666. if (needCallTransitionHooks) {
  667. transition!.beforeEnter(el)
  668. }
  669. hostInsert(el, container, anchor)
  670. if (
  671. (vnodeHook = props && props.onVnodeMounted) ||
  672. needCallTransitionHooks ||
  673. dirs
  674. ) {
  675. queuePostRenderEffect(() => {
  676. vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, vnode)
  677. needCallTransitionHooks && transition!.enter(el)
  678. dirs && invokeDirectiveHook(vnode, null, parentComponent, 'mounted')
  679. }, parentSuspense)
  680. }
  681. }
  682. const setScopeId = (
  683. el: RendererElement,
  684. vnode: VNode,
  685. scopeId: string | null,
  686. slotScopeIds: string[] | null,
  687. parentComponent: ComponentInternalInstance | null,
  688. ) => {
  689. if (scopeId) {
  690. hostSetScopeId(el, scopeId)
  691. }
  692. if (slotScopeIds) {
  693. for (let i = 0; i < slotScopeIds.length; i++) {
  694. hostSetScopeId(el, slotScopeIds[i])
  695. }
  696. }
  697. if (parentComponent) {
  698. let subTree = parentComponent.subTree
  699. if (
  700. __DEV__ &&
  701. subTree.patchFlag > 0 &&
  702. subTree.patchFlag & PatchFlags.DEV_ROOT_FRAGMENT
  703. ) {
  704. subTree =
  705. filterSingleRoot(subTree.children as VNodeArrayChildren) || subTree
  706. }
  707. if (vnode === subTree) {
  708. const parentVNode = parentComponent.vnode
  709. setScopeId(
  710. el,
  711. parentVNode,
  712. parentVNode.scopeId,
  713. parentVNode.slotScopeIds,
  714. parentComponent.parent,
  715. )
  716. }
  717. }
  718. }
  719. const mountChildren: MountChildrenFn = (
  720. children,
  721. container,
  722. anchor,
  723. parentComponent,
  724. parentSuspense,
  725. namespace: ElementNamespace,
  726. slotScopeIds,
  727. optimized,
  728. start = 0,
  729. ) => {
  730. for (let i = start; i < children.length; i++) {
  731. const child = (children[i] = optimized
  732. ? cloneIfMounted(children[i] as VNode)
  733. : normalizeVNode(children[i]))
  734. patch(
  735. null,
  736. child,
  737. container,
  738. anchor,
  739. parentComponent,
  740. parentSuspense,
  741. namespace,
  742. slotScopeIds,
  743. optimized,
  744. )
  745. }
  746. }
  747. const patchElement = (
  748. n1: VNode,
  749. n2: VNode,
  750. parentComponent: ComponentInternalInstance | null,
  751. parentSuspense: SuspenseBoundary | null,
  752. namespace: ElementNamespace,
  753. slotScopeIds: string[] | null,
  754. optimized: boolean,
  755. ) => {
  756. const el = (n2.el = n1.el!)
  757. let { patchFlag, dynamicChildren, dirs } = n2
  758. // #1426 take the old vnode's patch flag into account since user may clone a
  759. // compiler-generated vnode, which de-opts to FULL_PROPS
  760. patchFlag |= n1.patchFlag & PatchFlags.FULL_PROPS
  761. const oldProps = n1.props || EMPTY_OBJ
  762. const newProps = n2.props || EMPTY_OBJ
  763. let vnodeHook: VNodeHook | undefined | null
  764. // disable recurse in beforeUpdate hooks
  765. parentComponent && toggleRecurse(parentComponent, false)
  766. if ((vnodeHook = newProps.onVnodeBeforeUpdate)) {
  767. invokeVNodeHook(vnodeHook, parentComponent, n2, n1)
  768. }
  769. if (dirs) {
  770. invokeDirectiveHook(n2, n1, parentComponent, 'beforeUpdate')
  771. }
  772. parentComponent && toggleRecurse(parentComponent, true)
  773. if (__DEV__ && isHmrUpdating) {
  774. // HMR updated, force full diff
  775. patchFlag = 0
  776. optimized = false
  777. dynamicChildren = null
  778. }
  779. if (dynamicChildren) {
  780. patchBlockChildren(
  781. n1.dynamicChildren!,
  782. dynamicChildren,
  783. el,
  784. parentComponent,
  785. parentSuspense,
  786. resolveChildrenNamespace(n2, namespace),
  787. slotScopeIds,
  788. )
  789. if (__DEV__) {
  790. // necessary for HMR
  791. traverseStaticChildren(n1, n2)
  792. }
  793. } else if (!optimized) {
  794. // full diff
  795. patchChildren(
  796. n1,
  797. n2,
  798. el,
  799. null,
  800. parentComponent,
  801. parentSuspense,
  802. resolveChildrenNamespace(n2, namespace),
  803. slotScopeIds,
  804. false,
  805. )
  806. }
  807. if (patchFlag > 0) {
  808. // the presence of a patchFlag means this element's render code was
  809. // generated by the compiler and can take the fast path.
  810. // in this path old node and new node are guaranteed to have the same shape
  811. // (i.e. at the exact same position in the source template)
  812. if (patchFlag & PatchFlags.FULL_PROPS) {
  813. // element props contain dynamic keys, full diff needed
  814. patchProps(
  815. el,
  816. n2,
  817. oldProps,
  818. newProps,
  819. parentComponent,
  820. parentSuspense,
  821. namespace,
  822. )
  823. } else {
  824. // class
  825. // this flag is matched when the element has dynamic class bindings.
  826. if (patchFlag & PatchFlags.CLASS) {
  827. if (oldProps.class !== newProps.class) {
  828. hostPatchProp(el, 'class', null, newProps.class, namespace)
  829. }
  830. }
  831. // style
  832. // this flag is matched when the element has dynamic style bindings
  833. if (patchFlag & PatchFlags.STYLE) {
  834. hostPatchProp(el, 'style', oldProps.style, newProps.style, namespace)
  835. }
  836. // props
  837. // This flag is matched when the element has dynamic prop/attr bindings
  838. // other than class and style. The keys of dynamic prop/attrs are saved for
  839. // faster iteration.
  840. // Note dynamic keys like :[foo]="bar" will cause this optimization to
  841. // bail out and go through a full diff because we need to unset the old key
  842. if (patchFlag & PatchFlags.PROPS) {
  843. // if the flag is present then dynamicProps must be non-null
  844. const propsToUpdate = n2.dynamicProps!
  845. for (let i = 0; i < propsToUpdate.length; i++) {
  846. const key = propsToUpdate[i]
  847. const prev = oldProps[key]
  848. const next = newProps[key]
  849. // #1471 force patch value
  850. if (next !== prev || key === 'value') {
  851. hostPatchProp(
  852. el,
  853. key,
  854. prev,
  855. next,
  856. namespace,
  857. n1.children as VNode[],
  858. parentComponent,
  859. parentSuspense,
  860. unmountChildren,
  861. )
  862. }
  863. }
  864. }
  865. }
  866. // text
  867. // This flag is matched when the element has only dynamic text children.
  868. if (patchFlag & PatchFlags.TEXT) {
  869. if (n1.children !== n2.children) {
  870. hostSetElementText(el, n2.children as string)
  871. }
  872. }
  873. } else if (!optimized && dynamicChildren == null) {
  874. // unoptimized, full diff
  875. patchProps(
  876. el,
  877. n2,
  878. oldProps,
  879. newProps,
  880. parentComponent,
  881. parentSuspense,
  882. namespace,
  883. )
  884. }
  885. if ((vnodeHook = newProps.onVnodeUpdated) || dirs) {
  886. queuePostRenderEffect(() => {
  887. vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, n2, n1)
  888. dirs && invokeDirectiveHook(n2, n1, parentComponent, 'updated')
  889. }, parentSuspense)
  890. }
  891. }
  892. // The fast path for blocks.
  893. const patchBlockChildren: PatchBlockChildrenFn = (
  894. oldChildren,
  895. newChildren,
  896. fallbackContainer,
  897. parentComponent,
  898. parentSuspense,
  899. namespace: ElementNamespace,
  900. slotScopeIds,
  901. ) => {
  902. for (let i = 0; i < newChildren.length; i++) {
  903. const oldVNode = oldChildren[i]
  904. const newVNode = newChildren[i]
  905. // Determine the container (parent element) for the patch.
  906. const container =
  907. // oldVNode may be an errored async setup() component inside Suspense
  908. // which will not have a mounted element
  909. oldVNode.el &&
  910. // - In the case of a Fragment, we need to provide the actual parent
  911. // of the Fragment itself so it can move its children.
  912. (oldVNode.type === Fragment ||
  913. // - In the case of different nodes, there is going to be a replacement
  914. // which also requires the correct parent container
  915. !isSameVNodeType(oldVNode, newVNode) ||
  916. // - In the case of a component, it could contain anything.
  917. oldVNode.shapeFlag & (ShapeFlags.COMPONENT | ShapeFlags.TELEPORT))
  918. ? hostParentNode(oldVNode.el)!
  919. : // In other cases, the parent container is not actually used so we
  920. // just pass the block element here to avoid a DOM parentNode call.
  921. fallbackContainer
  922. patch(
  923. oldVNode,
  924. newVNode,
  925. container,
  926. null,
  927. parentComponent,
  928. parentSuspense,
  929. namespace,
  930. slotScopeIds,
  931. true,
  932. )
  933. }
  934. }
  935. const patchProps = (
  936. el: RendererElement,
  937. vnode: VNode,
  938. oldProps: Data,
  939. newProps: Data,
  940. parentComponent: ComponentInternalInstance | null,
  941. parentSuspense: SuspenseBoundary | null,
  942. namespace: ElementNamespace,
  943. ) => {
  944. if (oldProps !== newProps) {
  945. if (oldProps !== EMPTY_OBJ) {
  946. for (const key in oldProps) {
  947. if (!isReservedProp(key) && !(key in newProps)) {
  948. hostPatchProp(
  949. el,
  950. key,
  951. oldProps[key],
  952. null,
  953. namespace,
  954. vnode.children as VNode[],
  955. parentComponent,
  956. parentSuspense,
  957. unmountChildren,
  958. )
  959. }
  960. }
  961. }
  962. for (const key in newProps) {
  963. // empty string is not valid prop
  964. if (isReservedProp(key)) continue
  965. const next = newProps[key]
  966. const prev = oldProps[key]
  967. // defer patching value
  968. if (next !== prev && key !== 'value') {
  969. hostPatchProp(
  970. el,
  971. key,
  972. prev,
  973. next,
  974. namespace,
  975. vnode.children as VNode[],
  976. parentComponent,
  977. parentSuspense,
  978. unmountChildren,
  979. )
  980. }
  981. }
  982. if ('value' in newProps) {
  983. hostPatchProp(el, 'value', oldProps.value, newProps.value, namespace)
  984. }
  985. }
  986. }
  987. const processFragment = (
  988. n1: VNode | null,
  989. n2: VNode,
  990. container: RendererElement,
  991. anchor: RendererNode | null,
  992. parentComponent: ComponentInternalInstance | null,
  993. parentSuspense: SuspenseBoundary | null,
  994. namespace: ElementNamespace,
  995. slotScopeIds: string[] | null,
  996. optimized: boolean,
  997. ) => {
  998. const fragmentStartAnchor = (n2.el = n1 ? n1.el : hostCreateText(''))!
  999. const fragmentEndAnchor = (n2.anchor = n1 ? n1.anchor : hostCreateText(''))!
  1000. let { patchFlag, dynamicChildren, slotScopeIds: fragmentSlotScopeIds } = n2
  1001. if (
  1002. __DEV__ &&
  1003. // #5523 dev root fragment may inherit directives
  1004. (isHmrUpdating || patchFlag & PatchFlags.DEV_ROOT_FRAGMENT)
  1005. ) {
  1006. // HMR updated / Dev root fragment (w/ comments), force full diff
  1007. patchFlag = 0
  1008. optimized = false
  1009. dynamicChildren = null
  1010. }
  1011. // check if this is a slot fragment with :slotted scope ids
  1012. if (fragmentSlotScopeIds) {
  1013. slotScopeIds = slotScopeIds
  1014. ? slotScopeIds.concat(fragmentSlotScopeIds)
  1015. : fragmentSlotScopeIds
  1016. }
  1017. if (n1 == null) {
  1018. hostInsert(fragmentStartAnchor, container, anchor)
  1019. hostInsert(fragmentEndAnchor, container, anchor)
  1020. // a fragment can only have array children
  1021. // since they are either generated by the compiler, or implicitly created
  1022. // from arrays.
  1023. mountChildren(
  1024. // #10007
  1025. // such fragment like `<></>` will be compiled into
  1026. // a fragment which doesn't have a children.
  1027. // In this case fallback to an empty array
  1028. (n2.children || []) as VNodeArrayChildren,
  1029. container,
  1030. fragmentEndAnchor,
  1031. parentComponent,
  1032. parentSuspense,
  1033. namespace,
  1034. slotScopeIds,
  1035. optimized,
  1036. )
  1037. } else {
  1038. if (
  1039. patchFlag > 0 &&
  1040. patchFlag & PatchFlags.STABLE_FRAGMENT &&
  1041. dynamicChildren &&
  1042. // #2715 the previous fragment could've been a BAILed one as a result
  1043. // of renderSlot() with no valid children
  1044. n1.dynamicChildren
  1045. ) {
  1046. // a stable fragment (template root or <template v-for>) doesn't need to
  1047. // patch children order, but it may contain dynamicChildren.
  1048. patchBlockChildren(
  1049. n1.dynamicChildren,
  1050. dynamicChildren,
  1051. container,
  1052. parentComponent,
  1053. parentSuspense,
  1054. namespace,
  1055. slotScopeIds,
  1056. )
  1057. if (__DEV__) {
  1058. // necessary for HMR
  1059. traverseStaticChildren(n1, n2)
  1060. } else if (
  1061. // #2080 if the stable fragment has a key, it's a <template v-for> that may
  1062. // get moved around. Make sure all root level vnodes inherit el.
  1063. // #2134 or if it's a component root, it may also get moved around
  1064. // as the component is being moved.
  1065. n2.key != null ||
  1066. (parentComponent && n2 === parentComponent.subTree)
  1067. ) {
  1068. traverseStaticChildren(n1, n2, true /* shallow */)
  1069. }
  1070. } else {
  1071. // keyed / unkeyed, or manual fragments.
  1072. // for keyed & unkeyed, since they are compiler generated from v-for,
  1073. // each child is guaranteed to be a block so the fragment will never
  1074. // have dynamicChildren.
  1075. patchChildren(
  1076. n1,
  1077. n2,
  1078. container,
  1079. fragmentEndAnchor,
  1080. parentComponent,
  1081. parentSuspense,
  1082. namespace,
  1083. slotScopeIds,
  1084. optimized,
  1085. )
  1086. }
  1087. }
  1088. }
  1089. const processComponent = (
  1090. n1: VNode | null,
  1091. n2: VNode,
  1092. container: RendererElement,
  1093. anchor: RendererNode | null,
  1094. parentComponent: ComponentInternalInstance | null,
  1095. parentSuspense: SuspenseBoundary | null,
  1096. namespace: ElementNamespace,
  1097. slotScopeIds: string[] | null,
  1098. optimized: boolean,
  1099. ) => {
  1100. n2.slotScopeIds = slotScopeIds
  1101. if (n1 == null) {
  1102. if (n2.shapeFlag & ShapeFlags.COMPONENT_KEPT_ALIVE) {
  1103. ;(parentComponent!.ctx as KeepAliveContext).activate(
  1104. n2,
  1105. container,
  1106. anchor,
  1107. namespace,
  1108. optimized,
  1109. )
  1110. } else {
  1111. mountComponent(
  1112. n2,
  1113. container,
  1114. anchor,
  1115. parentComponent,
  1116. parentSuspense,
  1117. namespace,
  1118. optimized,
  1119. )
  1120. }
  1121. } else {
  1122. updateComponent(n1, n2, optimized)
  1123. }
  1124. }
  1125. const mountComponent: MountComponentFn = (
  1126. initialVNode,
  1127. container,
  1128. anchor,
  1129. parentComponent,
  1130. parentSuspense,
  1131. namespace: ElementNamespace,
  1132. optimized,
  1133. ) => {
  1134. // 2.x compat may pre-create the component instance before actually
  1135. // mounting
  1136. const compatMountInstance =
  1137. __COMPAT__ && initialVNode.isCompatRoot && initialVNode.component
  1138. const instance: ComponentInternalInstance =
  1139. compatMountInstance ||
  1140. (initialVNode.component = createComponentInstance(
  1141. initialVNode,
  1142. parentComponent,
  1143. parentSuspense,
  1144. ))
  1145. if (__DEV__ && instance.type.__hmrId) {
  1146. registerHMR(instance)
  1147. }
  1148. if (__DEV__) {
  1149. pushWarningContext(initialVNode)
  1150. startMeasure(instance, `mount`)
  1151. }
  1152. // inject renderer internals for keepAlive
  1153. if (isKeepAlive(initialVNode)) {
  1154. ;(instance.ctx as KeepAliveContext).renderer = internals
  1155. }
  1156. // resolve props and slots for setup context
  1157. if (!(__COMPAT__ && compatMountInstance)) {
  1158. if (__DEV__) {
  1159. startMeasure(instance, `init`)
  1160. }
  1161. setupComponent(instance)
  1162. if (__DEV__) {
  1163. endMeasure(instance, `init`)
  1164. }
  1165. }
  1166. // setup() is async. This component relies on async logic to be resolved
  1167. // before proceeding
  1168. if (__FEATURE_SUSPENSE__ && instance.asyncDep) {
  1169. parentSuspense && parentSuspense.registerDep(instance, setupRenderEffect)
  1170. // Give it a placeholder if this is not hydration
  1171. // TODO handle self-defined fallback
  1172. if (!initialVNode.el) {
  1173. const placeholder = (instance.subTree = createVNode(Comment))
  1174. processCommentNode(null, placeholder, container!, anchor)
  1175. }
  1176. } else {
  1177. setupRenderEffect(
  1178. instance,
  1179. initialVNode,
  1180. container,
  1181. anchor,
  1182. parentSuspense,
  1183. namespace,
  1184. optimized,
  1185. )
  1186. }
  1187. if (__DEV__) {
  1188. popWarningContext()
  1189. endMeasure(instance, `mount`)
  1190. }
  1191. }
  1192. const updateComponent = (n1: VNode, n2: VNode, optimized: boolean) => {
  1193. const instance = (n2.component = n1.component)!
  1194. if (shouldUpdateComponent(n1, n2, optimized)) {
  1195. if (
  1196. __FEATURE_SUSPENSE__ &&
  1197. instance.asyncDep &&
  1198. !instance.asyncResolved
  1199. ) {
  1200. // async & still pending - just update props and slots
  1201. // since the component's reactive effect for render isn't set-up yet
  1202. if (__DEV__) {
  1203. pushWarningContext(n2)
  1204. }
  1205. updateComponentPreRender(instance, n2, optimized)
  1206. if (__DEV__) {
  1207. popWarningContext()
  1208. }
  1209. return
  1210. } else {
  1211. // normal update
  1212. instance.next = n2
  1213. // in case the child component is also queued, remove it to avoid
  1214. // double updating the same child component in the same flush.
  1215. invalidateJob(instance.update)
  1216. // instance.update is the reactive effect.
  1217. instance.effect.dirty = true
  1218. instance.update()
  1219. }
  1220. } else {
  1221. // no update needed. just copy over properties
  1222. n2.el = n1.el
  1223. instance.vnode = n2
  1224. }
  1225. }
  1226. const setupRenderEffect: SetupRenderEffectFn = (
  1227. instance,
  1228. initialVNode,
  1229. container,
  1230. anchor,
  1231. parentSuspense,
  1232. namespace: ElementNamespace,
  1233. optimized,
  1234. ) => {
  1235. const componentUpdateFn = () => {
  1236. if (!instance.isMounted) {
  1237. let vnodeHook: VNodeHook | null | undefined
  1238. const { el, props } = initialVNode
  1239. const { bm, m, parent } = instance
  1240. const isAsyncWrapperVNode = isAsyncWrapper(initialVNode)
  1241. toggleRecurse(instance, false)
  1242. // beforeMount hook
  1243. if (bm) {
  1244. invokeArrayFns(bm)
  1245. }
  1246. // onVnodeBeforeMount
  1247. if (
  1248. !isAsyncWrapperVNode &&
  1249. (vnodeHook = props && props.onVnodeBeforeMount)
  1250. ) {
  1251. invokeVNodeHook(vnodeHook, parent, initialVNode)
  1252. }
  1253. if (
  1254. __COMPAT__ &&
  1255. isCompatEnabled(DeprecationTypes.INSTANCE_EVENT_HOOKS, instance)
  1256. ) {
  1257. instance.emit('hook:beforeMount')
  1258. }
  1259. toggleRecurse(instance, true)
  1260. if (el && hydrateNode) {
  1261. // vnode has adopted host node - perform hydration instead of mount.
  1262. const hydrateSubTree = () => {
  1263. if (__DEV__) {
  1264. startMeasure(instance, `render`)
  1265. }
  1266. instance.subTree = renderComponentRoot(instance)
  1267. if (__DEV__) {
  1268. endMeasure(instance, `render`)
  1269. }
  1270. if (__DEV__) {
  1271. startMeasure(instance, `hydrate`)
  1272. }
  1273. hydrateNode!(
  1274. el as Node,
  1275. instance.subTree,
  1276. instance,
  1277. parentSuspense,
  1278. null,
  1279. )
  1280. if (__DEV__) {
  1281. endMeasure(instance, `hydrate`)
  1282. }
  1283. }
  1284. if (isAsyncWrapperVNode) {
  1285. ;(initialVNode.type as ComponentOptions).__asyncLoader!().then(
  1286. // note: we are moving the render call into an async callback,
  1287. // which means it won't track dependencies - but it's ok because
  1288. // a server-rendered async wrapper is already in resolved state
  1289. // and it will never need to change.
  1290. () => !instance.isUnmounted && hydrateSubTree(),
  1291. )
  1292. } else {
  1293. hydrateSubTree()
  1294. }
  1295. } else {
  1296. if (__DEV__) {
  1297. startMeasure(instance, `render`)
  1298. }
  1299. const subTree = (instance.subTree = renderComponentRoot(instance))
  1300. if (__DEV__) {
  1301. endMeasure(instance, `render`)
  1302. }
  1303. if (__DEV__) {
  1304. startMeasure(instance, `patch`)
  1305. }
  1306. patch(
  1307. null,
  1308. subTree,
  1309. container,
  1310. anchor,
  1311. instance,
  1312. parentSuspense,
  1313. namespace,
  1314. )
  1315. if (__DEV__) {
  1316. endMeasure(instance, `patch`)
  1317. }
  1318. initialVNode.el = subTree.el
  1319. }
  1320. // mounted hook
  1321. if (m) {
  1322. queuePostRenderEffect(m, parentSuspense)
  1323. }
  1324. // onVnodeMounted
  1325. if (
  1326. !isAsyncWrapperVNode &&
  1327. (vnodeHook = props && props.onVnodeMounted)
  1328. ) {
  1329. const scopedInitialVNode = initialVNode
  1330. queuePostRenderEffect(
  1331. () => invokeVNodeHook(vnodeHook!, parent, scopedInitialVNode),
  1332. parentSuspense,
  1333. )
  1334. }
  1335. if (
  1336. __COMPAT__ &&
  1337. isCompatEnabled(DeprecationTypes.INSTANCE_EVENT_HOOKS, instance)
  1338. ) {
  1339. queuePostRenderEffect(
  1340. () => instance.emit('hook:mounted'),
  1341. parentSuspense,
  1342. )
  1343. }
  1344. // activated hook for keep-alive roots.
  1345. // #1742 activated hook must be accessed after first render
  1346. // since the hook may be injected by a child keep-alive
  1347. if (
  1348. initialVNode.shapeFlag & ShapeFlags.COMPONENT_SHOULD_KEEP_ALIVE ||
  1349. (parent &&
  1350. isAsyncWrapper(parent.vnode) &&
  1351. parent.vnode.shapeFlag & ShapeFlags.COMPONENT_SHOULD_KEEP_ALIVE)
  1352. ) {
  1353. instance.a && queuePostRenderEffect(instance.a, parentSuspense)
  1354. if (
  1355. __COMPAT__ &&
  1356. isCompatEnabled(DeprecationTypes.INSTANCE_EVENT_HOOKS, instance)
  1357. ) {
  1358. queuePostRenderEffect(
  1359. () => instance.emit('hook:activated'),
  1360. parentSuspense,
  1361. )
  1362. }
  1363. }
  1364. instance.isMounted = true
  1365. if (__DEV__ || __FEATURE_PROD_DEVTOOLS__) {
  1366. devtoolsComponentAdded(instance)
  1367. }
  1368. // #2458: deference mount-only object parameters to prevent memleaks
  1369. initialVNode = container = anchor = null as any
  1370. } else {
  1371. let { next, bu, u, parent, vnode } = instance
  1372. if (__FEATURE_SUSPENSE__) {
  1373. const nonHydratedAsyncRoot = locateNonHydratedAsyncRoot(instance)
  1374. // we are trying to update some async comp before hydration
  1375. // this will cause crash because we don't know the root node yet
  1376. if (nonHydratedAsyncRoot) {
  1377. // only sync the properties and abort the rest of operations
  1378. if (next) {
  1379. next.el = vnode.el
  1380. updateComponentPreRender(instance, next, optimized)
  1381. }
  1382. // and continue the rest of operations once the deps are resolved
  1383. nonHydratedAsyncRoot.asyncDep!.then(() => {
  1384. // the instance may be destroyed during the time period
  1385. if (!instance.isUnmounted) {
  1386. componentUpdateFn()
  1387. }
  1388. })
  1389. return
  1390. }
  1391. }
  1392. // updateComponent
  1393. // This is triggered by mutation of component's own state (next: null)
  1394. // OR parent calling processComponent (next: VNode)
  1395. let originNext = next
  1396. let vnodeHook: VNodeHook | null | undefined
  1397. if (__DEV__) {
  1398. pushWarningContext(next || instance.vnode)
  1399. }
  1400. // Disallow component effect recursion during pre-lifecycle hooks.
  1401. toggleRecurse(instance, false)
  1402. if (next) {
  1403. next.el = vnode.el
  1404. updateComponentPreRender(instance, next, optimized)
  1405. } else {
  1406. next = vnode
  1407. }
  1408. // beforeUpdate hook
  1409. if (bu) {
  1410. invokeArrayFns(bu)
  1411. }
  1412. // onVnodeBeforeUpdate
  1413. if ((vnodeHook = next.props && next.props.onVnodeBeforeUpdate)) {
  1414. invokeVNodeHook(vnodeHook, parent, next, vnode)
  1415. }
  1416. if (
  1417. __COMPAT__ &&
  1418. isCompatEnabled(DeprecationTypes.INSTANCE_EVENT_HOOKS, instance)
  1419. ) {
  1420. instance.emit('hook:beforeUpdate')
  1421. }
  1422. toggleRecurse(instance, true)
  1423. // render
  1424. if (__DEV__) {
  1425. startMeasure(instance, `render`)
  1426. }
  1427. const nextTree = renderComponentRoot(instance)
  1428. if (__DEV__) {
  1429. endMeasure(instance, `render`)
  1430. }
  1431. const prevTree = instance.subTree
  1432. instance.subTree = nextTree
  1433. if (__DEV__) {
  1434. startMeasure(instance, `patch`)
  1435. }
  1436. patch(
  1437. prevTree,
  1438. nextTree,
  1439. // parent may have changed if it's in a teleport
  1440. hostParentNode(prevTree.el!)!,
  1441. // anchor may have changed if it's in a fragment
  1442. getNextHostNode(prevTree),
  1443. instance,
  1444. parentSuspense,
  1445. namespace,
  1446. )
  1447. if (__DEV__) {
  1448. endMeasure(instance, `patch`)
  1449. }
  1450. next.el = nextTree.el
  1451. if (originNext === null) {
  1452. // self-triggered update. In case of HOC, update parent component
  1453. // vnode el. HOC is indicated by parent instance's subTree pointing
  1454. // to child component's vnode
  1455. updateHOCHostEl(instance, nextTree.el)
  1456. }
  1457. // updated hook
  1458. if (u) {
  1459. queuePostRenderEffect(u, parentSuspense)
  1460. }
  1461. // onVnodeUpdated
  1462. if ((vnodeHook = next.props && next.props.onVnodeUpdated)) {
  1463. queuePostRenderEffect(
  1464. () => invokeVNodeHook(vnodeHook!, parent, next!, vnode),
  1465. parentSuspense,
  1466. )
  1467. }
  1468. if (
  1469. __COMPAT__ &&
  1470. isCompatEnabled(DeprecationTypes.INSTANCE_EVENT_HOOKS, instance)
  1471. ) {
  1472. queuePostRenderEffect(
  1473. () => instance.emit('hook:updated'),
  1474. parentSuspense,
  1475. )
  1476. }
  1477. if (__DEV__ || __FEATURE_PROD_DEVTOOLS__) {
  1478. devtoolsComponentUpdated(instance)
  1479. }
  1480. if (__DEV__) {
  1481. popWarningContext()
  1482. }
  1483. }
  1484. }
  1485. // create reactive effect for rendering
  1486. const effect = (instance.effect = new ReactiveEffect(
  1487. componentUpdateFn,
  1488. NOOP,
  1489. () => queueJob(update),
  1490. instance.scope, // track it in component's effect scope
  1491. ))
  1492. const update: SchedulerJob = (instance.update = () => {
  1493. if (effect.dirty) {
  1494. effect.run()
  1495. }
  1496. })
  1497. update.id = instance.uid
  1498. // allowRecurse
  1499. // #1801, #2043 component render effects should allow recursive updates
  1500. toggleRecurse(instance, true)
  1501. if (__DEV__) {
  1502. effect.onTrack = instance.rtc
  1503. ? e => invokeArrayFns(instance.rtc!, e)
  1504. : void 0
  1505. effect.onTrigger = instance.rtg
  1506. ? e => invokeArrayFns(instance.rtg!, e)
  1507. : void 0
  1508. update.ownerInstance = instance
  1509. }
  1510. update()
  1511. }
  1512. const updateComponentPreRender = (
  1513. instance: ComponentInternalInstance,
  1514. nextVNode: VNode,
  1515. optimized: boolean,
  1516. ) => {
  1517. nextVNode.component = instance
  1518. const prevProps = instance.vnode.props
  1519. instance.vnode = nextVNode
  1520. instance.next = null
  1521. updateProps(instance, nextVNode.props, prevProps, optimized)
  1522. updateSlots(instance, nextVNode.children, optimized)
  1523. pauseTracking()
  1524. // props update may have triggered pre-flush watchers.
  1525. // flush them before the render update.
  1526. flushPreFlushCbs(instance)
  1527. resetTracking()
  1528. }
  1529. const patchChildren: PatchChildrenFn = (
  1530. n1,
  1531. n2,
  1532. container,
  1533. anchor,
  1534. parentComponent,
  1535. parentSuspense,
  1536. namespace: ElementNamespace,
  1537. slotScopeIds,
  1538. optimized = false,
  1539. ) => {
  1540. const c1 = n1 && n1.children
  1541. const prevShapeFlag = n1 ? n1.shapeFlag : 0
  1542. const c2 = n2.children
  1543. const { patchFlag, shapeFlag } = n2
  1544. // fast path
  1545. if (patchFlag > 0) {
  1546. if (patchFlag & PatchFlags.KEYED_FRAGMENT) {
  1547. // this could be either fully-keyed or mixed (some keyed some not)
  1548. // presence of patchFlag means children are guaranteed to be arrays
  1549. patchKeyedChildren(
  1550. c1 as VNode[],
  1551. c2 as VNodeArrayChildren,
  1552. container,
  1553. anchor,
  1554. parentComponent,
  1555. parentSuspense,
  1556. namespace,
  1557. slotScopeIds,
  1558. optimized,
  1559. )
  1560. return
  1561. } else if (patchFlag & PatchFlags.UNKEYED_FRAGMENT) {
  1562. // unkeyed
  1563. patchUnkeyedChildren(
  1564. c1 as VNode[],
  1565. c2 as VNodeArrayChildren,
  1566. container,
  1567. anchor,
  1568. parentComponent,
  1569. parentSuspense,
  1570. namespace,
  1571. slotScopeIds,
  1572. optimized,
  1573. )
  1574. return
  1575. }
  1576. }
  1577. // children has 3 possibilities: text, array or no children.
  1578. if (shapeFlag & ShapeFlags.TEXT_CHILDREN) {
  1579. // text children fast path
  1580. if (prevShapeFlag & ShapeFlags.ARRAY_CHILDREN) {
  1581. unmountChildren(c1 as VNode[], parentComponent, parentSuspense)
  1582. }
  1583. if (c2 !== c1) {
  1584. hostSetElementText(container, c2 as string)
  1585. }
  1586. } else {
  1587. if (prevShapeFlag & ShapeFlags.ARRAY_CHILDREN) {
  1588. // prev children was array
  1589. if (shapeFlag & ShapeFlags.ARRAY_CHILDREN) {
  1590. // two arrays, cannot assume anything, do full diff
  1591. patchKeyedChildren(
  1592. c1 as VNode[],
  1593. c2 as VNodeArrayChildren,
  1594. container,
  1595. anchor,
  1596. parentComponent,
  1597. parentSuspense,
  1598. namespace,
  1599. slotScopeIds,
  1600. optimized,
  1601. )
  1602. } else {
  1603. // no new children, just unmount old
  1604. unmountChildren(c1 as VNode[], parentComponent, parentSuspense, true)
  1605. }
  1606. } else {
  1607. // prev children was text OR null
  1608. // new children is array OR null
  1609. if (prevShapeFlag & ShapeFlags.TEXT_CHILDREN) {
  1610. hostSetElementText(container, '')
  1611. }
  1612. // mount new if array
  1613. if (shapeFlag & ShapeFlags.ARRAY_CHILDREN) {
  1614. mountChildren(
  1615. c2 as VNodeArrayChildren,
  1616. container,
  1617. anchor,
  1618. parentComponent,
  1619. parentSuspense,
  1620. namespace,
  1621. slotScopeIds,
  1622. optimized,
  1623. )
  1624. }
  1625. }
  1626. }
  1627. }
  1628. const patchUnkeyedChildren = (
  1629. c1: VNode[],
  1630. c2: VNodeArrayChildren,
  1631. container: RendererElement,
  1632. anchor: RendererNode | null,
  1633. parentComponent: ComponentInternalInstance | null,
  1634. parentSuspense: SuspenseBoundary | null,
  1635. namespace: ElementNamespace,
  1636. slotScopeIds: string[] | null,
  1637. optimized: boolean,
  1638. ) => {
  1639. c1 = c1 || EMPTY_ARR
  1640. c2 = c2 || EMPTY_ARR
  1641. const oldLength = c1.length
  1642. const newLength = c2.length
  1643. const commonLength = Math.min(oldLength, newLength)
  1644. let i
  1645. for (i = 0; i < commonLength; i++) {
  1646. const nextChild = (c2[i] = optimized
  1647. ? cloneIfMounted(c2[i] as VNode)
  1648. : normalizeVNode(c2[i]))
  1649. patch(
  1650. c1[i],
  1651. nextChild,
  1652. container,
  1653. null,
  1654. parentComponent,
  1655. parentSuspense,
  1656. namespace,
  1657. slotScopeIds,
  1658. optimized,
  1659. )
  1660. }
  1661. if (oldLength > newLength) {
  1662. // remove old
  1663. unmountChildren(
  1664. c1,
  1665. parentComponent,
  1666. parentSuspense,
  1667. true,
  1668. false,
  1669. commonLength,
  1670. )
  1671. } else {
  1672. // mount new
  1673. mountChildren(
  1674. c2,
  1675. container,
  1676. anchor,
  1677. parentComponent,
  1678. parentSuspense,
  1679. namespace,
  1680. slotScopeIds,
  1681. optimized,
  1682. commonLength,
  1683. )
  1684. }
  1685. }
  1686. // can be all-keyed or mixed
  1687. const patchKeyedChildren = (
  1688. c1: VNode[],
  1689. c2: VNodeArrayChildren,
  1690. container: RendererElement,
  1691. parentAnchor: RendererNode | null,
  1692. parentComponent: ComponentInternalInstance | null,
  1693. parentSuspense: SuspenseBoundary | null,
  1694. namespace: ElementNamespace,
  1695. slotScopeIds: string[] | null,
  1696. optimized: boolean,
  1697. ) => {
  1698. let i = 0
  1699. const l2 = c2.length
  1700. let e1 = c1.length - 1 // prev ending index
  1701. let e2 = l2 - 1 // next ending index
  1702. // 1. sync from start
  1703. // (a b) c
  1704. // (a b) d e
  1705. while (i <= e1 && i <= e2) {
  1706. const n1 = c1[i]
  1707. const n2 = (c2[i] = optimized
  1708. ? cloneIfMounted(c2[i] as VNode)
  1709. : normalizeVNode(c2[i]))
  1710. if (isSameVNodeType(n1, n2)) {
  1711. patch(
  1712. n1,
  1713. n2,
  1714. container,
  1715. null,
  1716. parentComponent,
  1717. parentSuspense,
  1718. namespace,
  1719. slotScopeIds,
  1720. optimized,
  1721. )
  1722. } else {
  1723. break
  1724. }
  1725. i++
  1726. }
  1727. // 2. sync from end
  1728. // a (b c)
  1729. // d e (b c)
  1730. while (i <= e1 && i <= e2) {
  1731. const n1 = c1[e1]
  1732. const n2 = (c2[e2] = optimized
  1733. ? cloneIfMounted(c2[e2] as VNode)
  1734. : normalizeVNode(c2[e2]))
  1735. if (isSameVNodeType(n1, n2)) {
  1736. patch(
  1737. n1,
  1738. n2,
  1739. container,
  1740. null,
  1741. parentComponent,
  1742. parentSuspense,
  1743. namespace,
  1744. slotScopeIds,
  1745. optimized,
  1746. )
  1747. } else {
  1748. break
  1749. }
  1750. e1--
  1751. e2--
  1752. }
  1753. // 3. common sequence + mount
  1754. // (a b)
  1755. // (a b) c
  1756. // i = 2, e1 = 1, e2 = 2
  1757. // (a b)
  1758. // c (a b)
  1759. // i = 0, e1 = -1, e2 = 0
  1760. if (i > e1) {
  1761. if (i <= e2) {
  1762. const nextPos = e2 + 1
  1763. const anchor = nextPos < l2 ? (c2[nextPos] as VNode).el : parentAnchor
  1764. while (i <= e2) {
  1765. patch(
  1766. null,
  1767. (c2[i] = optimized
  1768. ? cloneIfMounted(c2[i] as VNode)
  1769. : normalizeVNode(c2[i])),
  1770. container,
  1771. anchor,
  1772. parentComponent,
  1773. parentSuspense,
  1774. namespace,
  1775. slotScopeIds,
  1776. optimized,
  1777. )
  1778. i++
  1779. }
  1780. }
  1781. }
  1782. // 4. common sequence + unmount
  1783. // (a b) c
  1784. // (a b)
  1785. // i = 2, e1 = 2, e2 = 1
  1786. // a (b c)
  1787. // (b c)
  1788. // i = 0, e1 = 0, e2 = -1
  1789. else if (i > e2) {
  1790. while (i <= e1) {
  1791. unmount(c1[i], parentComponent, parentSuspense, true)
  1792. i++
  1793. }
  1794. }
  1795. // 5. unknown sequence
  1796. // [i ... e1 + 1]: a b [c d e] f g
  1797. // [i ... e2 + 1]: a b [e d c h] f g
  1798. // i = 2, e1 = 4, e2 = 5
  1799. else {
  1800. const s1 = i // prev starting index
  1801. const s2 = i // next starting index
  1802. // 5.1 build key:index map for newChildren
  1803. const keyToNewIndexMap: Map<string | number | symbol, number> = new Map()
  1804. for (i = s2; i <= e2; i++) {
  1805. const nextChild = (c2[i] = optimized
  1806. ? cloneIfMounted(c2[i] as VNode)
  1807. : normalizeVNode(c2[i]))
  1808. if (nextChild.key != null) {
  1809. if (__DEV__ && keyToNewIndexMap.has(nextChild.key)) {
  1810. warn(
  1811. `Duplicate keys found during update:`,
  1812. JSON.stringify(nextChild.key),
  1813. `Make sure keys are unique.`,
  1814. )
  1815. }
  1816. keyToNewIndexMap.set(nextChild.key, i)
  1817. }
  1818. }
  1819. // 5.2 loop through old children left to be patched and try to patch
  1820. // matching nodes & remove nodes that are no longer present
  1821. let j
  1822. let patched = 0
  1823. const toBePatched = e2 - s2 + 1
  1824. let moved = false
  1825. // used to track whether any node has moved
  1826. let maxNewIndexSoFar = 0
  1827. // works as Map<newIndex, oldIndex>
  1828. // Note that oldIndex is offset by +1
  1829. // and oldIndex = 0 is a special value indicating the new node has
  1830. // no corresponding old node.
  1831. // used for determining longest stable subsequence
  1832. const newIndexToOldIndexMap = new Array(toBePatched)
  1833. for (i = 0; i < toBePatched; i++) newIndexToOldIndexMap[i] = 0
  1834. for (i = s1; i <= e1; i++) {
  1835. const prevChild = c1[i]
  1836. if (patched >= toBePatched) {
  1837. // all new children have been patched so this can only be a removal
  1838. unmount(prevChild, parentComponent, parentSuspense, true)
  1839. continue
  1840. }
  1841. let newIndex
  1842. if (prevChild.key != null) {
  1843. newIndex = keyToNewIndexMap.get(prevChild.key)
  1844. } else {
  1845. // key-less node, try to locate a key-less node of the same type
  1846. for (j = s2; j <= e2; j++) {
  1847. if (
  1848. newIndexToOldIndexMap[j - s2] === 0 &&
  1849. isSameVNodeType(prevChild, c2[j] as VNode)
  1850. ) {
  1851. newIndex = j
  1852. break
  1853. }
  1854. }
  1855. }
  1856. if (newIndex === undefined) {
  1857. unmount(prevChild, parentComponent, parentSuspense, true)
  1858. } else {
  1859. newIndexToOldIndexMap[newIndex - s2] = i + 1
  1860. if (newIndex >= maxNewIndexSoFar) {
  1861. maxNewIndexSoFar = newIndex
  1862. } else {
  1863. moved = true
  1864. }
  1865. patch(
  1866. prevChild,
  1867. c2[newIndex] as VNode,
  1868. container,
  1869. null,
  1870. parentComponent,
  1871. parentSuspense,
  1872. namespace,
  1873. slotScopeIds,
  1874. optimized,
  1875. )
  1876. patched++
  1877. }
  1878. }
  1879. // 5.3 move and mount
  1880. // generate longest stable subsequence only when nodes have moved
  1881. const increasingNewIndexSequence = moved
  1882. ? getSequence(newIndexToOldIndexMap)
  1883. : EMPTY_ARR
  1884. j = increasingNewIndexSequence.length - 1
  1885. // looping backwards so that we can use last patched node as anchor
  1886. for (i = toBePatched - 1; i >= 0; i--) {
  1887. const nextIndex = s2 + i
  1888. const nextChild = c2[nextIndex] as VNode
  1889. const anchor =
  1890. nextIndex + 1 < l2 ? (c2[nextIndex + 1] as VNode).el : parentAnchor
  1891. if (newIndexToOldIndexMap[i] === 0) {
  1892. // mount new
  1893. patch(
  1894. null,
  1895. nextChild,
  1896. container,
  1897. anchor,
  1898. parentComponent,
  1899. parentSuspense,
  1900. namespace,
  1901. slotScopeIds,
  1902. optimized,
  1903. )
  1904. } else if (moved) {
  1905. // move if:
  1906. // There is no stable subsequence (e.g. a reverse)
  1907. // OR current node is not among the stable sequence
  1908. if (j < 0 || i !== increasingNewIndexSequence[j]) {
  1909. move(nextChild, container, anchor, MoveType.REORDER)
  1910. } else {
  1911. j--
  1912. }
  1913. }
  1914. }
  1915. }
  1916. }
  1917. const move: MoveFn = (
  1918. vnode,
  1919. container,
  1920. anchor,
  1921. moveType,
  1922. parentSuspense = null,
  1923. ) => {
  1924. const { el, type, transition, children, shapeFlag } = vnode
  1925. if (shapeFlag & ShapeFlags.COMPONENT) {
  1926. move(vnode.component!.subTree, container, anchor, moveType)
  1927. return
  1928. }
  1929. if (__FEATURE_SUSPENSE__ && shapeFlag & ShapeFlags.SUSPENSE) {
  1930. vnode.suspense!.move(container, anchor, moveType)
  1931. return
  1932. }
  1933. if (shapeFlag & ShapeFlags.TELEPORT) {
  1934. ;(type as typeof TeleportImpl).move(vnode, container, anchor, internals)
  1935. return
  1936. }
  1937. if (type === Fragment) {
  1938. hostInsert(el!, container, anchor)
  1939. for (let i = 0; i < (children as VNode[]).length; i++) {
  1940. move((children as VNode[])[i], container, anchor, moveType)
  1941. }
  1942. hostInsert(vnode.anchor!, container, anchor)
  1943. return
  1944. }
  1945. if (type === Static) {
  1946. moveStaticNode(vnode, container, anchor)
  1947. return
  1948. }
  1949. // single nodes
  1950. const needTransition =
  1951. moveType !== MoveType.REORDER &&
  1952. shapeFlag & ShapeFlags.ELEMENT &&
  1953. transition
  1954. if (needTransition) {
  1955. if (moveType === MoveType.ENTER) {
  1956. transition!.beforeEnter(el!)
  1957. hostInsert(el!, container, anchor)
  1958. queuePostRenderEffect(() => transition!.enter(el!), parentSuspense)
  1959. } else {
  1960. const { leave, delayLeave, afterLeave } = transition!
  1961. const remove = () => hostInsert(el!, container, anchor)
  1962. const performLeave = () => {
  1963. leave(el!, () => {
  1964. remove()
  1965. afterLeave && afterLeave()
  1966. })
  1967. }
  1968. if (delayLeave) {
  1969. delayLeave(el!, remove, performLeave)
  1970. } else {
  1971. performLeave()
  1972. }
  1973. }
  1974. } else {
  1975. hostInsert(el!, container, anchor)
  1976. }
  1977. }
  1978. const unmount: UnmountFn = (
  1979. vnode,
  1980. parentComponent,
  1981. parentSuspense,
  1982. doRemove = false,
  1983. optimized = false,
  1984. ) => {
  1985. const {
  1986. type,
  1987. props,
  1988. ref,
  1989. children,
  1990. dynamicChildren,
  1991. shapeFlag,
  1992. patchFlag,
  1993. dirs,
  1994. } = vnode
  1995. // unset ref
  1996. if (ref != null) {
  1997. setRef(ref, null, parentSuspense, vnode, true)
  1998. }
  1999. if (shapeFlag & ShapeFlags.COMPONENT_SHOULD_KEEP_ALIVE) {
  2000. ;(parentComponent!.ctx as KeepAliveContext).deactivate(vnode)
  2001. return
  2002. }
  2003. const shouldInvokeDirs = shapeFlag & ShapeFlags.ELEMENT && dirs
  2004. const shouldInvokeVnodeHook = !isAsyncWrapper(vnode)
  2005. let vnodeHook: VNodeHook | undefined | null
  2006. if (
  2007. shouldInvokeVnodeHook &&
  2008. (vnodeHook = props && props.onVnodeBeforeUnmount)
  2009. ) {
  2010. invokeVNodeHook(vnodeHook, parentComponent, vnode)
  2011. }
  2012. if (shapeFlag & ShapeFlags.COMPONENT) {
  2013. unmountComponent(vnode.component!, parentSuspense, doRemove)
  2014. } else {
  2015. if (__FEATURE_SUSPENSE__ && shapeFlag & ShapeFlags.SUSPENSE) {
  2016. vnode.suspense!.unmount(parentSuspense, doRemove)
  2017. return
  2018. }
  2019. if (shouldInvokeDirs) {
  2020. invokeDirectiveHook(vnode, null, parentComponent, 'beforeUnmount')
  2021. }
  2022. if (shapeFlag & ShapeFlags.TELEPORT) {
  2023. ;(vnode.type as typeof TeleportImpl).remove(
  2024. vnode,
  2025. parentComponent,
  2026. parentSuspense,
  2027. optimized,
  2028. internals,
  2029. doRemove,
  2030. )
  2031. } else if (
  2032. dynamicChildren &&
  2033. // #1153: fast path should not be taken for non-stable (v-for) fragments
  2034. (type !== Fragment ||
  2035. (patchFlag > 0 && patchFlag & PatchFlags.STABLE_FRAGMENT))
  2036. ) {
  2037. // fast path for block nodes: only need to unmount dynamic children.
  2038. unmountChildren(
  2039. dynamicChildren,
  2040. parentComponent,
  2041. parentSuspense,
  2042. false,
  2043. true,
  2044. )
  2045. } else if (
  2046. (type === Fragment &&
  2047. patchFlag &
  2048. (PatchFlags.KEYED_FRAGMENT | PatchFlags.UNKEYED_FRAGMENT)) ||
  2049. (!optimized && shapeFlag & ShapeFlags.ARRAY_CHILDREN)
  2050. ) {
  2051. unmountChildren(children as VNode[], parentComponent, parentSuspense)
  2052. }
  2053. if (doRemove) {
  2054. remove(vnode)
  2055. }
  2056. }
  2057. if (
  2058. (shouldInvokeVnodeHook &&
  2059. (vnodeHook = props && props.onVnodeUnmounted)) ||
  2060. shouldInvokeDirs
  2061. ) {
  2062. queuePostRenderEffect(() => {
  2063. vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, vnode)
  2064. shouldInvokeDirs &&
  2065. invokeDirectiveHook(vnode, null, parentComponent, 'unmounted')
  2066. }, parentSuspense)
  2067. }
  2068. }
  2069. const remove: RemoveFn = vnode => {
  2070. const { type, el, anchor, transition } = vnode
  2071. if (type === Fragment) {
  2072. if (
  2073. __DEV__ &&
  2074. vnode.patchFlag > 0 &&
  2075. vnode.patchFlag & PatchFlags.DEV_ROOT_FRAGMENT &&
  2076. transition &&
  2077. !transition.persisted
  2078. ) {
  2079. ;(vnode.children as VNode[]).forEach(child => {
  2080. if (child.type === Comment) {
  2081. hostRemove(child.el!)
  2082. } else {
  2083. remove(child)
  2084. }
  2085. })
  2086. } else {
  2087. removeFragment(el!, anchor!)
  2088. }
  2089. return
  2090. }
  2091. if (type === Static) {
  2092. removeStaticNode(vnode)
  2093. return
  2094. }
  2095. const performRemove = () => {
  2096. hostRemove(el!)
  2097. if (transition && !transition.persisted && transition.afterLeave) {
  2098. transition.afterLeave()
  2099. }
  2100. }
  2101. if (
  2102. vnode.shapeFlag & ShapeFlags.ELEMENT &&
  2103. transition &&
  2104. !transition.persisted
  2105. ) {
  2106. const { leave, delayLeave } = transition
  2107. const performLeave = () => leave(el!, performRemove)
  2108. if (delayLeave) {
  2109. delayLeave(vnode.el!, performRemove, performLeave)
  2110. } else {
  2111. performLeave()
  2112. }
  2113. } else {
  2114. performRemove()
  2115. }
  2116. }
  2117. const removeFragment = (cur: RendererNode, end: RendererNode) => {
  2118. // For fragments, directly remove all contained DOM nodes.
  2119. // (fragment child nodes cannot have transition)
  2120. let next
  2121. while (cur !== end) {
  2122. next = hostNextSibling(cur)!
  2123. hostRemove(cur)
  2124. cur = next
  2125. }
  2126. hostRemove(end)
  2127. }
  2128. const unmountComponent = (
  2129. instance: ComponentInternalInstance,
  2130. parentSuspense: SuspenseBoundary | null,
  2131. doRemove?: boolean,
  2132. ) => {
  2133. if (__DEV__ && instance.type.__hmrId) {
  2134. unregisterHMR(instance)
  2135. }
  2136. const { bum, scope, update, subTree, um } = instance
  2137. // beforeUnmount hook
  2138. if (bum) {
  2139. invokeArrayFns(bum)
  2140. }
  2141. if (
  2142. __COMPAT__ &&
  2143. isCompatEnabled(DeprecationTypes.INSTANCE_EVENT_HOOKS, instance)
  2144. ) {
  2145. instance.emit('hook:beforeDestroy')
  2146. }
  2147. // stop effects in component scope
  2148. scope.stop()
  2149. // update may be null if a component is unmounted before its async
  2150. // setup has resolved.
  2151. if (update) {
  2152. // so that scheduler will no longer invoke it
  2153. update.active = false
  2154. unmount(subTree, instance, parentSuspense, doRemove)
  2155. }
  2156. // unmounted hook
  2157. if (um) {
  2158. queuePostRenderEffect(um, parentSuspense)
  2159. }
  2160. if (
  2161. __COMPAT__ &&
  2162. isCompatEnabled(DeprecationTypes.INSTANCE_EVENT_HOOKS, instance)
  2163. ) {
  2164. queuePostRenderEffect(
  2165. () => instance.emit('hook:destroyed'),
  2166. parentSuspense,
  2167. )
  2168. }
  2169. queuePostRenderEffect(() => {
  2170. instance.isUnmounted = true
  2171. }, parentSuspense)
  2172. // A component with async dep inside a pending suspense is unmounted before
  2173. // its async dep resolves. This should remove the dep from the suspense, and
  2174. // cause the suspense to resolve immediately if that was the last dep.
  2175. if (
  2176. __FEATURE_SUSPENSE__ &&
  2177. parentSuspense &&
  2178. parentSuspense.pendingBranch &&
  2179. !parentSuspense.isUnmounted &&
  2180. instance.asyncDep &&
  2181. !instance.asyncResolved &&
  2182. instance.suspenseId === parentSuspense.pendingId
  2183. ) {
  2184. parentSuspense.deps--
  2185. if (parentSuspense.deps === 0) {
  2186. parentSuspense.resolve()
  2187. }
  2188. }
  2189. if (__DEV__ || __FEATURE_PROD_DEVTOOLS__) {
  2190. devtoolsComponentRemoved(instance)
  2191. }
  2192. }
  2193. const unmountChildren: UnmountChildrenFn = (
  2194. children,
  2195. parentComponent,
  2196. parentSuspense,
  2197. doRemove = false,
  2198. optimized = false,
  2199. start = 0,
  2200. ) => {
  2201. for (let i = start; i < children.length; i++) {
  2202. unmount(children[i], parentComponent, parentSuspense, doRemove, optimized)
  2203. }
  2204. }
  2205. const getNextHostNode: NextFn = vnode => {
  2206. if (vnode.shapeFlag & ShapeFlags.COMPONENT) {
  2207. return getNextHostNode(vnode.component!.subTree)
  2208. }
  2209. if (__FEATURE_SUSPENSE__ && vnode.shapeFlag & ShapeFlags.SUSPENSE) {
  2210. return vnode.suspense!.next()
  2211. }
  2212. return hostNextSibling((vnode.anchor || vnode.el)!)
  2213. }
  2214. let isFlushing = false
  2215. const render: RootRenderFunction = (vnode, container, namespace) => {
  2216. if (vnode == null) {
  2217. if (container._vnode) {
  2218. unmount(container._vnode, null, null, true)
  2219. }
  2220. } else {
  2221. patch(
  2222. container._vnode || null,
  2223. vnode,
  2224. container,
  2225. null,
  2226. null,
  2227. null,
  2228. namespace,
  2229. )
  2230. }
  2231. if (!isFlushing) {
  2232. isFlushing = true
  2233. flushPreFlushCbs()
  2234. flushPostFlushCbs()
  2235. isFlushing = false
  2236. }
  2237. container._vnode = vnode
  2238. }
  2239. const internals: RendererInternals = {
  2240. p: patch,
  2241. um: unmount,
  2242. m: move,
  2243. r: remove,
  2244. mt: mountComponent,
  2245. mc: mountChildren,
  2246. pc: patchChildren,
  2247. pbc: patchBlockChildren,
  2248. n: getNextHostNode,
  2249. o: options,
  2250. }
  2251. let hydrate: ReturnType<typeof createHydrationFunctions>[0] | undefined
  2252. let hydrateNode: ReturnType<typeof createHydrationFunctions>[1] | undefined
  2253. if (createHydrationFns) {
  2254. ;[hydrate, hydrateNode] = createHydrationFns(
  2255. internals as RendererInternals<Node, Element>,
  2256. )
  2257. }
  2258. return {
  2259. render,
  2260. hydrate,
  2261. createApp: createAppAPI(render, hydrate),
  2262. }
  2263. }
  2264. function resolveChildrenNamespace(
  2265. { type, props }: VNode,
  2266. currentNamespace: ElementNamespace,
  2267. ): ElementNamespace {
  2268. return (currentNamespace === 'svg' && type === 'foreignObject') ||
  2269. (currentNamespace === 'mathml' &&
  2270. type === 'annotation-xml' &&
  2271. props &&
  2272. props.encoding &&
  2273. props.encoding.includes('html'))
  2274. ? undefined
  2275. : currentNamespace
  2276. }
  2277. function toggleRecurse(
  2278. { effect, update }: ComponentInternalInstance,
  2279. allowed: boolean,
  2280. ) {
  2281. effect.allowRecurse = update.allowRecurse = allowed
  2282. }
  2283. export function needTransition(
  2284. parentSuspense: SuspenseBoundary | null,
  2285. transition: TransitionHooks | null,
  2286. ) {
  2287. return (
  2288. (!parentSuspense || (parentSuspense && !parentSuspense.pendingBranch)) &&
  2289. transition &&
  2290. !transition.persisted
  2291. )
  2292. }
  2293. /**
  2294. * #1156
  2295. * When a component is HMR-enabled, we need to make sure that all static nodes
  2296. * inside a block also inherit the DOM element from the previous tree so that
  2297. * HMR updates (which are full updates) can retrieve the element for patching.
  2298. *
  2299. * #2080
  2300. * Inside keyed `template` fragment static children, if a fragment is moved,
  2301. * the children will always be moved. Therefore, in order to ensure correct move
  2302. * position, el should be inherited from previous nodes.
  2303. */
  2304. export function traverseStaticChildren(n1: VNode, n2: VNode, shallow = false) {
  2305. const ch1 = n1.children
  2306. const ch2 = n2.children
  2307. if (isArray(ch1) && isArray(ch2)) {
  2308. for (let i = 0; i < ch1.length; i++) {
  2309. // this is only called in the optimized path so array children are
  2310. // guaranteed to be vnodes
  2311. const c1 = ch1[i] as VNode
  2312. let c2 = ch2[i] as VNode
  2313. if (c2.shapeFlag & ShapeFlags.ELEMENT && !c2.dynamicChildren) {
  2314. if (c2.patchFlag <= 0 || c2.patchFlag === PatchFlags.NEED_HYDRATION) {
  2315. c2 = ch2[i] = cloneIfMounted(ch2[i] as VNode)
  2316. c2.el = c1.el
  2317. }
  2318. if (!shallow) traverseStaticChildren(c1, c2)
  2319. }
  2320. // #6852 also inherit for text nodes
  2321. if (c2.type === Text) {
  2322. c2.el = c1.el
  2323. }
  2324. // also inherit for comment nodes, but not placeholders (e.g. v-if which
  2325. // would have received .el during block patch)
  2326. if (__DEV__ && c2.type === Comment && !c2.el) {
  2327. c2.el = c1.el
  2328. }
  2329. }
  2330. }
  2331. }
  2332. // https://en.wikipedia.org/wiki/Longest_increasing_subsequence
  2333. function getSequence(arr: number[]): number[] {
  2334. const p = arr.slice()
  2335. const result = [0]
  2336. let i, j, u, v, c
  2337. const len = arr.length
  2338. for (i = 0; i < len; i++) {
  2339. const arrI = arr[i]
  2340. if (arrI !== 0) {
  2341. j = result[result.length - 1]
  2342. if (arr[j] < arrI) {
  2343. p[i] = j
  2344. result.push(i)
  2345. continue
  2346. }
  2347. u = 0
  2348. v = result.length - 1
  2349. while (u < v) {
  2350. c = (u + v) >> 1
  2351. if (arr[result[c]] < arrI) {
  2352. u = c + 1
  2353. } else {
  2354. v = c
  2355. }
  2356. }
  2357. if (arrI < arr[result[u]]) {
  2358. if (u > 0) {
  2359. p[i] = result[u - 1]
  2360. }
  2361. result[u] = i
  2362. }
  2363. }
  2364. }
  2365. u = result.length
  2366. v = result[u - 1]
  2367. while (u-- > 0) {
  2368. result[u] = v
  2369. v = p[v]
  2370. }
  2371. return result
  2372. }
  2373. function locateNonHydratedAsyncRoot(
  2374. instance: ComponentInternalInstance,
  2375. ): ComponentInternalInstance | undefined {
  2376. const subComponent = instance.subTree.component
  2377. if (subComponent) {
  2378. if (subComponent.asyncDep && !subComponent.asyncResolved) {
  2379. return subComponent
  2380. } else {
  2381. return locateNonHydratedAsyncRoot(subComponent)
  2382. }
  2383. }
  2384. }