Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
97 changes: 97 additions & 0 deletions packages/runtime-vapor/__tests__/components/Transition.gc.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
// @vitest-environment jsdom

import { nextTick, ref } from 'vue'
import { compile, makeRender } from '../_utils'

const define = makeRender()

const gc = () =>
new Promise<void>(resolve => {
setTimeout(() => {
global.gc!()
resolve()
})
})

// Keep the element access out of the async test's retained stack frame.
function getElementRef(host: Element) {
// @ts-expect-error ES2021 API
return new WeakRef(host.firstElementChild!)
}

describe.skipIf(!global.gc)('Transition/gc', () => {
test('in-out: completed leaves release their elements while the app is mounted', async () => {
const removed: { deref(): Element | undefined }[] = []
const data = ref({
key: 0,
onLeave: (el: Element, done: () => void) => {
// @ts-expect-error ES2021 API
removed.push(new WeakRef(el))
done()
},
})
const App = compile(
`<template>
<Transition mode="in-out" :css="false" @leave="data.onLeave">
<div :key="data.key" :id="'k' + data.key" />
</Transition>
</template>`,
data,
)
const { app, host } = define(App).render()

try {
for (let key = 1; key <= 10; key++) {
data.value.key = key
await nextTick()
}
expect(removed).toHaveLength(10)
expect(host.innerHTML).toBe('<div id="k10"></div><!--keyed-->')

await gc()
await gc()
expect(removed.filter(element => element.deref())).toHaveLength(0)
expect(host.innerHTML).toBe('<div id="k10"></div><!--keyed-->')
} finally {
app.unmount()
}
})

test('in-out: early removal releases an element while the next enter is pending', async () => {
const data = ref({
show: true,
// Leave enters pending without retaining their completion callbacks.
onEnter: (_el: Element, _done: () => void) => {},
})
const App = compile(
`<template>
<Transition mode="in-out" :css="false" @enter="data.onEnter">
<div v-if="data.show" id="a" />
<div v-else id="b" />
</Transition>
</template>`,
data,
)
const { app, host } = define(App).render()
const removed = getElementRef(host)

try {
data.value.show = false
await nextTick()
data.value.show = true
await nextTick()
expect(host.innerHTML).toBe(
'<div id="b"></div><div id="a"></div><!--if-->',
)

await gc()
await gc()
expect(removed.deref()).toBeUndefined()
expect(host.innerHTML).toBe(
'<div id="b"></div><div id="a"></div><!--if-->',
)
} finally {
app.unmount()
}
})
})
134 changes: 134 additions & 0 deletions packages/runtime-vapor/__tests__/components/Transition.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2550,4 +2550,138 @@ describe('Transition', () => {
expect(host.innerHTML).not.toContain('class="b"')
expect(host.innerHTML).toContain('fallback')
})

test.each([
['k2', 'k3'],
['k3', 'k2'],
])(
'in-out: each entering child hands off its own leave when %s finishes before %s',
async (first, second) => {
const enters: Record<string, () => void> = {}
const left: string[] = []
const data = ref<any>({
k: 1,
onEnter: (el: Element, done: () => void) => (enters[el.id] = done),
onLeave: (el: Element, done: () => void) => {
left.push(el.id)
done()
},
})
const App = compile(
`<script setup vapor>
const data = _data
</script>
<template>
<Transition mode="in-out" :css="false" @enter="data.onEnter" @leave="data.onLeave">
<div :key="data.k" :id="'k' + data.k" />
</Transition>
</template>`,
data,
)
const { host } = define(App).render()

data.value.k = 2
await nextTick()
data.value.k = 3
await nextTick()
expect(left).toEqual([])

enters[first]()
expect(left).toEqual(first === 'k2' ? ['k1'] : ['k1', 'k2'])
enters[second]()
expect(left).toEqual(['k1', 'k2'])
await nextTick()
expect(host.innerHTML).toBe('<div id="k3"></div><!--keyed-->')
},
)

