image-converter-client/app/routes/CropSelector.tsx
christian 521dabe17a
All checks were successful
Deploy to Cloudflare Pages / deploy (push) Successful in 28s
suspense not needed
2024-11-03 22:41:10 +01:00

76 lines
2.3 KiB
TypeScript

import { Suspense, useEffect, useRef, useState } from "react";
import DragableBox from "./DragableBox";
import { PhAngle } from "./PhAngle";
type Coordinates = {
x: number;
y: number;
}
export default function CropSelector() {
const [firstDragable, setFirstDragable] = useState<Coordinates>({
x: 0,
y: 0
});
const [secondDragable, setSecondDragable] = useState<Coordinates>({
x: 100,
y: 100
});
const [selectorPosition, setSelectorPosition] = useState<Coordinates>({
x: 0,
y: 0
});
const containerRef = useRef<HTMLDivElement>(null);
// Update selector position and dimensions based on handle positions
useEffect(() => {
setSelectorPosition({
x: Math.min(firstDragable.x, secondDragable.x),
y: Math.min(firstDragable.y, secondDragable.y)
});
}, [firstDragable, secondDragable]);
// Calculate selector dimensions
const selectorWidth = Math.abs(secondDragable.x - firstDragable.x);
const selectorHeight = Math.abs(secondDragable.y - firstDragable.y);
// Handle selector drag
const handleSelectorDrag = (newPosition: Coordinates) => {
const deltaX = newPosition.x - selectorPosition.x;
const deltaY = newPosition.y - selectorPosition.y;
setFirstDragable({
x: Math.min(firstDragable.x, secondDragable.x) + deltaX,
y: Math.min(firstDragable.y, secondDragable.y) + deltaY
});
setSecondDragable({
x: Math.max(firstDragable.x, secondDragable.x) + deltaX,
y: Math.max(firstDragable.y, secondDragable.y) + deltaY
});
};
return (
<div className="flex flex-col h-screen w-screen justify-center items-center">
<div ref={containerRef} className="relative w-1/3 h-1/3 border-black border">
<DragableBox
position={selectorPosition}
mode="box"
width={selectorWidth}
height={selectorHeight}
coordSetter={setSelectorPosition}
onDrag={handleSelectorDrag}
className="border border-black"
/>
<DragableBox position={firstDragable} coordSetter={setFirstDragable} mode="handle">
<PhAngle />
</DragableBox>
<DragableBox position={secondDragable} coordSetter={setSecondDragable} mode="handle">
<PhAngle />
</DragableBox>
</div>
</div>
);
}