-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGrid.tsx
85 lines (77 loc) · 2.5 KB
/
Grid.tsx
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import { twMerge } from "tailwind-merge";
import { usePathfinding } from "../hooks/usePathfinding";
import { MAX_COLS, MAX_ROWS } from "../utils/constants";
import { Tile } from "./Tile";
import { MutableRefObject, useState } from "react";
import { checkIfStartOrEnd, createNewGrid } from "../utils/helpers";
export function Grid({
isVisualizationRunningRef,
}: {
isVisualizationRunningRef: MutableRefObject<boolean>;
}) {
const { grid, setGrid } = usePathfinding();
const [isMouseDown, setIsMouseDown] = useState(false);
const handleMouseDown = (row: number, col: number) => {
if (isVisualizationRunningRef.current || checkIfStartOrEnd(row, col)) {
return;
}
setIsMouseDown(true);
const newGrid = createNewGrid(grid, row, col);
setGrid(newGrid);
};
const handleMouseUp = (row: number, col: number) => {
if (isVisualizationRunningRef.current || checkIfStartOrEnd(row, col)) {
return;
}
setIsMouseDown(false);
};
const handleMouseEnter = (row: number, col: number) => {
if (isVisualizationRunningRef.current || checkIfStartOrEnd(row, col)) {
return;
}
if (isMouseDown) {
const newGrid = createNewGrid(grid, row, col);
setGrid(newGrid);
}
};
return (
<div
className={twMerge(
// Base classes
"flex items-center flex-col justify-center border-sky-300 mt-10",
// Control Grid height
`lg:min-h-[${MAX_ROWS * 17}px] md:min-h-[${
MAX_ROWS * 15
}px] xs:min-h-[${MAX_ROWS * 8}px] min-h-[${MAX_ROWS * 7}px]`,
// Controlling grid width
`lg:w-[${MAX_COLS * 17}px] md:w-[${MAX_COLS * 15}px] xs:w-[${
MAX_COLS * 8
}px] w-[${MAX_COLS * 7}px]`
)}
>
{grid.map((r, rowIndex) => (
<div key={rowIndex} className="flex">
{r.map((tile, tileIndex) => {
const { row, col, isEnd, isStart, isPath, isTraversed, isWall } =
tile;
return (
<Tile
key={tileIndex}
row={tile.row}
col={tile.col}
isEnd={isEnd}
isStart={isStart}
isPath={isPath}
isTraversed={isTraversed}
isWall={isWall}
handleMouseDown={() => handleMouseDown(row, col)}
handleMouseUp={() => handleMouseUp(row, col)}
handleMouseEnter={() => handleMouseEnter(row, col)}
/>
);
})}
</div>
))}
</div>
);
}