connection.tsx
1.51 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
55
56
57
58
59
60
61
62
63
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);
}