diff --git a/src/components/grid/grid.tsx b/src/components/grid/grid.tsx index c945ecb..3974165 100644 --- a/src/components/grid/grid.tsx +++ b/src/components/grid/grid.tsx @@ -29,25 +29,14 @@ function snapToGrid(p: Point, gap: number): Point { }; } -const ORIGIN: Point = { x: 0, y: 0 }; - -function useWindowSizeCustom() { - const sizeRaw = useWindowSize(); - const size = useMemo(() => { - if (sizeRaw.width === null || sizeRaw.height === null) return null; - return { width: sizeRaw.width, height: sizeRaw.height }; - }, [sizeRaw]); - return size; -} - function useRange(offset: Point): Range { - const windowSize = useWindowSizeCustom(); + const windowSize = useWindowSize(); const range = useMemo( () => ({ x0: offset.x, y0: offset.y, - x1: offset.x + (windowSize?.width || 0), - y1: offset.y + (windowSize?.height || 0), + x1: offset.x + (windowSize.width || 0), + y1: offset.y + (windowSize.height || 0), }), [windowSize, offset] ); @@ -60,18 +49,21 @@ function useMouseInRange(range: Range): Point { } const Grid: FC = () => { - const [offset, setOffset] = useState(ORIGIN); + const GAP = 20; + + // const [offset, setOffset] = useState({ x: GAP / 2, y: GAP / 2 }); + const [offset, setOffset] = useState({ x: 10, y: 10 }); const range = useRange(offset); const mousePoint = useMouseInRange(range); - const GAP = 20; - const gridLines = useMemo(() => { const lines = []; - for (let x = range.x0; x <= range.x1; x += GAP) { + const start = snapToGrid({ x: range.x0, y: range.y0 }, GAP); + const end = snapToGrid({ x: range.x1, y: range.y1 }, GAP); + for (let x = start.x; x <= end.x; x += GAP) { lines.push({ ...range, x0: x, x1: x }); } - for (let y = range.y0; y <= range.y1; y += GAP) { + for (let y = start.y; y <= end.y; y += GAP) { lines.push({ ...range, y0: y, y1: y }); } @@ -140,9 +132,7 @@ const Grid: FC = () => { const onGridClick = useCallback( (event: MouseEvent) => { - console.log('grid click', event); - const pointRaw = { x: event.clientX, y: event.clientY }; - const point = snapToGrid(pointRaw, GAP); + const point = snapToGrid(mousePoint, GAP); if (lodash.isEqual(userStartPoint, point)) return; if (lodash.isNull(userStartPoint)) { @@ -159,14 +149,16 @@ const Grid: FC = () => { setUserStartPoint(point); } }, - [userStartPoint, setUserStartPoint, setUserLines, GAP] + [userStartPoint, setUserStartPoint, setUserLines, GAP, mousePoint] ); return ( {gridLineElements}