summaryrefslogtreecommitdiff
path: root/src/components/grid/GridComponent.tsx
blob: 9ec528e533f6dd7b79d8e10f656e315909703da0 (plain)
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
59
60
61
import React, { useState } from 'react';

import type { Grid, GridCell } from '@/types/grid';
import { Cell } from '@/components/grid/Cell';

interface GridProps {
    grid: Grid;
    onCellInteract?: (cell: GridCell) => void;
    onDragStart?: () => void;
    onDragEnd?: () => void;
}

export const GridComponent: React.FC<GridProps> = ({
    grid,
    onCellInteract,
    onDragStart,
    onDragEnd,
}) => {
    const [isDragging, setIsDragging] = useState(false);

    const handleMouseDown = (e: React.MouseEvent) => {
        e.preventDefault(); // Prevent text selection
        setIsDragging(true);
        onDragStart?.();
    };

    const handleMouseUp = () => {
        setIsDragging(false);
        onDragEnd?.();
    };

    const handleMouseLeave = () => {
        if (isDragging) {
            setIsDragging(false);
            onDragEnd?.();
        }
    };

    return (
        <div
            className='grid'
            onMouseDown={handleMouseDown}
            onMouseUp={handleMouseUp}
            onMouseLeave={handleMouseLeave}
            style={{ userSelect: 'none' }}
        >
            {grid.map((row, i) => (
                <div className='grid-row' key={i}>
                    {row.map((cell, j) => (
                        <Cell
                            key={j}
                            cell={cell}
                            onClick={onCellInteract ? () => onCellInteract(cell) : undefined}
                            onMouseEnter={isDragging && onCellInteract ? () => onCellInteract(cell) : undefined}
                        />
                    ))}
                </div>
            ))}
        </div>
    );
};