diff --git a/packages/runtime-core/__tests__/hmr.spec.ts b/packages/runtime-core/__tests__/hmr.spec.ts index 9e92ed2a218..2aa658d016a 100644 --- a/packages/runtime-core/__tests__/hmr.spec.ts +++ b/packages/runtime-core/__tests__/hmr.spec.ts @@ -154,6 +154,38 @@ describe('hot module replacement', () => { expect(mountSpy).toHaveBeenCalledTimes(1) }) + test('reload multiple children under same parent should rerender parent once', async () => { + const root = nodeOps.createElement('div') + const childId = 'test-reload-multiple-children-same-parent' + + const Child: ComponentOptions = { + __hmrId: childId, + render: () => h('div', 'old'), + } + createRecord(childId, Child) + + let parentRenderCount = 0 + const Parent: ComponentOptions = { + render() { + parentRenderCount++ + return [h(Child), h(Child)] + }, + } + + render(h(Parent), root) + expect(serializeInner(root)).toBe(`
old
old
`) + expect(parentRenderCount).toBe(1) + + reload(childId, { + __hmrId: childId, + render: () => h('div', 'new'), + }) + await nextTick() + + expect(serializeInner(root)).toBe(`
new
new
`) + expect(parentRenderCount).toBe(2) + }) + // #7042 test('reload KeepAlive slot', async () => { const root = nodeOps.createElement('div') diff --git a/packages/runtime-core/src/hmr.ts b/packages/runtime-core/src/hmr.ts index a03ef9c904c..234956e0698 100644 --- a/packages/runtime-core/src/hmr.ts +++ b/packages/runtime-core/src/hmr.ts @@ -98,6 +98,20 @@ function normalizeClassComponent(component: HMRComponent): ComponentOptions { return isClassComponent(component) ? component.__vccOpts : component } +function hasDirtyAncestor( + instance: GenericComponentInstance, + dirtyInstances: Set, +): boolean { + let parent = instance.parent + while (parent) { + if (dirtyInstances.has(parent)) { + return true + } + parent = parent.parent + } + return false +} + function rerender(id: string, newRender?: Function): void { const record = map.get(id) if (!record) { @@ -143,7 +157,13 @@ function reload(id: string, newComp: HMRComponent): void { // create a snapshot which avoids the set being mutated during updates const instances = [...record.instances] - if (isVapor && newComp.__vapor && !instances.some(i => i.ceReload)) { + if ( + isVapor && + newComp.__vapor && + // VDOM parents need the VDOM HMR path to remount dirty Vapor children. + !instances.some(instance => instance.parent && !instance.parent.vapor) && + !instances.some(i => i.ceReload) + ) { // For multiple instances with the same __hmrId, remove styles first before reload // to avoid the second instance's style removal deleting the first instance's // newly added styles (since hmrReload is synchronous) @@ -153,10 +173,30 @@ function reload(id: string, newComp: HMRComponent): void { instance.root.ce._removeChildStyle(instance.type) } } + const dirtyInstances = new Set(instances) + const rerenderedParents = new Set() for (const instance of instances) { - instance.hmrReload!(newComp) + const parent = instance.parent + if (parent) { + // A dirty ancestor will recreate this child. Otherwise, each parent + // only needs one rerender for this HMR record. + if ( + !hasDirtyAncestor(instance, dirtyInstances) && + !rerenderedParents.has(parent) + ) { + rerenderedParents.add(parent) + parent.hmrRerender!() + } + } else { + instance.hmrReload!(newComp) + } } } else { + const parentUpdates = new Map< + GenericComponentInstance, + [GenericComponentInstance, Set][] + >() + const dirtyInstanceSet = new Set(instances) for (const instance of instances as ComponentInternalInstance[]) { const oldComp = normalizeClassComponent(instance.type as HMRComponent) @@ -188,23 +228,14 @@ function reload(id: string, newComp: HMRComponent): void { // 4. Force the parent instance to re-render. This will cause all updated // components to be unmounted and re-mounted. Queue the update so that we // don't end up forcing the same parent to re-render multiple times. - queueJob(() => { - isHmrUpdating = true - const parent = instance.parent! as ComponentInternalInstance - if (parent.vapor) { - parent.hmrRerender!() - } else { - if (!(parent.effect.flags! & EffectFlags.STOP)) { - parent.renderCache = [] - parent.effect.run() - } + const parent = instance.parent + if (!hasDirtyAncestor(instance, dirtyInstanceSet)) { + let updates = parentUpdates.get(parent) + if (!updates) { + parentUpdates.set(parent, (updates = [])) } - nextTick(() => { - isHmrUpdating = false - }) - // #6930, #11248 avoid infinite recursion - dirtyInstances.delete(instance) - }) + updates.push([instance, dirtyInstances]) + } } else if (instance.appContext.reload) { // root instance mounted via createApp() has a reload method instance.appContext.reload() @@ -222,6 +253,27 @@ function reload(id: string, newComp: HMRComponent): void { instance.root.ce._removeChildStyle(oldComp) } } + parentUpdates.forEach((updates, parent) => { + queueJob(() => { + isHmrUpdating = true + if (parent.vapor) { + parent.hmrRerender!() + } else { + const i = parent as ComponentInternalInstance + if (!(i.effect.flags! & EffectFlags.STOP)) { + i.renderCache = [] + i.effect.run() + } + } + nextTick(() => { + isHmrUpdating = false + }) + // #6930, #11248 avoid infinite recursion + updates.forEach(([instance, dirtyInstances]) => { + dirtyInstances.delete(instance) + }) + }) + }) } // 5. make sure to cleanup dirty hmr components after update queuePostFlushCb(() => { diff --git a/packages/runtime-vapor/__tests__/components/Teleport.spec.ts b/packages/runtime-vapor/__tests__/components/Teleport.spec.ts index 25302204eb5..e4196be3197 100644 --- a/packages/runtime-vapor/__tests__/components/Teleport.spec.ts +++ b/packages/runtime-vapor/__tests__/components/Teleport.spec.ts @@ -371,6 +371,7 @@ describe('renderer: VaporTeleport', () => { return [n0] }, }) + await nextTick() expect(root.innerHTML).toBe( '
root
', ) diff --git a/packages/runtime-vapor/__tests__/hmr.spec.ts b/packages/runtime-vapor/__tests__/hmr.spec.ts index 38e5dd10433..4e154944101 100644 --- a/packages/runtime-vapor/__tests__/hmr.spec.ts +++ b/packages/runtime-vapor/__tests__/hmr.spec.ts @@ -2,6 +2,7 @@ import { type HMRRuntime, computed, createApp, + currentInstance, h, inject, nextTick, @@ -9,9 +10,13 @@ import { onDeactivated, onMounted, onUnmounted, + popWarningContext, provide, ref, + setCurrentInstance, toDisplayString, + warn, + watchEffect, } from '@vue/runtime-dom' import { compileToVaporRender as compileToFunction, makeRender } from './_utils' import { @@ -179,6 +184,42 @@ describe('hot module replacement', () => { expect(mountSpy).toHaveBeenCalledTimes(1) }) + test('reload child should preserve parent setup effects', async () => { + const root = document.createElement('div') + const childId = 'test-reload-child-preserve-parent-effects' + const parentCount = ref(0) + const spy = vi.fn() + + const Child = defineVaporComponent({ + __hmrId: childId, + render: () => template('
old
')(), + }) + createRecord(childId, Child as any) + + const Parent = defineVaporComponent({ + setup() { + watchEffect(() => spy(parentCount.value)) + }, + render: () => createComponent(Child), + }) + + createVaporApp(Parent).mount(root) + expect(root.innerHTML).toBe(`
old
`) + expect(spy).toHaveBeenLastCalledWith(0) + + reload(childId, { + __vapor: true, + __hmrId: childId, + render: () => template('
new
')(), + }) + await nextTick() + expect(root.innerHTML).toBe(`
new
`) + + parentCount.value++ + await nextTick() + expect(spy).toHaveBeenLastCalledWith(1) + }) + test('reload root vapor component should preserve appContext provide/inject', async () => { const root = document.createElement('div') const appId = 'test-root-reload-app-context' @@ -212,6 +253,123 @@ describe('hot module replacement', () => { expect(root.innerHTML).toBe(`
app-injected
`) }) + test('reload root vapor component should update app instance for unmount', async () => { + const root = document.createElement('div') + const appId = 'test-root-reload-app-unmount' + const oldUnmountSpy = vi.fn() + const newUnmountSpy = vi.fn() + + const App = defineVaporComponent({ + __hmrId: appId, + setup() { + onUnmounted(oldUnmountSpy) + }, + render: () => template(`
old
`)(), + }) + createRecord(appId, App as any) + + const app = createVaporApp(App) + app.mount(root) + expect(root.innerHTML).toBe(`
old
`) + + reload(appId, { + __vapor: true, + __hmrId: appId, + setup() { + onUnmounted(newUnmountSpy) + }, + render: () => template(`
new
`)(), + }) + + await nextTick() + expect(root.innerHTML).toBe(`
new
`) + expect(oldUnmountSpy).toHaveBeenCalledTimes(1) + + app.unmount() + await nextTick() + expect(root.innerHTML).toBe(``) + expect(newUnmountSpy).toHaveBeenCalledTimes(1) + }) + + test('failed rerender restores current instance and warning context', () => { + const root = document.createElement('div') + const id = 'test-rerender-restore-context' + const warnHandler = vi.fn() + const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) + + const Comp = defineVaporComponent({ + __hmrId: id, + render: () => template('ok')(), + }) + createRecord(id, Comp as any) + + const app = createVaporApp(Comp) + app.config.warnHandler = warnHandler + app.mount(root) + expect(currentInstance).toBe(null) + + rerender(id, () => { + throw new Error('hmr rerender error') + }) + warnHandler.mockClear() + + const leakedInstance = currentInstance + setCurrentInstance(null, undefined) + warn('after failed hmr') + popWarningContext() + errorSpy.mockRestore() + + expect( + '[HMR] Something went wrong during Vue component hot-reload.', + ).toHaveBeenWarned() + expect('[Vue warn]: after failed hmr').toHaveBeenWarned() + expect(leakedInstance).toBe(null) + expect(warnHandler).not.toHaveBeenCalled() + }) + + test('failed reload restores current instance', () => { + const root = document.createElement('div') + const childId = 'test-reload-restore-context-child' + const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) + + const Child = defineVaporComponent({ + __hmrId: childId, + render: () => template('old')(), + }) + createRecord(childId, Child as any) + + const Parent = defineVaporComponent({ + render: () => createComponent(Child), + }) + + createVaporApp(Parent).mount(root) + expect(currentInstance).toBe(null) + + reload(childId, { + __vapor: true, + __hmrId: childId, + setup() { + throw new Error('hmr reload error') + }, + render: () => template('new')(), + }) + + const leakedInstance = currentInstance + setCurrentInstance(null, undefined) + errorSpy.mockRestore() + + expect( + '[Vue warn]: Unhandled error during execution of setup function', + ).toHaveBeenWarned() + expect( + '[Vue warn]: Unhandled error during execution of render function', + ).toHaveBeenWarned() + expect( + '[HMR] Something went wrong during Vue component hot-reload.', + ).toHaveBeenWarned() + expect(leakedInstance).toBe(null) + }) + test('reload KeepAlive slot', async () => { const root = document.createElement('div') document.body.appendChild(root) @@ -544,9 +702,7 @@ describe('hot module replacement', () => { expect(deactivatedSpy).toHaveBeenCalledTimes(1) }) - // TODO: renderEffect not re-run after child reload - // it requires parent rerender to align with vdom - test.todo('reload: avoid infinite recursion', async () => { + test('reload child through parent rerender', async () => { const root = document.createElement('div') document.body.appendChild(root) const childId = 'test-child-6930' @@ -593,19 +749,101 @@ describe('hot module replacement', () => { reload(childId, { __hmrId: childId, __vapor: true, - setup() { + setup(_, { expose }) { onMounted(mountSpy) const count = ref(1) + expose({ + count, + }) return { count } }, render: compileToFunction(`
{{ count }}
`), }) await nextTick() + await nextTick() expect(root.innerHTML).toBe(`
1
1
1`) expect(unmountSpy).toHaveBeenCalledTimes(2) expect(mountSpy).toHaveBeenCalledTimes(2) }) + test('reload multiple children under same vapor parent should rerender parent once', async () => { + const root = document.createElement('div') + const childId = 'test-child-reload-same-vapor-parent' + + const Child = defineVaporComponent({ + __hmrId: childId, + render: () => template('
old
')(), + }) + createRecord(childId, Child as any) + + let parentRenderCount = 0 + const Parent = defineVaporComponent({ + render() { + parentRenderCount++ + return [createComponent(Child), createComponent(Child)] + }, + }) + + createVaporApp(Parent).mount(root) + expect(root.innerHTML).toBe(`
old
old
`) + expect(parentRenderCount).toBe(1) + + reload(childId, { + __vapor: true, + __hmrId: childId, + render: () => template('
new
')(), + }) + await nextTick() + + expect(root.innerHTML).toBe(`
new
new
`) + expect(parentRenderCount).toBe(2) + }) + + test('reload vapor child under dirty ancestor should not rerender stale owner', async () => { + const root = document.createElement('div') + const id = 'test-child-reload-dirty-ancestor' + + let Child: any + const Wrapper = defineVaporComponent({ + render() { + return createComponent(Child, { nested: () => true }) + }, + }) + + Child = defineVaporComponent({ + __hmrId: id, + props: ['nested'], + setup(props: any) { + return { nested: props.nested } + }, + render: compileToFunction( + `
old {{ nested ? 'nested' : 'root' }}
`, + ), + }) + Child.components = { Wrapper } + createRecord(id, Child) + + createVaporApp(Child, { nested: () => false }).mount(root) + expect(root.textContent).toBe(`old rootold nested`) + + const NewChild: any = { + __vapor: true, + __hmrId: id, + props: ['nested'], + setup(props: any) { + return { nested: props.nested } + }, + render: compileToFunction( + `
new {{ nested ? 'nested' : 'root' }}
`, + ), + } + NewChild.components = { Wrapper } + reload(id, NewChild) + await nextTick() + + expect(root.textContent).toBe(`new rootnew nested`) + }) + test('static el reference', async () => { const root = document.createElement('div') document.body.appendChild(root) @@ -1413,6 +1651,82 @@ describe('hot module replacement', () => { }) describe('switch vapor/vdom modes', () => { + test('reload vapor child under vdom parent should rerender parent', async () => { + const id = 'vapor-child-under-vdom-parent' + const Child = { + __vapor: true, + __hmrId: id, + render() { + return template('
foo
')() + }, + } + createRecord(id, Child) + + let parentRenderCount = 0 + const Parent = { + render() { + parentRenderCount++ + return h(Child as any) + }, + } + const root = document.createElement('div') + const app = createApp(Parent) + app.use(vaporInteropPlugin) + app.mount(root) + expect(root.innerHTML).toBe('
foo
') + expect(parentRenderCount).toBe(1) + + reload(id, { + __vapor: true, + __hmrId: id, + render() { + return template('
bar
')() + }, + }) + + await nextTick() + expect(root.innerHTML).toBe('
bar
') + expect(parentRenderCount).toBe(2) + }) + + test('reload multiple vapor children under same vdom parent should rerender parent once', async () => { + const id = 'multiple-vapor-children-under-vdom-parent' + const Child = { + __vapor: true, + __hmrId: id, + render() { + return template('
foo
')() + }, + } + createRecord(id, Child) + + let parentRenderCount = 0 + const Parent = { + render() { + parentRenderCount++ + return [h(Child as any), h(Child as any)] + }, + } + const root = document.createElement('div') + const app = createApp(Parent) + app.use(vaporInteropPlugin) + app.mount(root) + expect(root.innerHTML).toBe('
foo
foo
') + expect(parentRenderCount).toBe(1) + + reload(id, { + __vapor: true, + __hmrId: id, + render() { + return template('
bar
')() + }, + }) + + await nextTick() + expect(root.innerHTML).toBe('
bar
bar
') + expect(parentRenderCount).toBe(2) + }) + test('vapor -> vdom', async () => { const id = 'vapor-to-vdom' const Comp = { diff --git a/packages/runtime-vapor/src/block.ts b/packages/runtime-vapor/src/block.ts index c4354eba79d..a42823f42f7 100644 --- a/packages/runtime-vapor/src/block.ts +++ b/packages/runtime-vapor/src/block.ts @@ -334,7 +334,7 @@ export function normalizeBlock(block: Block): Node[] { return nodes } -export function findBlockNode(block: Block): { +export function findBlockBoundary(block: Block): { parentNode: Node | null nextNode: Node | null } { diff --git a/packages/runtime-vapor/src/component.ts b/packages/runtime-vapor/src/component.ts index a6f412694fd..3556e01eaad 100644 --- a/packages/runtime-vapor/src/component.ts +++ b/packages/runtime-vapor/src/component.ts @@ -41,7 +41,7 @@ import { warn, warnExtraneousAttributes, } from '@vue/runtime-dom' -import { type Block, findBlockNode, insert, isBlock, remove } from './block' +import { type Block, findBlockBoundary, insert, isBlock, remove } from './block' import { type ShallowRef, markRaw, @@ -106,7 +106,6 @@ import { withDeferredHydrationBoundary, } from './dom/hydration' import { createComment, createElement, createTextNode } from './dom/node' -import type { TeleportFragment } from './components/Teleport' import { isTeleportEnabled, isTeleportFragment, @@ -486,7 +485,8 @@ export function createComponent( if ( instance.block && hydrationClose && - findBlockNode(instance.block).nextNode === hydrationClose.nextSibling + findBlockBoundary(instance.block).nextNode === + hydrationClose.nextSibling ) { setCurrentHydrationNode(hydrationClose) } @@ -708,7 +708,7 @@ export class VaporComponentInstance< restoreAsyncContext?: () => void | (() => void) deferredHydrationBoundary?: () => void - // for vapor custom element + // for vapor custom element and hmr rerender renderEffects?: RenderEffect[] hasFallthrough: boolean @@ -748,7 +748,6 @@ export class VaporComponentInstance< devtoolsRawSetupState?: any hmrRerender?: () => void hmrReload?: (newComp: VaporComponent) => void - parentTeleport?: TeleportFragment | null propsOptions?: NormalizedPropsOptions emitsOptions?: ObjectEmitsOptions | null isSingleRoot?: boolean diff --git a/packages/runtime-vapor/src/components/KeepAlive.ts b/packages/runtime-vapor/src/components/KeepAlive.ts index 2c47bad9dc4..d4f9585d3c1 100644 --- a/packages/runtime-vapor/src/components/KeepAlive.ts +++ b/packages/runtime-vapor/src/components/KeepAlive.ts @@ -20,7 +20,7 @@ import { warn, watch, } from '@vue/runtime-dom' -import { type Block, findBlockNode, move, remove } from '../block' +import { type Block, findBlockBoundary, move, remove } from '../block' import { type VaporComponent, type VaporComponentInstance, @@ -136,7 +136,7 @@ const VaporKeepAliveImpl = defineVaporComponent({ if (cached !== current) { // Cached blocks may contain interop children whose VDOM teardown // is owned by remove(), not scope.stop(). - const parentNode = findBlockNode(cached).parentNode + const parentNode = findBlockBoundary(cached).parentNode if (parentNode) remove(cached, parentNode as ParentNode) } }) @@ -281,7 +281,7 @@ const VaporKeepAliveImpl = defineVaporComponent({ if (cached && (!current || cached !== current)) { unsetShapeFlag(cached) // A pruned branch may still be leaving and not yet be in storageContainer. - const parentNode = findBlockNode(cached).parentNode + const parentNode = findBlockBoundary(cached).parentNode if (parentNode) remove(cached, parentNode as ParentNode) } else if (current) { unsetShapeFlag(current) diff --git a/packages/runtime-vapor/src/components/Teleport.ts b/packages/runtime-vapor/src/components/Teleport.ts index 6b045add717..fb3273c7865 100644 --- a/packages/runtime-vapor/src/components/Teleport.ts +++ b/packages/runtime-vapor/src/components/Teleport.ts @@ -170,16 +170,6 @@ export class TeleportFragment extends VaporFragment { if (this.parentComponent && this.parentComponent.ut) { this.registerUpdateCssVars(block) } - - if (__DEV__) { - if (isVaporComponent(block)) { - block.parentTeleport = this - } else if (isArray(block)) { - block.forEach( - node => isVaporComponent(node) && (node.parentTeleport = this), - ) - } - } } private handleChildrenUpdate(children: Block): void { diff --git a/packages/runtime-vapor/src/fragment.ts b/packages/runtime-vapor/src/fragment.ts index 77b6e45ac41..8b84b3de717 100644 --- a/packages/runtime-vapor/src/fragment.ts +++ b/packages/runtime-vapor/src/fragment.ts @@ -9,7 +9,7 @@ import { type BlockFn, type TransitionOptions, type VaporTransitionHooks, - findBlockNode, + findBlockBoundary, insert, isValidBlock, remove, @@ -729,7 +729,7 @@ export class DynamicFragment extends VaporFragment { parentNode = currentSlotEndAnchor.parentNode nextNode = currentSlotEndAnchor } else { - const node = findBlockNode(this.nodes) + const node = findBlockBoundary(this.nodes) parentNode = node.parentNode nextNode = node.nextNode } diff --git a/packages/runtime-vapor/src/hmr.ts b/packages/runtime-vapor/src/hmr.ts index f29ccbbbe9b..14d50e49911 100644 --- a/packages/runtime-vapor/src/hmr.ts +++ b/packages/runtime-vapor/src/hmr.ts @@ -1,35 +1,34 @@ import { - isKeepAlive, popWarningContext, pushWarningContext, setCurrentInstance, } from '@vue/runtime-dom' -import { type Block, insert, normalizeBlock, remove } from './block' +import { findBlockBoundary, insert, remove } from './block' import { type VaporComponent, type VaporComponentInstance, createComponent, devRender, - isVaporComponent, mountComponent, unmountComponent, } from './component' -import { isArray } from '@vue/shared' -import { isFragment } from './fragment' -import { isKeepAliveEnabled } from './keepAlive' export function hmrRerender(instance: VaporComponentInstance): void { - const normalized = normalizeBlock(instance.block) - const parent = normalized[0].parentNode! - const anchor = normalized[normalized.length - 1].nextSibling - // reset scope to avoid stale effects - instance.scope.reset() + const { parentNode, nextNode: anchor } = findBlockBoundary(instance.block) + const parent = parentNode as ParentNode + if (instance.renderEffects) { + instance.renderEffects.forEach(e => e.stop()) + instance.renderEffects.length = 0 + } remove(instance.block, parent) const prev = setCurrentInstance(instance) pushWarningContext(instance) - devRender(instance) - popWarningContext() - setCurrentInstance(...prev) + try { + devRender(instance) + } finally { + popWarningContext() + setCurrentInstance(...prev) + } insert(instance.block, parent, anchor) } @@ -37,94 +36,38 @@ export function hmrReload( instance: VaporComponentInstance, newComp: VaporComponent, ): void { - // If parent is KeepAlive, rerender it so new component goes through - // KeepAlive's slot rendering flow to receive activated hooks properly - if (isKeepAliveEnabled && instance.parent && isKeepAlive(instance.parent)) { - instance.parent.hmrRerender!() + const parentInstance = instance.parent + + // Align child reloads with VDOM HMR: rerender the parent instead of + // surgically swapping the child instance. A local swap can leave parent + // block ownership, component refs, or exposed instances pointing at the old + // instance. + if (parentInstance) { + parentInstance.hmrRerender!() return } - const normalized = normalizeBlock(instance.block) - const parent = normalized[0].parentNode! - const anchor = normalized[normalized.length - 1].nextSibling + + const { parentNode, nextNode: anchor } = findBlockBoundary(instance.block) + const parent = parentNode as ParentNode unmountComponent(instance, parent) - const parentInstance = instance.parent as VaporComponentInstance | null const prev = setCurrentInstance(parentInstance) - const newInstance = createComponent( - newComp, - instance.rawProps, - instance.rawSlots, - instance.isSingleRoot, - undefined, - instance.appContext, - ) - setCurrentInstance(...prev) - mountComponent(newInstance, parent, anchor) - - updateParentBlockOnHmrReload(parentInstance, instance, newInstance) - updateParentTeleportOnHmrReload(instance, newInstance) -} - -/** - * dev only - * update parentInstance.block to ensure that the correct parent and - * anchor are found during parentInstance HMR rerender/reload, as - * `normalizeBlock` relies on the current instance.block - */ -function updateParentBlockOnHmrReload( - parentInstance: VaporComponentInstance | null, - instance: VaporComponentInstance, - newInstance: VaporComponentInstance, -): void { - if (parentInstance) { - parentInstance.block = replaceBlockInstance( - parentInstance.block, - instance, - newInstance, + let newInstance: VaporComponentInstance + try { + newInstance = createComponent( + newComp, + instance.rawProps, + instance.rawSlots, + instance.isSingleRoot, + undefined, + instance.appContext, ) + } finally { + setCurrentInstance(...prev) } -} - -/** - * dev only - * during root component HMR reload, since the old component will be unmounted - * and a new one will be mounted, we need to update the teleport's nodes - * to ensure that the correct parent and anchor are found during parentInstance - * HMR rerender/reload, as `normalizeBlock` relies on the current instance.block - */ -export function updateParentTeleportOnHmrReload( - instance: VaporComponentInstance, - newInstance: VaporComponentInstance, -): void { - const teleport = instance.parentTeleport - if (teleport) { - newInstance.parentTeleport = teleport - teleport.nodes = replaceBlockInstance(teleport.nodes, instance, newInstance) - } -} - -function replaceBlockInstance( - block: Block, - instance: VaporComponentInstance, - newInstance: VaporComponentInstance, -): Block { - if (block === instance) return newInstance - - if (isArray(block)) { - for (let i = 0; i < block.length; i++) { - block[i] = replaceBlockInstance(block[i], instance, newInstance) - } - return block - } - - if (isVaporComponent(block)) { - block.block = replaceBlockInstance(block.block, instance, newInstance) - return block - } + mountComponent(newInstance, parent, anchor) - if (isFragment(block)) { - block.nodes = replaceBlockInstance(block.nodes, instance, newInstance) - return block + const app = instance.appContext.app + if (app && app._instance === instance) { + app._instance = newInstance } - - return block } diff --git a/packages/runtime-vapor/src/renderEffect.ts b/packages/runtime-vapor/src/renderEffect.ts index 86efd582840..fe6a1b01c09 100644 --- a/packages/runtime-vapor/src/renderEffect.ts +++ b/packages/runtime-vapor/src/renderEffect.ts @@ -44,9 +44,9 @@ export class RenderEffect extends ReactiveEffect { : void 0 } - // register effect for vapor custom element update - if (instance.type.ce) { - ;(instance.renderEffects || (instance.renderEffects = [])).push(this) + // register effect for vapor custom element update and dev HMR cleanup + if (instance.type.ce || __DEV__) { + ;(instance.renderEffects ||= []).push(this) } job.i = instance }