统一全系统资源加载、轻量趋势与缓存恢复
This commit is contained in:
@@ -0,0 +1,30 @@
|
||||
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 <T,>(work: () => Promise<T>): Promise<T> => {
|
||||
setPendingCount(count => count + 1);
|
||||
try { return await work(); }
|
||||
finally { if (mounted.current) setPendingCount(count => Math.max(0, count - 1)); }
|
||||
}, []);
|
||||
return { busy, run };
|
||||
}
|
||||
Reference in New Issue
Block a user