useDnd

Obsługuje akcję "drag and drop" w kontekście listy wybranych tekstów.

useDnd.js
import { useState, useContext, useEffect } from 'react';
import { PlaylistContext } from 'providers/PlaylistProvider';

const useDnd = () => {
  const { selectedContent, setSelectedContent } = useContext(PlaylistContext);

  // Create association table with drag and drop content
  const createAssociationTable = () => {
    let dndContent = {};
    selectedContent.map(({ content, id, name }) => {
      return (dndContent[id] = { content, id, name });
    });
    return dndContent;
  };

  const createIdsTable = () => {
    return selectedContent.map(({ id }) => id);
  };

  const initialData = {
    dndContent: createAssociationTable(),
    dndContentIds: createIdsTable(),
  };

  const [selectedData, setSelectedData] = useState(initialData);
  // Create a dndContent array containing draggable and droppable elements corresponding to the identifiers stored in dndContentIds
  const dndContent = selectedData.dndContentIds.map((dndContentId) => selectedData.dndContent[dndContentId]);

  useEffect(() => {
    setSelectedData(initialData);
    // eslint-disable-next-line
  }, [selectedContent]);

  // Sorts the selected texts based on the dndContentIds array and updates the selectedContent using setSelectedContent.
  const sortSelectedContent = (dndContentIds) => {
    let sortedSelectedContent = [];
    dndContentIds.forEach((element) => {
      sortedSelectedContent.push(selectedContent.find((elem) => element === elem.id));
    });
    setSelectedContent(sortedSelectedContent);
  };

  // Handling the drag and drop event. It updates the state of selectedData and then calls sortSelectedContent() to re-sort the selected tracks
  const onDragEnd = (result) => {
    const { destination, source, draggableId } = result;

    if (!destination) {
      return;
    }

    if (destination.droppableId === source.droppableId && destination.index === source.index) {
      return;
    }

    const newContentIds = Array.from(selectedData.dndContentIds);
    newContentIds.splice(source.index, 1);
    newContentIds.splice(destination.index, 0, draggableId);

    const newState = {
      ...selectedData,
      dndContentIds: newContentIds,
    };

    sortSelectedContent(newContentIds);

    setSelectedData(newState);
  };

  return {
    dndContent,
    onDragEnd,
  };
};

export default useDnd;

Last updated