feat(web): add WebSocket client and context infrastructure
- WsClient class: connect/disconnect/send/on/off/isConnected/clearCallbacks
- connect() derives wss:// from https:// automatically, returns Promise<void>
- on/off typed with Extract<WsServerMessage, { type: T }> for precise
callback narrowing, callbacks stored as Map<string, Set<fn>>
- ws-context.ts: WsContextValue type + WsContext definition
- ws-provider.tsx: WsProvider with module-level wsClient singleton,
owns connection lifecycle (connect/disconnect/isConnected state)
- ws-hooks.ts: useWsClient, useWsConnected, useWsConnect, useWsDisconnect
This commit is contained in:
parent
d60b0da9df
commit
9affe339c6
4 changed files with 99 additions and 0 deletions
44
apps/web/src/lib/ws-provider.tsx
Normal file
44
apps/web/src/lib/ws-provider.tsx
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
import { useCallback, useEffect, useState } from "react";
|
||||
import type { ReactNode } from "react";
|
||||
import { WsClient } from "./ws-client.js";
|
||||
import { WsContext } from "./ws-context.js";
|
||||
|
||||
const wsClient = new WsClient();
|
||||
|
||||
export const WsProvider = ({ children }: { children: ReactNode }) => {
|
||||
const [isConnected, setIsConnected] = useState(false);
|
||||
|
||||
const connect = useCallback(async (url: string): Promise<void> => {
|
||||
wsClient.onClose = () => setIsConnected(false);
|
||||
wsClient.onError = () => setIsConnected(false);
|
||||
try {
|
||||
await wsClient.connect(url);
|
||||
setIsConnected(true);
|
||||
} catch (err) {
|
||||
setIsConnected(false);
|
||||
throw err;
|
||||
}
|
||||
}, []);
|
||||
|
||||
const disconnect = useCallback((): void => {
|
||||
wsClient.disconnect();
|
||||
setIsConnected(false);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
wsClient.disconnect();
|
||||
wsClient.clearCallbacks();
|
||||
wsClient.onClose = null;
|
||||
wsClient.onError = null;
|
||||
};
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<WsContext.Provider
|
||||
value={{ client: wsClient, isConnected, connect, disconnect }}
|
||||
>
|
||||
{children}
|
||||
</WsContext.Provider>
|
||||
);
|
||||
};
|
||||
Loading…
Add table
Add a link
Reference in a new issue