UNPKG

winbox-ui-next

Version:

We Design Vue 2.0: A Vue.js 3 UI Library

72 lines (71 loc) 2.4 kB
import { ref } from "vue"; import { on, off } from "../../_utils/dom.js"; const useDraggable = ({ modalRef, wrapperRef, draggable }) => { const isDragging = ref(false); const startMouse = ref([0, 0]); const diffMouse = ref([0, 0]); const initialPosition = ref([0, 0]); const position = ref(); const maxPosition = ref([0, 0]); const getInitialPosition = () => { var _a, _b; if (wrapperRef.value && modalRef.value) { const { top: wrapperTop, left: wrapperLeft } = wrapperRef.value.getBoundingClientRect(); const { clientWidth: wrapperWidth, clientHeight: wrapperHeight } = wrapperRef.value; const { top, left, width, height } = modalRef.value.getBoundingClientRect(); const initialX = left - wrapperLeft; const initialY = top - wrapperTop; if (initialX !== ((_a = initialPosition.value) == null ? void 0 : _a[0]) || initialY !== ((_b = initialPosition.value) == null ? void 0 : _b[1])) { initialPosition.value = [initialX, initialY]; } const maxX = wrapperWidth > width ? wrapperWidth - width : 0; const maxY = wrapperHeight > height ? wrapperHeight - height : 0; if (maxX !== maxPosition.value[0] || maxY !== maxPosition.value[1]) { maxPosition.value = [maxX, maxY]; } } }; const handleMoveDown = (ev) => { if (draggable.value) { ev.preventDefault(); isDragging.value = true; getInitialPosition(); startMouse.value = [ev.x, ev.y]; diffMouse.value = [0, 0]; on(window, "mousemove", handleMouseMove); on(window, "mouseup", handleMouseUp); on(window, "contextmenu", handleMouseUp); } }; const handleMouseMove = (ev) => { if (isDragging.value) { const diffX = ev.x - startMouse.value[0]; const diffY = ev.y - startMouse.value[1]; let x = initialPosition.value[0] + diffX; let y = initialPosition.value[1] + diffY; if (x < 0) x = 0; if (x > maxPosition.value[0]) x = maxPosition.value[0]; if (y < 0) y = 0; if (y > maxPosition.value[1]) y = maxPosition.value[1]; position.value = [x, y]; } }; const handleMouseUp = () => { isDragging.value = false; off(window, "mousemove", handleMouseMove); off(window, "mouseup", handleMouseUp); }; return { position, handleMoveDown }; }; export { useDraggable };