본문 바로가기
학원에서 배운 것/React

팀플을 하면서 시도했던 드래그앤드롭 코드들..

by 쿠리의일상 2023. 4. 22.

결국 dnd 라이브러리로 성공은 했지만

노가다와 삽질한 흔적을 남겨본다...

 

// 드래그앤드롭 시안 1
const [originPos, setOriginPos] = useState({ x: 0, y: 0 });
  const [clientPos, setClientPos] = useState({ x: 0, y: 0 });
  const [pos, setPos] = useState({ top: 100, left: 0 });
  const draggingRef = useRef(null);
  const draggingOverRef = useRef(null);
  const dispatch = useDispatch();

  const onDragOver = e => {
    e.preventDefault();
  };

  const onDragStart = e => {
    e.dataTransfer.effectAllowed = 'move';
    const originPosTemp = { ...originPos };
    originPosTemp.x = e.target.offsetLeft; //칸반보드 컨텐츠 부분부터
    originPosTemp.y = e.target.offsetTop;
    setOriginPos(originPosTemp);
    console.log(originPosTemp);

    const clientPosTemp = { ...clientPos };
    clientPosTemp.x = e.clientX; // 브라우저 왼쪽 상단부터
    clientPosTemp.y = e.clientY;
    setClientPos(clientPosTemp);
    console.log('clientPosTemp', clientPosTemp);
  };

  const onDrag = e => {
    const PosTemp = { ...pos };
    console.log(pos.left, pos.top);
    // 자신이 위치한 칸반섹션 부터
    PosTemp.left = e.target.offsetLeft + e.clientX - clientPos.x;
    PosTemp.top = e.target.offsetTop + e.clientY - clientPos.y;
    setPos(PosTemp);

    console.log(PosTemp);

    const clientPosTemp = { ...clientPos };
    clientPosTemp.x = e.clientX;
    clientPosTemp.y = e.clientY;
    setClientPos(clientPosTemp);
  };

  let isClick = false;
  let topPos = idx => {
    const init = 100;
    const diff = 90;
    isClick = true;
    return idx > 0 ? idx * diff + init : init;
  };

  const onDragEnd = e => {
    e.dataTransfer.dropEffect = 'move';
    // if (!isInsideDragArea(e)) {
    //   const posTemp = { ...pos };
    //   posTemp.left = originPos.x;
    //   posTemp.top = originPos.y;
    //   setPos(posTemp);
    // }
  };

  // 드래그앤드롭 시안2
  const onDragStart = (e, idx, progress) => {
    console.log('onDragging');
    draggingRef.current = idx;
  };

  const onDragging = (e, idx, progress) => {
    console.log('onDragging');
    draggingOverRef.current = idx;

    // dispatch(
    //   changeOrder({
    //     newIdx,
    //     oldIdx,
    //     draggingItem,
    //     workspaceId: 0,
    //     progress,
    //     copyList,
    //   })
    // );
  };

  const onDrop = (e, idx, progress) => {
    console.log('onDrop');
    const copyList = [...workflowList];
    const draggingItem = {
      progress: progress,
      item: copyList[draggingOverRef.current],
    };

    copyList.splice(draggingRef.current, 1);
    copyList.splice(draggingOverRef.current, 0, draggingItem);

    let newIdx = draggingOverRef.current;
    let oldIdx = draggingItem.current;
    draggingRef.current = draggingOverRef.current;
    draggingOverRef.current = null;

    dispatch(
      changeOrder({
        newIdx,
        oldIdx,
        draggingItem,
        workspaceId: 0,
        progress,
        copyList,
      })
    );
  };