统一全系统资源加载、轻量趋势与缓存恢复

This commit is contained in:
2026-11-02 09:54:01 +08:00
parent 8b8f9b7728
commit b711327c8e
58 changed files with 3150 additions and 661 deletions
+76
View File
@@ -0,0 +1,76 @@
export type PollScheduler = {
setTimeout: (callback: () => void, delayMs: number) => unknown;
clearTimeout: (handle: unknown) => void;
};
export type VisiblePollingController = {
start: (visible: boolean, runImmediately?: boolean) => void;
setVisible: (visible: boolean) => void;
stop: () => void;
};
/** Runs one request at a time and starts the next delay only after it settles. */
export function createVisiblePollingController(
callback: () => void | Promise<void>,
intervalMs: number,
scheduler: PollScheduler = {
setTimeout: (run, delay) => window.setTimeout(run, delay),
clearTimeout: handle => window.clearTimeout(handle as number),
},
): VisiblePollingController {
let enabled = false;
let visible = false;
let inFlight = false;
let runImmediatelyAfterFlight = false;
let timer: unknown = null;
const clear = () => {
if (timer !== null) scheduler.clearTimeout(timer);
timer = null;
};
const schedule = () => {
if (!enabled || !visible || inFlight || timer !== null) return;
timer = scheduler.setTimeout(() => {
timer = null;
void run();
}, intervalMs);
};
const run = async () => {
if (!enabled || !visible) return;
if (inFlight) {
runImmediatelyAfterFlight = true;
return;
}
clear();
inFlight = true;
try { await callback(); } catch { /* Polling errors are rendered by the caller. */ }
finally {
inFlight = false;
if (!enabled || !visible) return;
if (runImmediatelyAfterFlight) {
runImmediatelyAfterFlight = false;
void run();
} else schedule();
}
};
return {
start(nextVisible, runImmediately = false) {
enabled = true;
visible = nextVisible;
if (visible) runImmediately ? void run() : schedule();
},
setVisible(nextVisible) {
if (visible === nextVisible) return;
visible = nextVisible;
if (!enabled) return;
if (!visible) clear();
else void run();
},
stop() {
enabled = false;
runImmediatelyAfterFlight = false;
clear();
},
};
}