connection.tsx 1.15 KB
import {
  createContext,
  useContext,
  useEffect,
  useRef,
  useState,
  type ReactNode,
} from 'react';
import { onSSEStatus } from './api';

interface ConnectionContextValue {
  connected: boolean;
}

const ConnectionContext = createContext<ConnectionContextValue>({
  connected: false,
});

/**
 * 全局 SSE 连接监控:订阅一次后端事件流,向整个应用提供「已连接」状态,
 * 用于顶栏的实时连接脉冲指示。
 */
export function ConnectionProvider({ children }: { children: ReactNode }) {
  const [connected, setConnected] = useState(false);
  const aliveRef = useRef(true);

  useEffect(() => {
    aliveRef.current = true;
    const unsub = onSSEStatus(
      () => {
        if (!aliveRef.current) return;
        setConnected(true);
      },
      () => {
        if (!aliveRef.current) return;
        setConnected(false);
      },
    );
    return () => {
      aliveRef.current = false;
      unsub();
    };
  }, []);

  return (
    <ConnectionContext.Provider value={{ connected }}>
      {children}
    </ConnectionContext.Provider>
  );
}

export function useConnection() {
  return useContext(ConnectionContext);
}