multica/apps/web/features/realtime/provider.tsx
Naiyuan Qing a2d7501d57 refactor(web): restructure to feature-based architecture with zustand stores
- Remove tab system entirely (tab-store, tab-bar, tab-link)
- Split monolithic AuthContext into zustand auth + workspace stores
- Move issue components/config to features/issues/
- Move WebSocket provider to features/realtime/
- Move api.ts to shared/
- Migrate all consumers from useAuth() to direct store imports
- Simplify sidebar: replace hand-built dropdown with shadcn DropdownMenu,
  replace custom layout wrapper with SidebarInset
- Remove unused @multica/store and @multica/hooks dependencies
- Add @/ path alias and zustand dependency
- Update CLAUDE.md with feature-based architecture conventions

Net change: +293 / -2435 lines

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-24 16:08:36 +08:00

62 lines
1.4 KiB
TypeScript

"use client";
import {
createContext,
useContext,
useEffect,
useRef,
useCallback,
type ReactNode,
} from "react";
import { WSClient } from "@multica/sdk";
import type { WSEventType } from "@multica/types";
import { useAuthStore } from "@/features/auth";
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 wsRef = useRef<WSClient | null>(null);
useEffect(() => {
if (!user) return;
const ws = new WSClient(WS_URL);
wsRef.current = ws;
ws.connect();
return () => {
ws.disconnect();
wsRef.current = null;
};
}, [user]);
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;
}