summaryrefslogtreecommitdiff
path: root/apps/web/src/components/editor/selection-box.tsx
blob: 69b753f4b6cbe8248bdfdbb91a629be38d461fe2 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
"use client";

import { useEffect, useRef } from "react";

interface SelectionBoxProps {
	startPos: { x: number; y: number } | null;
	currentPos: { x: number; y: number } | null;
	containerRef: React.RefObject<HTMLElement>;
	isActive: boolean;
}

export function SelectionBox({
	startPos,
	currentPos,
	containerRef,
	isActive,
}: SelectionBoxProps) {
	const selectionBoxRef = useRef<HTMLDivElement>(null);

	useEffect(() => {
		if (!isActive || !startPos || !currentPos || !containerRef.current) return;

		const container = containerRef.current;
		const containerRect = container.getBoundingClientRect();

		// Calculate relative positions within the container
		const startX = startPos.x - containerRect.left;
		const startY = startPos.y - containerRect.top;
		const currentX = currentPos.x - containerRect.left;
		const currentY = currentPos.y - containerRect.top;

		// Calculate the selection rectangle bounds
		const left = Math.min(startX, currentX);
		const top = Math.min(startY, currentY);
		const width = Math.abs(currentX - startX);
		const height = Math.abs(currentY - startY);

		// Update the selection box position and size
		if (selectionBoxRef.current) {
			selectionBoxRef.current.style.left = `${left}px`;
			selectionBoxRef.current.style.top = `${top}px`;
			selectionBoxRef.current.style.width = `${width}px`;
			selectionBoxRef.current.style.height = `${height}px`;
		}
	}, [startPos, currentPos, isActive, containerRef]);

	if (!isActive || !startPos || !currentPos) return null;

	return (
		<div
			ref={selectionBoxRef}
			className="absolute pointer-events-none z-50"
			style={{
				backgroundColor: "hsl(var(--foreground) / 0.1)",
			}}
		/>
	);
}