import { isRef, onMounted, watchEffect, onBeforeUnmount } from 'vue';
import '../../utils/index.mjs';
import { addUnit } from '../../utils/dom/style.mjs';

const useDraggable = (targetRef, dragRef, draggable, topOffest = 0) => {
  const onMousedown = (e) => {
    if (!targetRef.value)
      return;
    const downX = e.clientX;
    const downY = e.clientY;
    let offsetX = 0;
    let offsetY = 0;
    const transform = window.getComputedStyle(targetRef.value).transform;
    if (transform !== "none") {
      const matrix = new WebKitCSSMatrix(transform);
      offsetX = matrix.e;
      offsetY = matrix.f;
    }
    const targetRect = targetRef.value.getBoundingClientRect();
    const targetLeft = targetRect.left;
    const targetTop = targetRect.top;
    const targetWidth = targetRect.width;
    const targetHeight = targetRect.height;
    const clientWidth = document.documentElement.clientWidth;
    const clientHeight = document.documentElement.clientHeight;
    const minLeft = -targetLeft + offsetX;
    const minTop = -targetTop + offsetY + topOffest;
    const maxLeft = clientWidth - targetLeft - targetWidth + offsetX;
    const maxTop = clientHeight - targetTop - targetHeight + offsetY;
    const onMousemove = (e2) => {
      const moveX = Math.min(Math.max(offsetX + e2.clientX - downX, minLeft), maxLeft);
      const moveY = Math.min(Math.max(offsetY + e2.clientY - downY, minTop), maxTop);
      targetRef.value.style.transform = `translate(${addUnit(moveX)}, ${addUnit(moveY)})`;
    };
    const onMouseup = () => {
      document.removeEventListener("mousemove", onMousemove);
      document.removeEventListener("mouseup", onMouseup);
    };
    document.addEventListener("mousemove", onMousemove);
    document.addEventListener("mouseup", onMouseup);
  };
  const onDraggable = () => {
    var _a;
    if (targetRef.value) {
      if (isRef(dragRef)) {
        (_a = dragRef.value) == null ? void 0 : _a.addEventListener("mousedown", onMousedown);
      } else {
        if (dragRef) {
          const dragDom = document.querySelectorAll(dragRef);
          Array.prototype.forEach.call(dragDom, (dom) => dom == null ? void 0 : dom.addEventListener("mousedown", onMousedown));
        }
      }
    }
  };
  const offDraggable = () => {
    var _a;
    if (targetRef.value) {
      if (isRef(dragRef)) {
        (_a = dragRef.value) == null ? void 0 : _a.removeEventListener("mousedown", onMousedown);
      } else {
        if (dragRef) {
          const dragDom = document.querySelectorAll(dragRef);
          Array.prototype.forEach.call(dragDom, (dom) => dom == null ? void 0 : dom.removeEventListener("mousedown", onMousedown));
        }
      }
    }
  };
  onMounted(() => {
    watchEffect(() => {
      console.log(1);
      draggable.value ? onDraggable() : offDraggable();
    });
  });
  onBeforeUnmount(() => {
    offDraggable();
  });
};

export { useDraggable };
//# sourceMappingURL=index.mjs.map
