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

65 lines
1.8 KiB
TypeScript
Raw Normal View History

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";
import { DragDropContext } from "react-beautiful-dnd";
import { StrictModeDroppable } from "./StrictModeDroppable";
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-11 07:25:28 +00:00
<StrictModeDroppable 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>
)}
</StrictModeDroppable>
</DragDropContext>
);
};