renderer.ts 69 KB

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