File size: 1,781 Bytes
f5071ca |
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 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
import React, { useRef, useContext } from 'react';
import { useDrag, useDrop } from 'react-dnd';
import BoardContext from '../Board/context';
import { Container, Label } from './styles';
export default function Card({ data, index, listIndex }) {
const ref = useRef();
const { move } = useContext(BoardContext);
const [{ isDragging }, dragRef] = useDrag({
item: {
type: 'CARD',
index,
listIndex
},
collect: monitor => ({
isDragging: monitor.isDragging(),
})
});
const [, dropRef] = useDrop({
accept: 'CARD',
hover(item, monitor){
const draggedListIndex = item.listIndex;
const targetListIndex = listIndex;
const draggedIndex = item.index;
const targetIndex = index;
if (draggedIndex == targetIndex && draggedListIndex == targetListIndex){
return;
}
const targetSize = ref.current.getBoundingClientRect();
const targetCenter = (targetSize.bottom - targetSize.top) / 2;
const draggedOffset = monitor.getClientOffset();
const draggedTop = draggedOffset.y - targetSize.top;
if (draggedIndex < targetIndex && draggedTop < targetCenter){
return;
}
if (draggedIndex > targetIndex && draggedTop > targetCenter){
return;
}
move(draggedListIndex, targetListIndex, draggedIndex, targetIndex);
item.index = targetIndex;
item.listIndex = targetListIndex;
}
});
dragRef(dropRef(ref));
return (
<Container ref={ref} isDragging={isDragging}>
<header>
{
data.labels.map(label => <Label key={label} color={label} />)
}
</header>
<p>{data.content}</p>
{data.user && (
<img src={data.user} alt=""/>
)}
</Container>
);
}
|