image-converter-client/app/routes/DragableBox.tsx

97 lines
2.6 KiB
TypeScript
Raw Normal View History

2024-11-02 17:25:14 +00:00
import { useState, useEffect, MouseEvent, useRef, Dispatch, SetStateAction } from 'react';
type Coordinates = {
x: number;
y: number;
}
2024-11-02 15:47:17 +00:00
interface DraggableBoxProps {
initialX: number;
initialY: number;
className?: string;
children?: React.ReactNode;
2024-11-02 17:25:14 +00:00
setter?: Dispatch<SetStateAction<Coordinates>>;
2024-11-02 15:47:17 +00:00
}
const DraggableBox = ({
initialX,
initialY,
className = "",
2024-11-02 17:25:14 +00:00
children = "",
setter
2024-11-02 15:47:17 +00:00
}: DraggableBoxProps) => {
const [isDragging, setIsDragging] = useState(false);
const [dragOffset, setDragOffset] = useState({ x: 0, y: 0 });
2024-11-02 17:25:14 +00:00
const [xPosition, setXPosition] = useState(initialX)
const [yPosition, setYPosition] = useState(initialY)
2024-11-02 15:47:17 +00:00
const dragRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!isDragging) return;
const handleMouseMove = (e: globalThis.MouseEvent) => {
if (!dragRef.current?.parentElement) return;
const parent = dragRef.current.parentElement;
const parentRect = parent.getBoundingClientRect();
const boxRect = dragRef.current.getBoundingClientRect();
const relativeX = e.clientX - parentRect.left - dragOffset.x;
const relativeY = e.clientY - parentRect.top - dragOffset.y;
const maxX = parentRect.width - boxRect.width;
const maxY = parentRect.height - boxRect.height;
2024-11-02 22:30:55 +00:00
let newX = (Math.max(0, Math.min(relativeX, maxX)));
let newY = (Math.max(0, Math.min(relativeY, maxY)));
setXPosition(newX);
setYPosition(newY);
2024-11-02 17:25:14 +00:00
if (setter) {
setter({
2024-11-02 22:30:55 +00:00
x: newX,
y: newY
2024-11-02 17:25:14 +00:00
})
}
2024-11-02 15:47:17 +00:00
};
const handleMouseUp = () => setIsDragging(false);
window.addEventListener('mousemove', handleMouseMove);
window.addEventListener('mouseup', handleMouseUp);
return () => {
window.removeEventListener('mousemove', handleMouseMove);
window.removeEventListener('mouseup', handleMouseUp);
};
2024-11-02 17:25:14 +00:00
}, [isDragging, dragOffset, xPosition, yPosition, initialX, initialY]);
2024-11-02 15:47:17 +00:00
const handleMouseDown = (e: MouseEvent) => {
if (!dragRef.current?.parentElement) return;
const parentRect = dragRef.current.parentElement.getBoundingClientRect();
setDragOffset({
2024-11-02 17:25:14 +00:00
x: e.clientX - parentRect.left - xPosition,
y: e.clientY - parentRect.top - yPosition
2024-11-02 15:47:17 +00:00
});
setIsDragging(true);
};
return (
<div
ref={dragRef}
2024-11-02 22:30:55 +00:00
className={`absolute cursor-pointer ${className}`}
2024-11-02 15:47:17 +00:00
style={{
2024-11-02 17:25:14 +00:00
transform: `translate(${xPosition}px, ${yPosition}px)`,
2024-11-02 15:47:17 +00:00
userSelect: 'none',
}}
onMouseDown={handleMouseDown}
>
{children}
</div>
);
};
export default DraggableBox;