diff --git a/apps/front/src/context.tsx b/apps/front/src/context.tsx index 1ff3d89..a62c55c 100644 --- a/apps/front/src/context.tsx +++ b/apps/front/src/context.tsx @@ -3,7 +3,13 @@ import { createContext, FC, useContext, useEffect, useState } from "react"; import { defaultState } from "./constants"; import { ContextData, ContextValue } from "./types/context"; -import { isArrayOf, isMessage, isRoom } from "@roomruler/messages"; +import { + composeMessage, + isListMessage, + isMessage, + isUpdateMessage, + UpdateMessage, +} from "@roomruler/messages"; import { WS_URL } from "./config"; import { RoomDisplay, RoomState } from "./types/room"; @@ -14,31 +20,51 @@ const ws = new WebSocket(WS_URL); export const RoomContextProvider: FC = ({ children }) => { const [state, setState] = useState(defaultState); - const toggleFree = (index: number) => {}; + const toggleFree = (id: number) => { + ws.send( + JSON.stringify( + composeMessage("update", { + id, + value: !state.char[state.ids[id]].free, + }) + ) + ); + }; useEffect(() => { ws.onmessage = ({ data }) => { const message: unknown = JSON.parse(data); - if (isMessage(message) && isArrayOf(message.args, isRoom)) { - const map: RoomDisplay[] = [], - char: RoomState[] = [], - ids: Record = {}; + if (isMessage(message)) { + if (isListMessage(message)) { + const map: RoomDisplay[] = [], + char: RoomState[] = [], + ids: Record = {}; - for (const { - x, - y, - height: h, - width: w, - title, - free, - id, - } of message.args) { - map.push({ coordinates: { x, y }, size: { w, h }, title: title }); - char.push({ free }); - ids[id] = map.length - 1; + for (const { + x, + y, + height: h, + width: w, + title, + free, + id, + } of message.args) { + map.push({ coordinates: { x, y }, size: { w, h }, title: title }); + char.push({ free }); + ids[id] = map.length - 1; + } + + setState({ map, char, ids }); + } else if (isUpdateMessage(message)) { + setState( + produce((draft) => { + const { id, value } = message.args; + const index = draft.ids[id]; + + draft.char[index].free = value; + }) + ); } - - setState({ map, char, ids }); } }; }, []);