From e69a8739fa71cdd893ab06193b8d189f95a889bc Mon Sep 17 00:00:00 2001 From: dm1sh Date: Sat, 4 Sep 2021 05:16:25 +0300 Subject: [PATCH] Added room free state toggle with click --- src/components/BuildingPlan.tsx | 46 ++++++++++++++++----------------- 1 file changed, 22 insertions(+), 24 deletions(-) diff --git a/src/components/BuildingPlan.tsx b/src/components/BuildingPlan.tsx index 5337c7d..e921eec 100644 --- a/src/components/BuildingPlan.tsx +++ b/src/components/BuildingPlan.tsx @@ -1,11 +1,27 @@ import { useCallback, useEffect, useState } from "react"; import { useRoomContext } from "../context"; +import { RoomDisplay } from "../types/room"; import { Canvas } from "./Canvas"; export type BuildingPlanProps = { width: number; height: number }; +const getRoomByCoord = (x: number, y: number, map: RoomDisplay[]) => { + for (let i = 0; i < map.length; i++) { + const { coordinates, size } = map[i]; + if ( + x >= coordinates.x && + x <= coordinates.x + size.w && + y >= coordinates.y && + y <= coordinates.y + size.h + ) + return i; + } + + return -1; +}; + export const BuildingPlan = ({ width, height }: BuildingPlanProps) => { - const { state, setState } = useRoomContext(); + const { state, toggleFree } = useRoomContext(); const draw = useCallback( (ctx: CanvasRenderingContext2D) => { @@ -32,32 +48,14 @@ export const BuildingPlan = ({ width, height }: BuildingPlanProps) => { [state.char, state.map] ); - useEffect(() => { - setTimeout( - () => - setState((p) => ({ - ...p, - char: [ - { free: false }, - { free: false }, - { free: false }, - { free: false }, - ], - })), - 1000 - ); - }, []); + const clickCb = (x: number, y: number) => { + const index = getRoomByCoord(x, y, state.map); + if (index >= 0) toggleFree(index); + }; return ( <> - { - console.log(`x: ${x}, y: ${y}`); - }} - height={height} - width={width} - draw={draw} - /> + ); };