/
Canvas.tsx
52 lines (48 loc) · 1.1 KB
/
Canvas.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import { DndContext, useDroppable } from "@dnd-kit/core";
import { DragEndEvent } from "@dnd-kit/core/dist/types";
import { Card } from "./App";
import { Draggable } from "./Draggable";
export const Canvas = ({
cards,
setCards,
}: {
cards: Card[];
setCards: (cards: Card[]) => void;
}) => {
const saveDragEndPosition = ({ delta, active }: DragEndEvent) => {
if (!delta.x && !delta.y) return;
setCards(
cards.map((card) => {
if (card.id === active.id) {
return {
...card,
coordinates: {
x: card.coordinates.x + delta.x,
y: card.coordinates.y + delta.y,
},
};
}
return card;
})
);
};
const { setNodeRef } = useDroppable({
id: "canvas",
});
return (
<div
className="canvas"
style={{
position: "relative",
height: "300px",
}}
ref={setNodeRef}
>
<DndContext onDragEnd={saveDragEndPosition}>
{cards.map((card) => (
<Draggable card={card} key={card.id} />
))}
</DndContext>
</div>
);
};