2023-08-11 13:59:00 +00:00
|
|
|
import { useState } from "react";
|
2023-08-11 07:25:28 +00:00
|
|
|
import { Box } from "@mui/material";
|
2023-08-29 12:39:51 +00:00
|
|
|
import { DragDropContext, Droppable } from "react-beautiful-dnd";
|
2023-08-11 07:25:28 +00:00
|
|
|
|
|
|
|
import { DraggableListItem } from "./DraggableListItem";
|
|
|
|
|
|
|
|
import { questionStore, updateQuestionsListDragAndDrop } from "@root/questions";
|
|
|
|
|
|
|
|
import { reorder } from "./helper";
|
|
|
|
|
|
|
|
import type { DropResult } from "react-beautiful-dnd";
|
|
|
|
|
|
|
|
export const DraggableList = () => {
|
2023-08-11 10:36:33 +00:00
|
|
|
const [draggableId, setDraggableId] = useState<number>(-1);
|
|
|
|
const [dropPlaceIndex, setDropPlaceIndex] = useState<number>(-1);
|
2023-08-11 07:25:28 +00:00
|
|
|
const { listQuestions } = questionStore();
|
|
|
|
|
2023-08-11 13:59:00 +00:00
|
|
|
const onDrop = () => {
|
|
|
|
setDraggableId(-1);
|
|
|
|
setDropPlaceIndex(-1);
|
|
|
|
};
|
|
|
|
|
2023-08-11 07:25:28 +00:00
|
|
|
const onDragEnd = ({ destination, source }: DropResult) => {
|
|
|
|
if (destination) {
|
|
|
|
const newItems = reorder(listQuestions, source.index, destination.index);
|
|
|
|
|
|
|
|
updateQuestionsListDragAndDrop(newItems);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
return (
|
2023-08-11 10:36:33 +00:00
|
|
|
<DragDropContext
|
|
|
|
onDragStart={({ draggableId }) => setDraggableId(Number(draggableId))}
|
|
|
|
onDragUpdate={({ destination }) => {
|
|
|
|
setDropPlaceIndex(destination?.index ?? -1);
|
|
|
|
}}
|
|
|
|
onDragEnd={onDragEnd}
|
|
|
|
>
|
2023-08-29 12:39:51 +00:00
|
|
|
<Droppable droppableId="droppable-list">
|
2023-08-11 10:36:33 +00:00
|
|
|
{(provided) => (
|
2023-08-11 13:59:00 +00:00
|
|
|
<Box
|
|
|
|
ref={provided.innerRef}
|
|
|
|
{...provided.droppableProps}
|
|
|
|
onMouseUp={onDrop}
|
|
|
|
>
|
2023-08-11 07:25:28 +00:00
|
|
|
{listQuestions.map((_, index) => (
|
|
|
|
<DraggableListItem
|
|
|
|
key={index}
|
|
|
|
index={index}
|
2023-08-11 10:36:33 +00:00
|
|
|
dropPlaceIndex={
|
|
|
|
dropPlaceIndex < draggableId
|
|
|
|
? dropPlaceIndex - 1
|
|
|
|
: dropPlaceIndex
|
|
|
|
}
|
2023-08-11 07:25:28 +00:00
|
|
|
/>
|
|
|
|
))}
|
|
|
|
{provided.placeholder}
|
|
|
|
</Box>
|
|
|
|
)}
|
2023-08-29 12:39:51 +00:00
|
|
|
</Droppable>
|
2023-08-11 07:25:28 +00:00
|
|
|
</DragDropContext>
|
|
|
|
);
|
|
|
|
};
|