renderer.ts 73 KB

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