Skip to content

Commit c053920

Browse files
committed
fix: Ensure useMotionValueEvent animationComplete fires for useSpring
1 parent b5df740 commit c053920

File tree

2 files changed

+60
-1
lines changed

2 files changed

+60
-1
lines changed

packages/framer-motion/src/value/__tests__/use-spring.test.tsx

Lines changed: 55 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { motionValue, MotionValue } from "motion-dom"
22
import { useEffect } from "react"
3-
import { motion } from "../../"
3+
import { motion, useMotionValueEvent } from "../../"
44
import { syncDriver } from "../../animation/animators/__tests__/utils"
55
import { render } from "../../jest.setup"
66
import { useMotionValue } from "../use-motion-value"
@@ -225,3 +225,57 @@ const runSpringTests = (unit?: string | undefined) => {
225225
// Run tests for both number values and percentage values
226226
runSpringTests()
227227
runSpringTests("%")
228+
229+
describe("useSpring animation events", () => {
230+
test("triggers animationStart event when spring animation begins", async () => {
231+
const promise = new Promise<boolean>((resolve) => {
232+
const Component = () => {
233+
const x = useMotionValue(0)
234+
const springX = useSpring(x, {
235+
stiffness: 100,
236+
damping: 10,
237+
})
238+
239+
useMotionValueEvent(springX, "animationStart", () => {
240+
resolve(true)
241+
})
242+
243+
useEffect(() => {
244+
x.set(100)
245+
}, [x])
246+
247+
return null
248+
}
249+
250+
render(<Component />)
251+
})
252+
253+
await expect(promise).resolves.toBe(true)
254+
})
255+
256+
test("triggers animationComplete event when spring animation finishes", async () => {
257+
const promise = new Promise<boolean>((resolve) => {
258+
const Component = () => {
259+
const x = useMotionValue(0)
260+
const springX = useSpring(x, {
261+
stiffness: 1000,
262+
damping: 50,
263+
})
264+
265+
useMotionValueEvent(springX, "animationComplete", () => {
266+
resolve(true)
267+
})
268+
269+
useEffect(() => {
270+
x.set(100)
271+
}, [x])
272+
273+
return null
274+
}
275+
276+
render(<Component />)
277+
})
278+
279+
await expect(promise).resolves.toBe(true)
280+
})
281+
})

packages/motion-dom/src/value/spring-value.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,12 @@ export function attachSpring<T extends AnyResolvedKeyframe>(
6363
restSpeed: 0.01,
6464
...options,
6565
onUpdate: latestSetter,
66+
onComplete: () => {
67+
value["events"].animationComplete?.notify()
68+
},
6669
})
70+
71+
value['events'].animationStart?.notify()
6772
}
6873

6974
value.attach((v, set) => {

0 commit comments

Comments
 (0)