renderer.ts 70 KB

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