test('in-out: toggling back before the enter finishes leaves once', async () => {
const enters: Record<string, () => void> = {}
const left: string[] = []
const data = ref<any>({
show: true,
onEnter: (el: Element, done: () => void) => (enters[el.id] = done),
onLeave: (el: Element, done: () => void) => {
left.push(el.id)
done()
},
})
const App = compile(
`<script setup vapor>
const data = _data
</script>
<template>
<Transition mode="in-out" :css="false" @enter="data.onEnter" @leave="data.onLeave">
<div v-if="data.show" id="a" />
<div v-else id="b" />
</Transition>
</template>`,
data,
)
const { host } = define(App).render()

data.value.show = false
await nextTick()
data.value.show = true
await nextTick()

// the first a was early-removed, so b's enter hands off nothing
enters.b()
expect(left).toEqual([])
enters.a()
expect(left).toEqual(['b'])
await nextTick()
expect(host.innerHTML).toBe('<div id="a"></div><!--if-->')
})

test.each(['static', 'dynamic'])(
'in-out: a branch that renders its content later still hands off the leave with a %s default slot',
async slotType => {
const left: string[] = []
const data = ref<any>({
view: 'A',
hasSlot: true,
ready: false,
onLeave: (el: Element, done: () => void) => {
left.push(el.id)
done()
},
})
const A = compile(`<template><div id="a">a</div></template>`, data)
const B = compile(
`<template><div v-if="data.ready" id="b">b</div></template>`,
data,
)
const App = compile(
`<script setup vapor>
const data = _data
const views = _components
</script>
<template>
<Transition mode="in-out" :css="false" @leave="data.onLeave">
${slotType === 'dynamic' ? '<template #default v-if="data.hasSlot">' : ''}
<component :is="views[data.view]" />
${slotType === 'dynamic' ? '</template>' : ''}
</Transition>
</template>`,
data,
{ A, B },
)
const { host } = define(App).render()

data.value.view = 'B'
await nextTick()
// Refresh the hooks while the entering branch still has no element.
data.value.onLeave = (el: Element, done: () => void) => {
left.push(el.id)
done()
}
await nextTick()

data.value.ready = true
await nextTick()
expect(left).toEqual(['a'])
expect(host.innerHTML).not.toContain('id="a"')
},
)
})
67 changes: 48 additions & 19 deletions packages/runtime-vapor/src/components/Transition.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ import {
} from '../component'
import { getAsyncWrapperInner } from '../apiDefineAsyncComponent'
import { isAsyncComponentEnabled } from '../asyncComponentState'
import { isArray } from '@vue/shared'
import { extend, isArray } from '@vue/shared'
import { renderEffect } from '../renderEffect'
import {
DynamicFragment,
Expand Down Expand Up @@ -193,6 +193,8 @@ export const VaporTransition: FunctionalVaporComponent<TransitionProps> =
frag.$transition = applyTransitionHooksImpl(
frag.nodes,
frag.$transition,
undefined,
true,
)
}
if (!isMounted && shouldPerformAppear) performAppear(frag.$transition!)
Expand All @@ -204,7 +206,7 @@ export const VaporTransition: FunctionalVaporComponent<TransitionProps> =
const children = ((slots.default && slots.default()) || []) as any as Block
state.root = children

