Major UI update

This commit is contained in:
Niels Geens
2024-11-06 16:12:50 +01:00
parent 70ed16f8ab
commit 6e78a0f0bd
16 changed files with 594 additions and 358 deletions

View File

@@ -0,0 +1,72 @@
import { useState, useEffect, useRef, useCallback } from 'react';
import { WebSocketState, MessageType } from '../constants';
export const useWebSocket = (url) => {
const [wsState, setWsState] = useState(WebSocketState.DISCONNECTED);
const wsRef = useRef(null);
const messageHandlersRef = useRef({});
const connect = useCallback(() => {
setWsState(WebSocketState.CONNECTING);
const ws = new WebSocket(url);
wsRef.current = ws;
ws.onopen = () => {
setWsState(WebSocketState.CONNECTED);
};
ws.onclose = () => {
setWsState(WebSocketState.DISCONNECTED);
setTimeout(connect, 2000);
};
ws.onerror = (error) => {
console.error('WebSocket error:', error);
};
ws.onmessage = (event) => {
try {
const message = JSON.parse(event.data);
const handler = messageHandlersRef.current[message.type];
if (handler) {
handler(message);
} else {
console.warn('No handler for message type:', message.type);
}
} catch (error) {
console.error('Error handling WebSocket message:', error);
}
};
return ws;
}, [url]);
useEffect(() => {
const ws = connect();
return () => {
if (ws) ws.close();
};
}, [connect]);
const sendMessage = useCallback((type, data = null) => {
if (wsRef.current?.readyState === WebSocket.OPEN) {
const message = {
type,
data: data || undefined
};
wsRef.current.send(JSON.stringify(message));
} else {
console.error('WebSocket not connected, state:', wsRef.current?.readyState);
}
}, []);
const setMessageHandler = useCallback((type, handler) => {
messageHandlersRef.current[type] = handler;
}, []);
return {
wsState,
sendMessage,
setMessageHandler
};
};