import { useCallback, useEffect, useRef, useState } from 'react'; /** Shows a loading indicator only when the request has lasted beyond the delay. */ export function useDelayedIndicator(active: boolean, delayMs = 150): boolean { const [visible, setVisible] = useState(false); useEffect(() => { if (!active) { setVisible(false); return; } setVisible(false); const timer = window.setTimeout(() => setVisible(true), delayMs); return () => window.clearTimeout(timer); }, [active, delayMs]); return active && visible; } /** Wraps reads with a delayed, concurrency-safe busy indicator. */ export function useDelayedBusy(delayMs = 150) { const [pendingCount, setPendingCount] = useState(0); const busy = useDelayedIndicator(pendingCount > 0, delayMs); const mounted = useRef(false); useEffect(() => { mounted.current = true; return () => { mounted.current = false; }; }, []); const run = useCallback(async (work: () => Promise): Promise => { setPendingCount(count => count + 1); try { return await work(); } finally { if (mounted.current) setPendingCount(count => Math.max(0, count - 1)); } }, []); return { busy, run }; }