import { useCallback, useEffect, useRef } from 'react'; /** Background poll interval while the tab is visible. */ export const SILENT_POLL_MS = 5000; /** Relaxed poll for views whose refresh pulls many tables at once. */ export const SLOW_POLL_MS = 15000; /** How long after a write we wait before pulling fresh data (batches bursts). */ export const WRITE_SETTLE_MS = 500; /** * Silent background refresh for admin data. * * Two triggers, both deliberately invisible: * 1. a poll every `SILENT_POLL_MS` while the tab is visible (paused when * hidden, and refreshed the moment it becomes visible again), so the table * shows staff scans performed on another device; * 2. `refreshSoon()`, a debounced pull `WRITE_SETTLE_MS` after a write, which * lets a burst of edits settle on the server before we read it back. * * "Silent" is the contract, and it has teeth: * - the interval never fires on mount — the view's own `load()` owns the first * fetch and the loading state; * - errors are swallowed. A background tick must not write the view's `error` * state, because these views render `if (error) return ` and a * single failed poll would replace a perfectly good table with an error * screen; * - overlapping ticks are dropped rather than queued (`inflight`), so a slow * response can never pile up behind a fast one; * - the callback is read from a ref, so an inline `() => load(...)` does not * reschedule the timer on every render. * * Callers must supply a refresh that patches data in place: no `setLoaded(false)`, * no re-sort that moves rows under the cursor. See Registrations, which keeps the * existing row order and skips rows with a write in flight. * * `intervalMs` relaxes the poll for views whose refresh is expensive (Reports * pulls nine tables at once). The 500 ms-after-write path is unaffected. */ export function useSilentRefresh( refresh: () => Promise | void, options: { enabled?: boolean; refresher?: () => Promise | void; intervalMs?: number } = {}, ): { refreshSoon: () => void } { const { enabled = true, intervalMs = SILENT_POLL_MS } = options; const tick = options.refresher ?? refresh; const saved = useRef(tick); saved.current = tick; const inflight = useRef(false); const timer = useRef(null); const run = useCallback(async () => { if (inflight.current) return; inflight.current = true; try { await saved.current(); } catch { // Silent by design — see the doc comment. } finally { inflight.current = false; } }, []); useEffect(() => { if (!enabled) return; const visible = () => typeof document === 'undefined' || document.visibilityState === 'visible'; const id = window.setInterval(() => { if (visible()) void run(); }, intervalMs); const onVisible = () => { if (visible()) void run(); }; document.addEventListener('visibilitychange', onVisible); return () => { window.clearInterval(id); document.removeEventListener('visibilitychange', onVisible); }; }, [enabled, intervalMs, run]); useEffect(() => () => { if (timer.current !== null) window.clearTimeout(timer.current); }, []); /** Schedule one debounced pull; repeated calls within the window collapse. */ const refreshSoon = useCallback(() => { if (timer.current !== null) window.clearTimeout(timer.current); timer.current = window.setTimeout(() => { timer.current = null; void run(); }, WRITE_SETTLE_MS); }, [run]); return { refreshSoon }; }