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
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { motion, useDragControls } from "../../../"
import { useState } from "react"
import { motion, useDragControls, DragControls } from "../../../"
import { render } from "../../../jest.setup"
import { nextFrame } from "../../__tests__/utils"
import { MockDrag, drag } from "./utils"
Expand Down Expand Up @@ -72,4 +73,71 @@ describe("useDragControls", () => {
await nextFrame()
expect(onDragStart).toBeCalledTimes(1)
})

test("dragControls can be updated", async () => {
const onDragStart = jest.fn()
const Component = ({
dragControls,
}: {
dragControls: DragControls | undefined
}) => {
return (
<MockDrag>
<div
onPointerDown={(e) => dragControls?.start(e)}
data-testid="drag-handle"
/>
<motion.div
drag
onDragStart={onDragStart}
dragControls={dragControls}
data-testid="draggable"
/>
</MockDrag>
)
}

const ControlledComponent = () => {
const controls1 = useDragControls()
const controls2 = useDragControls()
const [useFirst, setUseFirst] = useState(true)

return (
<>
<button
data-testid="switch"
onClick={() => setUseFirst(false)}
/>
<Component
dragControls={useFirst ? controls1 : controls2}
/>
</>
)
}

const { rerender, getByTestId } = render(<ControlledComponent />)
rerender(<ControlledComponent />)

// First drag with initial controls
let pointer = await drag(
getByTestId("draggable"),
getByTestId("drag-handle")
).to(100, 100)
pointer.end()
await nextFrame()
expect(onDragStart).toBeCalledTimes(1)

// Switch controls
getByTestId("switch").click()
await nextFrame()

// Drag again with new controls
pointer = await drag(
getByTestId("draggable"),
getByTestId("drag-handle")
).to(100, 100)
pointer.end()
await nextFrame()
expect(onDragStart).toBeCalledTimes(2)
})
})
12 changes: 12 additions & 0 deletions packages/framer-motion/src/gestures/drag/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,18 @@ export class DragGesture extends Feature<HTMLElement> {
this.removeListeners = this.controls.addListeners() || noop
}

update() {
const { dragControls } = this.node.getProps()
const { dragControls: prevDragControls } = this.node.prevProps || {}

if (dragControls !== prevDragControls) {
this.removeGroupControls()
if (dragControls) {
this.removeGroupControls = dragControls.subscribe(this.controls)
}
}
}

unmount() {
this.removeGroupControls()
this.removeListeners()
Expand Down