moved state out of url
All checks were successful
Deploy to Cloudflare Pages / deploy (push) Successful in 31s

This commit is contained in:
christian 2024-11-02 18:25:14 +01:00
parent 154962ff21
commit 5eab4fd47c
2 changed files with 41 additions and 44 deletions

View File

@ -1,37 +1,32 @@
import { useSearchParams } from '@remix-run/react'; import { useState, useEffect, MouseEvent, useRef, Dispatch, SetStateAction } from 'react';
import { useState, useEffect, MouseEvent, useRef } from 'react';
type Coordinates = {
x: number;
y: number;
}
interface DraggableBoxProps { interface DraggableBoxProps {
tag: string;
initialX: number; initialX: number;
initialY: number; initialY: number;
className?: string; className?: string;
children?: React.ReactNode; children?: React.ReactNode;
setter?: Dispatch<SetStateAction<Coordinates>>;
} }
const DraggableBox = ({ const DraggableBox = ({
tag,
initialX, initialX,
initialY, initialY,
className = "", className = "",
children = "" children = "",
setter
}: DraggableBoxProps) => { }: DraggableBoxProps) => {
const [isDragging, setIsDragging] = useState(false); const [isDragging, setIsDragging] = useState(false);
const [dragOffset, setDragOffset] = useState({ x: 0, y: 0 }); const [dragOffset, setDragOffset] = useState({ x: 0, y: 0 });
const [searchParams, setSearchParams] = useSearchParams(); const [xPosition, setXPosition] = useState(initialX)
const [yPosition, setYPosition] = useState(initialY)
const dragRef = useRef<HTMLDivElement>(null); const dragRef = useRef<HTMLDivElement>(null);
const xParam = `x${tag}`;
const yParam = `y${tag}`;
useEffect(() => { useEffect(() => {
if (!searchParams.has(xParam) || !searchParams.has(yParam)) {
const newParams = new URLSearchParams(searchParams);
newParams.set(xParam, initialX.toString());
newParams.set(yParam, initialY.toString());
setSearchParams(newParams, { replace: true });
}
if (!isDragging) return; if (!isDragging) return;
const handleMouseMove = (e: globalThis.MouseEvent) => { const handleMouseMove = (e: globalThis.MouseEvent) => {
@ -47,13 +42,14 @@ const DraggableBox = ({
const maxX = parentRect.width - boxRect.width; const maxX = parentRect.width - boxRect.width;
const maxY = parentRect.height - boxRect.height; const maxY = parentRect.height - boxRect.height;
const newX = Math.max(0, Math.min(relativeX, maxX)); setXPosition(Math.max(0, Math.min(relativeX, maxX)));
const newY = Math.max(0, Math.min(relativeY, maxY)); setYPosition(Math.max(0, Math.min(relativeY, maxY)));
if (setter) {
const newParams = new URLSearchParams(searchParams); setter({
newParams.set(xParam, newX.toString()); x: relativeX,
newParams.set(yParam, newY.toString()); y: relativeY
setSearchParams(newParams, { replace: true }); })
}
}; };
const handleMouseUp = () => setIsDragging(false); const handleMouseUp = () => setIsDragging(false);
@ -65,18 +61,16 @@ const DraggableBox = ({
window.removeEventListener('mousemove', handleMouseMove); window.removeEventListener('mousemove', handleMouseMove);
window.removeEventListener('mouseup', handleMouseUp); window.removeEventListener('mouseup', handleMouseUp);
}; };
}, [isDragging, dragOffset, tag, searchParams, initialX, initialY]); }, [isDragging, dragOffset, xPosition, yPosition, initialX, initialY]);
const handleMouseDown = (e: MouseEvent) => { const handleMouseDown = (e: MouseEvent) => {
if (!dragRef.current?.parentElement) return; if (!dragRef.current?.parentElement) return;
const parentRect = dragRef.current.parentElement.getBoundingClientRect(); const parentRect = dragRef.current.parentElement.getBoundingClientRect();
const currentX = parseInt(searchParams.get(xParam) || '0');
const currentY = parseInt(searchParams.get(yParam) || '0');
setDragOffset({ setDragOffset({
x: e.clientX - parentRect.left - currentX, x: e.clientX - parentRect.left - xPosition,
y: e.clientY - parentRect.top - currentY y: e.clientY - parentRect.top - yPosition
}); });
setIsDragging(true); setIsDragging(true);
}; };
@ -86,7 +80,7 @@ const DraggableBox = ({
ref={dragRef} ref={dragRef}
className={`absolute cursor-move bg-red-500 rounded-full w-4 h-4 text-white shadow-lg ${className}`} className={`absolute cursor-move bg-red-500 rounded-full w-4 h-4 text-white shadow-lg ${className}`}
style={{ style={{
transform: `translate(${searchParams.get(xParam) || 0}px, ${searchParams.get(yParam) || 0}px)`, transform: `translate(${xPosition}px, ${yPosition}px)`,
userSelect: 'none', userSelect: 'none',
}} }}
onMouseDown={handleMouseDown} onMouseDown={handleMouseDown}

View File

@ -16,29 +16,32 @@ export default function Index() {
const [selectorWidth, setSelectorWidth] = useState(0); const [selectorWidth, setSelectorWidth] = useState(0);
const [selectorTop, setSelectorTop] = useState(0); const [selectorTop, setSelectorTop] = useState(0);
const [selectorLeft, setSelectorLeft] = useState(0); const [selectorLeft, setSelectorLeft] = useState(0);
const [firstDragable, setFirstDragable] = useState({
x: 0,
y: 0
})
// Parse the values and convert to numbers, using 0 as fallback const [secondDragable, setSecondDragable] = useState({
let x1 = Number(searchParams.get("x1") || 0); x: 0,
let y1 = Number(searchParams.get("y1") || 0); y: 0
let x2 = Number(searchParams.get("x2") || 0); })
let y2 = Number(searchParams.get("y2") || 0);
// Use useEffect to calculate dimensions and position // Use useEffect to calculate dimensions and position
useEffect(() => { useEffect(() => {
// Calculate width // Calculate width
const width = Math.abs(x2 - x1); const width = Math.abs(secondDragable.x - firstDragable.x);
setSelectorWidth(width); setSelectorWidth(width);
// Calculate height // Calculate height
const height = Math.abs(y2 - y1); const height = Math.abs(secondDragable.y - firstDragable.y);
setSelectorHeight(height); setSelectorHeight(height);
// Calculate top position (minimum of y coordinates) // Calculate top position (minimum of y coordinates)
setSelectorTop(Math.min(y1, y2)); setSelectorTop(Math.min(firstDragable.y, secondDragable.y));
// Calculate left position (minimum of x coordinates) // Calculate left position (minimum of x coordinates)
setSelectorLeft(Math.min(x1, x2)); setSelectorLeft(Math.min(firstDragable.x, secondDragable.x));
}, [x1, x2, y1, y2]); }, [firstDragable, secondDragable]);
return ( return (
<div className="flex h-screen w-screen justify-center items-center"> <div className="flex h-screen w-screen justify-center items-center">
@ -52,8 +55,8 @@ export default function Index() {
width: `${selectorWidth}px`, width: `${selectorWidth}px`,
}} }}
/> />
<DragableBox tag="1" initialX={0} initialY={0} /> <DragableBox initialX={0} initialY={0} setter={setFirstDragable} />
<DragableBox tag="2" initialX={100} initialY={100} /> <DragableBox initialX={100} initialY={100} setter={setSecondDragable} />
</div> </div>
</div> </div>
); );