/**
 * ldesign v0.2.22
 * (c) 2022/12/7 16:21 built by swimly
 * @license MIT
 */

'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var VueCompositionAPI = require('@vue/composition-api');

function useDragSorter(props, context) {
  const {
    sortOnDraggable,
    onDragSort,
    onDragOverCheck
  } = props;
  const draggingIndex = VueCompositionAPI.ref(-1);
  const dragStartData = VueCompositionAPI.ref(null);
  const isDropped = VueCompositionAPI.ref(null);
  const startInfo = VueCompositionAPI.reactive({
    nodeX: 0,
    nodeWidth: 0,
    mouseX: 0
  });
  const onDragOver = (e, index, record) => {
    e.preventDefault();
    if (draggingIndex.value === index || draggingIndex.value === -1) return;
    const target = e.target;
    if (onDragOverCheck?.targetClassNameRegExp && !onDragOverCheck?.targetClassNameRegExp.test(target.className)) return;
    if (onDragOverCheck?.x && target) {
      if (!startInfo.nodeWidth) return;
      const {
        x,
        width
      } = target.getBoundingClientRect();
      const targetNodeMiddleX = x + width / 2;
      const draggingNodeLeft = e.clientX - (startInfo.mouseX - startInfo.nodeX);
      const draggingNodeRight = draggingNodeLeft + startInfo.nodeWidth;
      let overlap = false;
      if (draggingNodeLeft > x && draggingNodeLeft < x + width) overlap = draggingNodeLeft < targetNodeMiddleX;else overlap = draggingNodeRight > targetNodeMiddleX;
      if (!overlap) return;
    }
    const data = {
      currentIndex: draggingIndex.value,
      current: dragStartData,
      target: record,
      targetIndex: index
    };
    onDragSort?.(data);
    context.emit("drag-sort", data);
    draggingIndex.value = index;
  };
  if (!sortOnDraggable) return {};
  function onDragStart(e, index, record) {
    draggingIndex.value = index;
    dragStartData.value = record;
    const target = e.target;
    if (onDragOverCheck && target) {
      const {
        x,
        width
      } = target.getBoundingClientRect();
      startInfo.nodeX = x;
      startInfo.nodeWidth = width;
      startInfo.mouseX = e.clientX;
    }
  }
  function onDrop() {
    isDropped.value = true;
  }
  function onDragEnd() {
    if (!isDropped.value) ;
    isDropped.value = false;
    draggingIndex.value = -1;
    dragStartData.value = null;
  }
  function getDragProps(index, record) {
    if (sortOnDraggable) {
      return {
        draggable: true,
        onDragstart: e => {
          onDragStart(e, index, record);
        },
        onDragover: e => {
          onDragOver(e, index, record);
        },
        onDrop: () => {
          onDrop();
        },
        onDragend: () => {
          onDragEnd();
        }
      };
    }
  }
  return {
    onDragStart,
    onDragOver,
    onDrop,
    onDragEnd,
    getDragProps,
    dragging: draggingIndex.value !== -1
  };
}

exports["default"] = useDragSorter;
//# sourceMappingURL=use-drag-sorter.js.map
