"use client"; import { useEffect, useRef, useState } from "react"; export type StreamEvent = { id?: string; ts?: number; kind?: string; message?: string; anchor_name?: string; room_id?: string; session_id?: string; meta?: Record; }; export type RefreshOpts = { silent?: boolean }; /** One shared EventSource for the whole tab — avoids N sockets from Shell/home/alerts. */ type SharedBus = { es: EventSource | null; refs: number; connected: boolean; last: StreamEvent | null; tick: number; retryTimer: number; listeners: Set<() => void>; }; const bus: SharedBus = { es: null, refs: 0, connected: false, last: null, tick: 0, retryTimer: 0, listeners: new Set(), }; function notifyBus() { for (const fn of bus.listeners) fn(); } function openSharedStream() { if (bus.es) return; const es = new EventSource("/api/events/stream"); bus.es = es; es.onopen = () => { bus.connected = true; notifyBus(); }; es.onerror = () => { bus.connected = false; es.close(); bus.es = null; notifyBus(); if (bus.refs > 0 && !bus.retryTimer) { bus.retryTimer = window.setTimeout(() => { bus.retryTimer = 0; if (bus.refs > 0) openSharedStream(); }, 2500); } }; es.onmessage = (msg) => { try { bus.last = JSON.parse(msg.data) as StreamEvent; bus.tick += 1; notifyBus(); } catch { /* ignore */ } }; } function releaseSharedStream() { bus.refs = Math.max(0, bus.refs - 1); if (bus.refs > 0) return; window.clearTimeout(bus.retryTimer); bus.retryTimer = 0; bus.es?.close(); bus.es = null; bus.connected = false; } export function useEventStream(enabled = true) { const [connected, setConnected] = useState(bus.connected); const [last, setLast] = useState(bus.last); const [tick, setTick] = useState(bus.tick); const enabledRef = useRef(enabled); enabledRef.current = enabled; useEffect(() => { if (!enabled) return; bus.refs += 1; openSharedStream(); const onChange = () => { setConnected(bus.connected); setLast(bus.last); setTick(bus.tick); }; bus.listeners.add(onChange); onChange(); return () => { bus.listeners.delete(onChange); releaseSharedStream(); }; }, [enabled]); return { connected, last, tick }; } /** * 定时静默刷新 + 开播/下播等 SSE 事件立即刷新。 * load 需支持 opts.silent,后台刷新时不要闪 loading / 清空勾选。 */ export function useAutoRefresh( load: (opts?: RefreshOpts) => void | Promise, opts?: { intervalMs?: number; /** false = 仅轮询;默认 live/offline/risk */ eventKinds?: string[] | false; /** false = 暂停自动刷新(仍遵守 hook 规则) */ enabled?: boolean; }, ) { const intervalMs = opts?.intervalMs ?? 20000; const enabled = opts?.enabled !== false; const eventKinds = opts?.eventKinds === false ? null : opts?.eventKinds ?? ["live", "offline", "risk"]; const { connected, last, tick } = useEventStream(Boolean(eventKinds) && enabled); const loadRef = useRef(load); loadRef.current = load; useEffect(() => { if (!enabled) return; void loadRef.current({ silent: false }); if (!intervalMs || intervalMs <= 0) return; const tickSilent = () => { if (typeof document !== "undefined" && document.hidden) return; void loadRef.current({ silent: true }); }; const t = window.setInterval(tickSilent, intervalMs); const onVis = () => { if (!document.hidden) void loadRef.current({ silent: true }); }; document.addEventListener("visibilitychange", onVis); return () => { window.clearInterval(t); document.removeEventListener("visibilitychange", onVis); }; }, [load, intervalMs, enabled]); useEffect(() => { if (!enabled || !eventKinds || !last?.kind) return; if (!eventKinds.includes(String(last.kind))) return; if (typeof document !== "undefined" && document.hidden) return; void loadRef.current({ silent: true }); // eslint-disable-next-line react-hooks/exhaustive-deps }, [tick, enabled]); return { connected }; } export function useNow(intervalMs = 1000) { const [now, setNow] = useState(() => Date.now()); useEffect(() => { const t = setInterval(() => setNow(Date.now()), intervalMs); return () => clearInterval(t); }, [intervalMs]); return now; } export function liveElapsed(startedAt?: number, nowMs?: number) { if (!startedAt) return "—"; const now = (nowMs || Date.now()) / 1000; const total = Math.max(0, Math.floor(now - startedAt)); const h = Math.floor(total / 3600); const m = Math.floor((total % 3600) / 60); const s = total % 60; if (h > 0) return `${h}:${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}`; return `${m}:${String(s).padStart(2, "0")}`; }