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

0% Statements 0/48
0% Branches 0/23
0% Functions 0/8
0% Lines 0/47

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 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186                                                                                                                                                                                                                                                                                                                                                                                   
import React, { JSX } from "react";
import { DropTargetMonitor, useDrag, useDrop } from "react-dnd";
import type { SortableListOrientation } from "./SortableList";
 
type SortableDragItem<T> = {
  index: number;
  data: T;
};
 
interface SortableItemProps<T> {
  itemType: string;
  item: T;
  index: number;
  orientation: SortableListOrientation;
  renderItem: (
    item: T,
    {
      isOver,
      isDragging,
      dragHandleRef,
    }: {
      isOver: boolean;
      isDragging: boolean;
      dragHandleRef?: React.Ref<HTMLDivElement>;
    },
  ) => JSX.Element;
  onSelect: (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => void;
  moveItems: (dragIndex: number, hoverIndex: number) => void;
  setDragging: (isDragging: boolean) => void;
  useDragHandle?: boolean;
}
 
export const SortableItem = <T,>({
  itemType,
  item,
  index,
  orientation,
  renderItem,
  onSelect,
  moveItems,
  setDragging,
  useDragHandle = false,
}: SortableItemProps<T>) => {
  const ref = React.useRef<HTMLDivElement>(null);
  const dragHandleRef = React.useRef<HTMLDivElement>(null);
 
  const [{ isOver }, drop] = useDrop<
    SortableDragItem<T>,
    void,
    { isOver: boolean }
  >({
    accept: itemType,
    hover(_, monitor: DropTargetMonitor) {
      Iif (!ref.current) {
        return null;
      }
      const dragIndex = (monitor.getItem() as { index: number }).index;
      const hoverIndex = index;
 
      // Don't replace items with themselves
      Iif (dragIndex === hoverIndex) {
        return;
      }
 
      // Determine rectangle on screen
      const hoverBoundingRect = ref.current.getBoundingClientRect();
 
      if (orientation === "horizontal") {
        // Get horizontal middle
        const hoverMiddleX =
          (hoverBoundingRect.right - hoverBoundingRect.left) / 2;
 
        // Determine mouse position
        const clientOffset = monitor.getClientOffset();
 
        Iif (!clientOffset) {
          return;
        }
 
        // Get pixels to the left
        const hoverClientX = clientOffset.x - hoverBoundingRect.left;
 
        // Only perform the move when the mouse has crossed half of the items height
        // When dragging downwards, only move when the cursor is below 50%
        // When dragging upwards, only move when the cursor is above 50%
 
        // Dragging from left to right but not passed middle of element
        Iif (dragIndex < hoverIndex && hoverClientX < hoverMiddleX) {
          return;
        }
 
        // Dragging from right to left but not passed middle of element
        Iif (dragIndex > hoverIndex && hoverClientX > hoverMiddleX) {
          return;
        }
      } else {
        // Get vertical middle
        const hoverMiddleY =
          (hoverBoundingRect.bottom - hoverBoundingRect.top) / 2;
 
        // Determine mouse position
        const clientOffset = monitor.getClientOffset();
 
        Iif (!clientOffset) {
          return;
        }
 
        // Get pixels to the top
        const hoverClientY = clientOffset.y - hoverBoundingRect.top;
 
        // Only perform the move when the mouse has crossed half of the items height
        // When dragging downwards, only move when the cursor is below 50%
        // When dragging upwards, only move when the cursor is above 50%
 
        // Dragging from top to bottom but not passed middle of element
        Iif (dragIndex < hoverIndex && hoverClientY < hoverMiddleY) {
          return;
        }
 
        // Dragging from bottom to top but not passed middle of element
        Iif (dragIndex > hoverIndex && hoverClientY > hoverMiddleY) {
          return;
        }
      }
 
      // Time to actually perform the action
      moveItems(dragIndex, hoverIndex);
 
      // Note: we're mutating the monitor item here!
      // Generally it's better to avoid mutations,
      // but it's good here for the sake of performance
      // to avoid expensive index searches.
      (monitor.getItem() as { index: number }).index = hoverIndex;
    },
    collect(monitor) {
      return {
        isOver: monitor.isOver({ shallow: true }),
      };
    },
  });
 
  const [{ isDragging }, drag, dragPreview] = useDrag<
    SortableDragItem<T>,
    void,
    { isDragging: boolean }
  >(() => ({
    type: itemType,
    collect: (monitor) => {
      return {
        isDragging: monitor.isDragging(),
      };
    },
    item: () => {
      setDragging(true);
      return {
        index,
        data: item,
      };
    },
    end: () => setDragging(false),
  }));
 
  if (useDragHandle) {
    drop(ref);
    drag(dragHandleRef);
  } else {
    drag(drop(ref));
  }
 
  return (
    <div
      ref={(node) => {
        dragPreview(node);
      }}
    >
      <div ref={ref} onMouseDown={onSelect}>
        {renderItem(item, {
          isDragging,
          isOver,
          dragHandleRef: useDragHandle ? dragHandleRef : undefined,
        })}
      </div>
    </div>
  );
};