connection.tsx
1.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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);
}