- Fix useRealtimeSync never receiving WSClient (useRef → useState for re-render trigger, keeping ref for lazy subscribe callback) - Fix Hub.Run() global broadcast mutating map under RLock (same two-phase collect+cleanup pattern as BroadcastToWorkspace) - Move visibleStatuses to module-level constant (prevent useCallback recreation every render) - Replace console.error with toast.error for user-facing operations in issues page and inbox page Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
76 lines
1.9 KiB
TypeScript
76 lines
1.9 KiB
TypeScript
"use client";
|
|
|
|
import {
|
|
createContext,
|
|
useContext,
|
|
useEffect,
|
|
useState,
|
|
useRef,
|
|
useCallback,
|
|
type ReactNode,
|
|
} from "react";
|
|
import { WSClient } from "@multica/sdk";
|
|
import type { WSEventType } from "@multica/types";
|
|
import { useAuthStore } from "@/features/auth";
|
|
import { useWorkspaceStore } from "@/features/workspace";
|
|
import { useRealtimeSync } from "./use-realtime-sync";
|
|
|
|
const WS_URL = process.env.NEXT_PUBLIC_WS_URL ?? "ws://localhost:8080/ws";
|
|
|
|
type EventHandler = (payload: unknown) => void;
|
|
|
|
interface WSContextValue {
|
|
subscribe: (event: WSEventType, handler: EventHandler) => () => void;
|
|
}
|
|
|
|
const WSContext = createContext<WSContextValue | null>(null);
|
|
|
|
export function WSProvider({ children }: { children: ReactNode }) {
|
|
const user = useAuthStore((s) => s.user);
|
|
const workspace = useWorkspaceStore((s) => s.workspace);
|
|
const [wsClient, setWsClient] = useState<WSClient | null>(null);
|
|
const wsRef = useRef<WSClient | null>(null);
|
|
|
|
useEffect(() => {
|
|
if (!user || !workspace) return;
|
|
|
|
const token = localStorage.getItem("multica_token");
|
|
if (!token) return;
|
|
|
|
const ws = new WSClient(WS_URL);
|
|
ws.setAuth(token, workspace.id);
|
|
wsRef.current = ws;
|
|
setWsClient(ws);
|
|
ws.connect();
|
|
|
|
return () => {
|
|
ws.disconnect();
|
|
wsRef.current = null;
|
|
setWsClient(null);
|
|
};
|
|
}, [user, workspace]);
|
|
|
|
// Centralized WS → store sync (uses state so it re-subscribes when WS changes)
|
|
useRealtimeSync(wsClient);
|
|
|
|
const subscribe = useCallback(
|
|
(event: WSEventType, handler: EventHandler) => {
|
|
const ws = wsRef.current;
|
|
if (!ws) return () => {};
|
|
return ws.on(event, handler);
|
|
},
|
|
[],
|
|
);
|
|
|
|
return (
|
|
<WSContext.Provider value={{ subscribe }}>
|
|
{children}
|
|
</WSContext.Provider>
|
|
);
|
|
}
|
|
|
|
export function useWS() {
|
|
const ctx = useContext(WSContext);
|
|
if (!ctx) throw new Error("useWS must be used within WSProvider");
|
|
return ctx;
|
|
}
|