Skip to content

Commit cc43fef

Browse files
authored
Merge pull request #4050 from motiondivision/claude/project-thread-5hniaw
Fix AnimatePresence exit never starting when a child mounts already exiting
2 parents 7415b6c + 0a0584b commit cc43fef

5 files changed

Lines changed: 320 additions & 14 deletions

File tree

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
import { AnimatePresence, motion } from "framer-motion"
2+
import { Suspense, useState } from "react"
3+
4+
/**
5+
* #4049: Selecting an uncached item suspends the boundary, and the render
6+
* that reveals it again removes the action, which must still exit.
7+
*/
8+
const cache = new Map<string, { hasAction: boolean }>([
9+
["a", { hasAction: true }],
10+
])
11+
const pending = new Map<string, Promise<void>>()
12+
13+
const read = (id: string) => {
14+
const item = cache.get(id)
15+
if (item) return item
16+
17+
if (!pending.has(id)) {
18+
pending.set(
19+
id,
20+
new Promise<void>((resolve) =>
21+
setTimeout(() => {
22+
cache.set(id, { hasAction: false })
23+
resolve()
24+
}, 300)
25+
)
26+
)
27+
}
28+
29+
throw pending.get(id)
30+
}
31+
32+
const Details = ({ id }: { id: string }) => {
33+
const { hasAction } = read(id)
34+
35+
return (
36+
<>
37+
<p id={"item-" + id}>Item {id}</p>
38+
<AnimatePresence>
39+
{hasAction && (
40+
<motion.button
41+
key="action"
42+
id="action"
43+
initial={{ opacity: 0 }}
44+
animate={{ opacity: 1 }}
45+
exit={{ opacity: 0 }}
46+
transition={{ duration: 0.2 }}
47+
>
48+
Action for {id}
49+
</motion.button>
50+
)}
51+
</AnimatePresence>
52+
</>
53+
)
54+
}
55+
56+
export const App = () => {
57+
const [id, setId] = useState("a")
58+
59+
return (
60+
<>
61+
<button id="select-c" onClick={() => setId("c")}>
62+
Select C
63+
</button>
64+
<Suspense fallback={<p id="loading">Loading…</p>}>
65+
<Details id={id} />
66+
</Suspense>
67+
</>
68+
)
69+
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
describe("AnimatePresence child removed as Suspense reveals it", () => {
2+
it("exits and unmounts", () => {
3+
cy.visit("?test=animate-presence-suspense-reveal")
4+
.wait(300)
5+
.get("#action")
6+
.should("exist")
7+
.get("#select-c")
8+
.click()
9+
.get("#loading")
10+
.should("exist")
11+
.get("#item-c")
12+
.should("exist")
13+
.get("#action")
14+
.should("not.exist")
15+
})
16+
})
Lines changed: 212 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,212 @@
1+
import { act, Suspense, useState } from "react"
2+
import { AnimatePresence, motion, useIsPresent } from "../../.."
3+
import { nextFrame } from "../../../gestures/__tests__/utils"
4+
import { render } from "../../../jest.setup"
5+
6+
interface Item {
7+
name: string
8+
hasAction: boolean
9+
}
10+
11+
const isExit = (definition: any) => definition.opacity === 0
12+
13+
async function waitForRemoval(query: () => Element | null) {
14+
for (let i = 0; i < 60 && query(); i++) await act(nextFrame)
15+
}
16+
17+
/**
18+
* #4049: A Suspense boundary that's already showing content suspends again,
19+
* and the render that reveals it removes a child of AnimatePresence. React
20+
* detaches the hidden tree's refs while it's suspended and attaches them
21+
* again on reveal, so the exiting child mounts again already exiting.
22+
*/
23+
function renderItems(isStrict: boolean, duration = 0.05) {
24+
const cache = new Map<string, Item>([
25+
["A", { name: "A", hasAction: true }],
26+
["B", { name: "B", hasAction: false }],
27+
])
28+
let resolveItem = () => {}
29+
let pending: Promise<void> | undefined
30+
31+
const read = (id: string) => {
32+
const item = cache.get(id)
33+
if (item) return item
34+
35+
throw (pending ||= new Promise<void>((resolve) => {
36+
resolveItem = () => {
37+
cache.set(id, { name: id, hasAction: false })
38+
resolve()
39+
}
40+
}))
41+
}
42+
43+
const onAnimationStart = jest.fn()
44+
45+
const Details = ({ id }: { id: string }) => {
46+
const item = read(id)
47+
48+
return (
49+
<div>
50+
<p>Item {item.name}</p>
51+
<AnimatePresence>
52+
{item.hasAction && (
53+
<motion.button
54+
key="action"
55+
initial={{ opacity: 0 }}
56+
animate={{ opacity: 1 }}
57+
exit={{ opacity: 0 }}
58+
transition={{ duration }}
59+
onAnimationStart={onAnimationStart}
60+
>
61+
Action for {item.name}
62+
</motion.button>
63+
)}
64+
</AnimatePresence>
65+
</div>
66+
)
67+
}
68+
69+
let select = (_id: string) => {}
70+
71+
const App = () => {
72+
const [id, setId] = useState("A")
73+
select = setId
74+
75+
return (
76+
<Suspense fallback={<p>Loading…</p>}>
77+
<Details id={id} />
78+
</Suspense>
79+
)
80+
}
81+
82+
const result = render(<App />, isStrict)
83+
84+
return {
85+
...result,
86+
action: () => result.queryByText("Action for A"),
87+
exitStarted: () => onAnimationStart.mock.calls.some(([d]) => isExit(d)),
88+
select: (id: string) => act(() => select(id)),
89+
resolve: () => act(async () => resolveItem()),
90+
}
91+
}
92+
93+
describe.each([true, false])(
94+
"AnimatePresence child that mounts already exiting (StrictMode: %s)",
95+
(isStrict) => {
96+
test("exits when removed without suspending", async () => {
97+
const { action, getByText, exitStarted, select } =
98+
renderItems(isStrict)
99+
100+
for (let i = 0; i < 10; i++) await act(nextFrame)
101+
102+
await select("B")
103+
expect(getByText("Item B")).toBeInTheDocument()
104+
105+
await waitForRemoval(action)
106+
107+
expect(exitStarted()).toBe(true)
108+
expect(action()).toBeNull()
109+
})
110+
111+
test("exits when removed by the render that reveals a Suspense boundary", async () => {
112+
const { action, getByText, exitStarted, select, resolve } =
113+
renderItems(isStrict)
114+
115+
// Wait for the enter animation to finish
116+
for (let i = 0; i < 10; i++) await act(nextFrame)
117+
118+
await select("C")
119+
expect(getByText("Loading…")).toBeInTheDocument()
120+
121+
await resolve()
122+
expect(getByText("Item C")).toBeInTheDocument()
123+
124+
await waitForRemoval(action)
125+
126+
expect(exitStarted()).toBe(true)
127+
expect(action()).toBeNull()
128+
})
129+
130+
test("exits from the values it showed before the boundary suspended", async () => {
131+
const { action, select, resolve } = renderItems(isStrict, 1)
132+
133+
// Wait for the enter animation to finish
134+
for (let i = 0; i < 80 && action()?.style.opacity !== "1"; i++) {
135+
await act(nextFrame)
136+
}
137+
expect(action()!.style.opacity).toBe("1")
138+
139+
await select("C")
140+
await resolve()
141+
142+
/**
143+
* The action is only shown again to animate out, so it mustn't
144+
* be reset to initial={{ opacity: 0 }} first, which would hide
145+
* it without a visible exit.
146+
*/
147+
let maxOpacity = 0
148+
for (let i = 0; i < 120 && action(); i++) {
149+
await act(nextFrame)
150+
const opacity = action()?.style.opacity
151+
if (opacity) maxOpacity = Math.max(maxOpacity, +opacity)
152+
}
153+
154+
expect(maxOpacity).toBeGreaterThan(0.5)
155+
expect(action()).toBeNull()
156+
})
157+
158+
test("a motion component first rendered by an exiting child exits", async () => {
159+
const onAnimationStart = jest.fn()
160+
161+
const Child = () => {
162+
const isPresent = useIsPresent()
163+
164+
return (
165+
<div>
166+
<motion.div
167+
exit={{ opacity: 0 }}
168+
transition={{ duration: 0.05 }}
169+
/>
170+
{!isPresent && (
171+
<motion.div
172+
data-testid="late"
173+
initial={{ opacity: 0 }}
174+
animate={{ opacity: 1 }}
175+
exit={{ opacity: 0 }}
176+
transition={{ duration: 0.05 }}
177+
onAnimationStart={onAnimationStart}
178+
/>
179+
)}
180+
</div>
181+
)
182+
}
183+
184+
let setShow = (_show: boolean) => {}
185+
186+
const App = () => {
187+
const [show, set] = useState(true)
188+
setShow = set
189+
190+
return (
191+
<AnimatePresence>
192+
{show && <Child key="child" />}
193+
</AnimatePresence>
194+
)
195+
}
196+
197+
const { queryByTestId } = render(<App />, isStrict)
198+
const late = () => queryByTestId("late")
199+
200+
await act(nextFrame)
201+
act(() => setShow(false))
202+
expect(late()).toBeInTheDocument()
203+
204+
await waitForRemoval(late)
205+
206+
expect(onAnimationStart.mock.calls.some(([d]) => isExit(d))).toBe(
207+
true
208+
)
209+
expect(late()).toBeNull()
210+
})
211+
}
212+
)

‎packages/framer-motion/src/motion/features/animation/exit.ts‎

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -11,17 +11,21 @@ export class ExitAnimationFeature extends Feature<unknown> {
1111
private exit?: Promise<unknown> | true
1212

1313
update() {
14-
const { presenceContext, prevPresenceContext, animationState } =
15-
this.node
14+
const { presenceContext, animationState } = this.node
1615

1716
if (!presenceContext || !animationState) return
1817

1918
const { isPresent, onExitComplete } = presenceContext
20-
const prevIsPresent = prevPresenceContext?.isPresent
2119

22-
if (isPresent === prevIsPresent) return
20+
/**
21+
* Compare presence with our own exit, not the previous presence
22+
* context. An element can mount already exiting, for instance when
23+
* Suspense reveals it in the render that removed it, and then both
24+
* contexts have isPresent: false (#4049).
25+
*/
26+
if (isPresent === !this.exit) return
2327

24-
if (isPresent && prevIsPresent === false) {
28+
if (isPresent) {
2529
/**
2630
* When re-entering after the exit completed (element is at
2731
* rest), replay the enter animation from initial.
@@ -55,9 +59,9 @@ export class ExitAnimationFeature extends Feature<unknown> {
5559
return
5660
}
5761

58-
const exit = (this.exit = animationState.setActive("exit", !isPresent))
62+
const exit = (this.exit = animationState.setActive("exit", true))
5963

60-
if (onExitComplete && !isPresent) {
64+
if (onExitComplete) {
6165
exit.then(() => {
6266
/**
6367
* An exit can resolve after the element has re-entered, e.g.
@@ -71,15 +75,14 @@ export class ExitAnimationFeature extends Feature<unknown> {
7175
}
7276

7377
mount() {
74-
const { register, onExitComplete } = this.node.presenceContext || {}
75-
76-
if (onExitComplete) {
77-
onExitComplete(this.id)
78-
}
78+
const { register } = this.node.presenceContext || {}
7979

8080
if (register) {
8181
this.unmount = register(this.id, this.node)
8282
}
83+
84+
// Start the exit of an element that mounts already exiting
85+
this.update()
8386
}
8487

8588
unmount() {}

‎packages/motion-dom/src/render/VisualElement.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -451,9 +451,15 @@ export abstract class VisualElement<
451451
* If this element has been mounted before (e.g. after a Suspense
452452
* unmount/remount), reset motion values to their initial state
453453
* so animations replay correctly from initial → animate, unless
454-
* the presence asks to keep them.
454+
* the presence asks to keep them or the element is only shown
455+
* again to exit (#4049).
455456
*/
456-
if (this.hasBeenMounted && !this.presenceContext?.keepValuesOnRemount) {
457+
const presence = this.presenceContext
458+
if (
459+
this.hasBeenMounted &&
460+
presence?.isPresent !== false &&
461+
!presence?.keepValuesOnRemount
462+
) {
457463
for (const key in this.initialValues) {
458464
this.values.get(key)?.jump(this.initialValues[key])
459465
this.latestValues[key] = this.initialValues[key]

0 commit comments

Comments
 (0)