UNPKG

itm-holding-package

Version:

ITM HOLDING PACKAGES

59 lines (58 loc) 2.55 kB
import { useEffect, useRef, useState } from 'react'; export const useDraggable = ({ initialPosition = { x: 20, y: 20 }, boundaryElement = null, onPositionChange, } = {}) => { const [position, setPosition] = useState(initialPosition); const [isDragging, setIsDragging] = useState(false); const elementRef = useRef(null); // Pour stocker la position initiale du clic lors du drag const dragStartRef = useRef({ x: 0, y: 0 }); useEffect(() => { const element = elementRef.current; if (!element) return; const handleMouseDown = (e) => { setIsDragging(true); const rect = element.getBoundingClientRect(); // Stocker la position initiale du clic dragStartRef.current = { x: e.clientX - rect.left, y: e.clientY - rect.top, }; document.body.classList.add('dragging'); }; const handleMouseMove = (e) => { if (!isDragging) return; let newX = e.clientX - dragStartRef.current.x; let newY = e.clientY - dragStartRef.current.y; // Si un élément boundary est fourni, limiter le mouvement if (boundaryElement) { const boundaryRect = boundaryElement.getBoundingClientRect(); const elementRect = element.getBoundingClientRect(); newX = Math.max(0, Math.min(newX, boundaryRect.width - elementRect.width)); newY = Math.max(0, Math.min(newY, boundaryRect.height - elementRect.height)); } setPosition({ x: newX, y: newY }); onPositionChange?.({ x: newX, y: newY }); }; const handleMouseUp = () => { setIsDragging(false); document.body.classList.remove('dragging'); }; // Ajouter les event listeners element.addEventListener('mousedown', handleMouseDown); document.addEventListener('mousemove', handleMouseMove); document.addEventListener('mouseup', handleMouseUp); // Cleanup return () => { element.removeEventListener('mousedown', handleMouseDown); document.removeEventListener('mousemove', handleMouseMove); document.removeEventListener('mouseup', handleMouseUp); document.body.classList.remove('dragging'); }; }, [isDragging, position, boundaryElement, onPositionChange]); return { position, isDragging, elementRef, }; };