let appliedHooks = {
const hooks = {
__vapor: true,
state,
// use proxy to keep props reference stable
Expand All @@ -217,10 +219,15 @@ export const VaporTransition: FunctionalVaporComponent<TransitionProps> =
// props eagerly, so propsProxy alone can't keep an already-applied hooks
// closure live; re-applying rebinds the root element's (and any inner
// fragment's) $transition to fresh closures, mirroring VDOM's per-render
// re-resolve. Reusing appliedHooks preserves runtime state (delayedLeave)
// across re-resolves.
// re-resolve. Read runtime state (delayedLeave) from the current branch
// without retaining an earlier branch's hooks in this effect.
renderEffect(() => {
appliedHooks = applyTransitionHooksImpl(children, appliedHooks)
const appliedHooks = applyTransitionHooksImpl(
children,
hooks,
undefined,
isMounted,
)
if (!isMounted) {
isMounted = true
if (shouldPerformAppear) performAppear(appliedHooks)
Expand Down Expand Up @@ -355,6 +362,7 @@ export function applyTransitionHooksImpl(
block: Block,
hooks: VaporTransitionHooks,
owner?: VaporFragment,
refresh = false,
): VaporTransitionHooks {
// filter out comment nodes
if (isArray(block)) {
Expand Down Expand Up @@ -382,9 +390,15 @@ export function applyTransitionHooksImpl(
const fragments: VaporFragment[] = []
const child = resolveTransitionBlock(
block,
fragment => fragments.push(fragment),
fragment => {
fragments.push(fragment)
// Inner branches can replace their hooks without updating outer roots.
// Keep the current handoff even when the branch has no element yet.
if (refresh && fragment.$transition) hooks = fragment.$transition
},
owner,
)
if (refresh && child && child.$transition) hooks = child.$transition
if (!child) {
// set transition hooks on fragments for later use
fragments.forEach(f => (f.$transition = hooks))
Expand Down Expand Up @@ -468,17 +482,10 @@ export function applyTransitionLeaveHooksImpl(
const leavingNodes = getLeavingNodesForType(state, leavingBlock)
const leavingKey = String(getTransitionKey(leavingBlock))
leavingNodes[leavingKey] = leavingBlock
// Bind cleanup to this specific handoff so an older leave callback
// cannot clear a newer delayedLeave during rapid toggles.
const delayedLeaveCb = () => {
delayedLeave()
leavingBlock.$transition = undefined
if (enterHooks.delayedLeave === delayedLeaveCb) {
delete enterHooks.delayedLeave
}
}
const delayedLeaveCb = createDelayedLeave(leavingBlock, delayedLeave)
// early removal callback
block[leaveCbKey] = () => {
delayedLeaveCb(true)
earlyRemove()
block[leaveCbKey] = undefined
leavingBlock.$transition = undefined
Expand All @@ -487,16 +494,32 @@ export function applyTransitionLeaveHooksImpl(
if (leavingNodes[leavingKey] === leavingBlock) {
delete leavingNodes[leavingKey]
}
if (enterHooks.delayedLeave === delayedLeaveCb) {
delete enterHooks.delayedLeave
}
}
enterHooks.delayedLeave = delayedLeaveCb
}
}
return true
}

// Hooks copies share this callback. Keep its captures separate from the
// branch's hooks and release them when the handoff completes or is cancelled.
function createDelayedLeave(
block: ResolvedTransitionBlock | undefined,
leave: (() => void) | undefined,
): (cancelled?: boolean) => void {
return cancelled => {
if (!leave) return
const cb = leave
const leavingBlock = block!
// Settle before invoking hooks, which can synchronously trigger another leave.
leave = block = undefined
if (!cancelled) {
cb()
leavingBlock.$transition = undefined
}
}
}

function deferBranchUpdateDuringLeaveImpl(
frag: DynamicFragment,
render: BlockFn | undefined,
Expand Down Expand Up @@ -541,7 +564,13 @@ function removeBranchWithLeaveImpl(
(mode !== 'out-in' || isValidBlock(frag.nodes))
) {
const instance = currentInstance
applyTransitionLeaveHooksImpl(frag.nodes, transition, () => {
let enterHooks = transition
if (mode === 'in-out') {
// The current child's hooks may still hold the handoff its own pending
// enter will run. Hand this leave to the incoming branch through a copy.
enterHooks = frag.$transition = extend({}, transition)
}
applyTransitionLeaveHooksImpl(frag.nodes, enterHooks, () => {
// Unmounting cuts the leave short and runs afterLeave synchronously;
// the pending branch must not be rendered into the torn-down tree.
if (transition.state.isUnmounting) return
Expand Down
3 changes: 2 additions & 1 deletion packages/runtime-vapor/src/fragment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -449,7 +449,8 @@ export class DynamicFragment extends RenderContextFragment {

this.renderBranch(
render,
transition,
// in-out leave may have swapped in the hooks for the incoming branch
transition && this.$transition,
parent,
key,
noScope,
Expand Down
Loading
Loading