renderer.ts 67 KB

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