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

interface ConnectionContextValue {
  connected: boolean;
  lastEventAt: number | null;
}

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

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

  useEffect(() => {
    aliveRef.current = true;
    const unsub = subscribeSSE(
      () => {
        if (!aliveRef.current) return;
        setConnected(true);
        setLastEventAt(Date.now());
      },
      () => {
        if (!aliveRef.current) return;
        setConnected(false);
      },
    );
    // SSE 打开即视为已连接(即使尚未收到业务事件)
    const t = window.setTimeout(() => {
      if (aliveRef.current) setConnected(true);
    }, 800);
    return () => {
      aliveRef.current = false;
      window.clearTimeout(t);
      unsub();
    };
  }, []);

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

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