| 9 | |
| 10 | /** Read-only polling. Each lifecycle owns its responses; hidden views never commit them. */ |
| 11 | export function useSystemPoll<T>(read: () => Promise<T>, active: boolean, paused: boolean, intervalMs: number) { |
| 12 | const empty: SystemReading<T> = { data: null, updatedAt: null, error: null, loading: false }; |
| 13 | const [owned, setOwned] = useState({ owner: read, reading: empty }); |
| 14 | const refreshRef = useRef<() => void>(() => {}); |
| 15 | |
| 16 | useEffect(() => { |
| 17 | const setReading = (update: SystemReading<T> | ((previous: SystemReading<T>) => SystemReading<T>)) => { |
| 18 | setOwned(previous => { |
| 19 | const current = previous.owner === read ? previous.reading : { data: null, updatedAt: null, error: null, loading: false }; |
| 20 | return { owner: read, reading: typeof update === 'function' ? update(current) : update }; |
| 21 | }); |
| 22 | }; |
| 23 | let disposed = false; |
| 24 | let generation = 0; |
| 25 | let timer: ReturnType<typeof setTimeout> | undefined; |
| 26 | let inFlight = false; |
| 27 | const visible = () => active && document.visibilityState !== 'hidden'; |
| 28 | const invalidate = () => { |
| 29 | generation += 1; |
| 30 | inFlight = false; |
| 31 | clearTimeout(timer); |
| 32 | }; |
| 33 | const poll = async () => { |
| 34 | if (disposed || !visible() || inFlight) return; |
| 35 | clearTimeout(timer); |
| 36 | const ticket = generation; |
| 37 | inFlight = true; |
| 38 | setReading((previous) => ({ ...previous, loading: true })); |
| 39 | try { |
| 40 | const data = await read(); |
| 41 | if (!disposed && ticket === generation && visible()) { |
| 42 | setReading({ data, updatedAt: Date.now(), error: null, loading: false }); |
| 43 | } |
| 44 | } catch (error) { |
| 45 | if (!disposed && ticket === generation && visible()) { |
| 46 | setReading((previous) => ({ ...previous, error: error instanceof Error ? error.message : String(error), loading: false })); |
| 47 | } |
| 48 | } finally { |
| 49 | if (!disposed && ticket === generation) { |
| 50 | inFlight = false; |
| 51 | if (visible() && !paused) timer = setTimeout(() => { void poll(); }, intervalMs); |
| 52 | } |
| 53 | } |
| 54 | }; |
| 55 | const visibilityChanged = () => { |
| 56 | invalidate(); |
| 57 | setReading((previous) => ({ ...previous, loading: false })); |
| 58 | if (visible() && !paused) void poll(); |
| 59 | }; |
| 60 | refreshRef.current = () => { void poll(); }; |
| 61 | document.addEventListener('visibilitychange', visibilityChanged); |
| 62 | if (visible() && !paused) void poll(); |
| 63 | else setReading((previous) => ({ ...previous, loading: false })); |
| 64 | return () => { |
| 65 | disposed = true; |
| 66 | invalidate(); |
| 67 | refreshRef.current = () => {}; |
| 68 | document.removeEventListener('visibilitychange', visibilityChanged); |