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
56 changes: 55 additions & 1 deletion packages/framer-motion/src/value/__tests__/use-spring.test.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { motionValue, MotionValue } from "motion-dom"
import { useEffect } from "react"
import { motion } from "../../"
import { motion, useMotionValueEvent } from "../../"
import { syncDriver } from "../../animation/animators/__tests__/utils"
import { render } from "../../jest.setup"
import { useMotionValue } from "../use-motion-value"
Expand Down Expand Up @@ -225,3 +225,57 @@ const runSpringTests = (unit?: string | undefined) => {
// Run tests for both number values and percentage values
runSpringTests()
runSpringTests("%")

describe("useSpring animation events", () => {
test("triggers animationStart event when spring animation begins", async () => {
const promise = new Promise<boolean>((resolve) => {
const Component = () => {
const x = useMotionValue(0)
const springX = useSpring(x, {
stiffness: 100,
damping: 10,
})

useMotionValueEvent(springX, "animationStart", () => {
resolve(true)
})

useEffect(() => {
x.set(100)
}, [x])

return null
}

render(<Component />)
})

await expect(promise).resolves.toBe(true)
})

test("triggers animationComplete event when spring animation finishes", async () => {
const promise = new Promise<boolean>((resolve) => {
const Component = () => {
const x = useMotionValue(0)
const springX = useSpring(x, {
stiffness: 1000,
damping: 50,
})

useMotionValueEvent(springX, "animationComplete", () => {
resolve(true)
})

useEffect(() => {
x.set(100)
}, [x])

return null
}

render(<Component />)
})

await expect(promise).resolves.toBe(true)
})
})
8 changes: 7 additions & 1 deletion packages/motion-dom/src/value/spring-value.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,13 @@ export function attachSpring<T extends AnyResolvedKeyframe>(
latestValue = v
latestSetter = (latest) => set(parseValue(latest, unit) as T)

frame.postRender(startAnimation)
frame.postRender(()=>{
startAnimation()
value['events'].animationStart?.notify()
activeAnimation?.then(()=>{
value['events'].animationComplete?.notify()
})
})
}, stopAnimation)

if (isMotionValue(source)) {
Expand Down