Added server messages handling
This commit is contained in:
parent
633220dbce
commit
dcdc49e8e0
@ -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<ContextData>(defaultState);
|
||||
|
||||
const toggleFree = (index: number) => {};
|
||||
const toggleFree = (id: number) => {
|
||||
ws.send(
|
||||
JSON.stringify(
|
||||
composeMessage<UpdateMessage>("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<number, number> = {};
|
||||
if (isMessage(message)) {
|
||||
if (isListMessage(message)) {
|
||||
const map: RoomDisplay[] = [],
|
||||
char: RoomState[] = [],
|
||||
ids: Record<number, number> = {};
|
||||
|
||||
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 });
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
Loading…
x
Reference in New Issue
Block a user