All files / src/components/ui/lists EntityListItemDnD.tsx

0% Statements 0/18
0% Branches 0/7
0% Functions 0/5
0% Lines 0/16

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                                                                                           
import React, { useRef } from "react";
import {
  DragSourceMonitor,
  DropTargetMonitor,
  useDrag,
  useDrop,
} from "react-dnd";
import { EntityListItem } from "ui/lists/EntityListItem";
 
type EntityListItemDnDProps<
  T extends { name: string; labelColor?: string; warning?: string },
> = {
  dragType: string;
  acceptTypes?: string[];
  onDrop?: (draggedItem: T, targetItem: T) => void;
} & React.ComponentProps<typeof EntityListItem<T>>;
 
export const EntityListItemDnD = <
  T extends { name: string; labelColor?: string; warning?: string },
>({
  item,
  dragType,
  acceptTypes,
  onDrop,
  ...rest
}: EntityListItemDnDProps<T>) => {
  const [{ isOver }, drop] = useDrop({
    accept: acceptTypes || [],
    collect: (monitor: DropTargetMonitor) => ({
      isOver: monitor.isOver({ shallow: true }),
    }),
    drop(draggedItem: T, monitor: DropTargetMonitor) {
      Iif (monitor.didDrop()) return;
      onDrop?.(draggedItem, item);
    },
  });
 
  const [_, drag, dragPreview] = useDrag({
    type: dragType,
    item: (): T => item,
    options: { dropEffect: "move" },
    collect: (monitor: DragSourceMonitor) => ({
      isDragging: monitor.isDragging(),
    }),
  });
 
  const dragRef = useRef<HTMLDivElement>(null);
  drag(dragRef);
  drop(dragRef);
  dragPreview(dragRef);
 
  return <EntityListItem item={item} {...rest} ref={dragRef} isOver={isOver} />;
};