frontPanel/src/pages/Questions/DraggableList/index.tsx

70 lines
1.9 KiB
TypeScript
Raw Normal View History

2023-08-11 13:59:00 +00:00
import { useState } from "react";
2023-09-06 13:20:12 +00:00
import { useParams } from "react-router-dom";
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-09-06 13:20:12 +00:00
const quizId = Number(useParams().quizId);
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) {
2023-09-06 13:20:12 +00:00
const newItems = reorder(
listQuestions[quizId],
source.index,
destination.index
);
2023-08-11 07:25:28 +00:00
2023-09-06 13:20:12 +00:00
updateQuestionsListDragAndDrop(quizId, newItems);
2023-08-11 07:25:28 +00:00
}
};
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-09-06 13:20:12 +00:00
{listQuestions[quizId]?.map((_, index) => (
2023-08-11 07:25:28 +00:00
<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>
);
};