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
35
apps/web/src/lib/ws-hooks.ts
Normal file
35
apps/web/src/lib/ws-hooks.ts
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
import { useContext } from "react";
|
||||
import { WsContext } from "./ws-context.js";
|
||||
import type { WsClient } from "./ws-client.js";
|
||||
|
||||
export const useWsClient = (): WsClient => {
|
||||
const ctx = useContext(WsContext);
|
||||
if (!ctx) {
|
||||
throw new Error("useWsClient must be used within a WsProvider");
|
||||
}
|
||||
return ctx.client;
|
||||
};
|
||||
|
||||
export const useWsConnected = (): boolean => {
|
||||
const ctx = useContext(WsContext);
|
||||
if (!ctx) {
|
||||
throw new Error("useWsConnected must be used within a WsProvider");
|
||||
}
|
||||
return ctx.isConnected;
|
||||
};
|
||||
|
||||
export const useWsConnect = (): ((url: string) => Promise<void>) => {
|
||||
const ctx = useContext(WsContext);
|
||||
if (!ctx) {
|
||||
throw new Error("useWsConnect must be used within a WsProvider");
|
||||
}
|
||||
return ctx.connect;
|
||||
};
|
||||
|
||||
export const useWsDisconnect = (): (() => void) => {
|
||||
const ctx = useContext(WsContext);
|
||||
if (!ctx) {
|
||||
throw new Error("useWsDisconnect must be used within a WsProvider");
|
||||
}
|
||||
return ctx.disconnect;
|
||||
};
|
||||
Loading…
Add table
Add a link
Reference in a new issue