37 lines
1.0 KiB
JavaScript
37 lines
1.0 KiB
JavaScript
|
|
import { useState, useRef, useCallback, useEffect } from 'react';
|
||
|
|
|
||
|
|
export default function useDraggable() {
|
||
|
|
const [position, setPosition] = useState({ x: 0, y: 0 });
|
||
|
|
const dragging = useRef(false);
|
||
|
|
const dragStart = useRef({ x: 0, y: 0 });
|
||
|
|
|
||
|
|
const handleMouseDown = useCallback((e) => {
|
||
|
|
dragging.current = true;
|
||
|
|
dragStart.current = {
|
||
|
|
x: e.clientX - position.x,
|
||
|
|
y: e.clientY - position.y,
|
||
|
|
};
|
||
|
|
e.preventDefault();
|
||
|
|
}, [position]);
|
||
|
|
|
||
|
|
useEffect(() => {
|
||
|
|
const handleMouseMove = (e) => {
|
||
|
|
if (!dragging.current) return;
|
||
|
|
setPosition({
|
||
|
|
x: e.clientX - dragStart.current.x,
|
||
|
|
y: e.clientY - dragStart.current.y,
|
||
|
|
});
|
||
|
|
};
|
||
|
|
const handleMouseUp = () => { dragging.current = false; };
|
||
|
|
|
||
|
|
window.addEventListener('mousemove', handleMouseMove);
|
||
|
|
window.addEventListener('mouseup', handleMouseUp);
|
||
|
|
return () => {
|
||
|
|
window.removeEventListener('mousemove', handleMouseMove);
|
||
|
|
window.removeEventListener('mouseup', handleMouseUp);
|
||
|
|
};
|
||
|
|
}, []);
|
||
|
|
|
||
|
|
return { position, handleMouseDown };
|
||
|
|
}
|