puck / frontend /src /lib /useIdle.ts
vu1n's picture
Puck — desktop fairy familiar (HF Build Small)
3c124f3
Raw
History Blame Contribute Delete
1.04 kB
import * as React from "react";
// Idle detection — the gate that makes cloud vision affordable. When the user
// is away (no input for `thresholdMs`) or the tab is hidden, ambient vision
// pauses so the Modal GPU scales to zero and bills nothing.
export function useIdle(thresholdMs = 150_000): boolean {
const [idle, setIdle] = React.useState(false);
const last = React.useRef(Date.now());
React.useEffect(() => {
const bump = () => {
last.current = Date.now();
setIdle(false); // wake immediately on activity (React bails if already false)
};
const events = ["mousemove", "mousedown", "keydown", "wheel", "touchstart"] as const;
for (const e of events) window.addEventListener(e, bump, { passive: true });
const tick = setInterval(() => {
setIdle(document.hidden || Date.now() - last.current > thresholdMs);
}, 5000);
return () => {
for (const e of events) window.removeEventListener(e, bump);
clearInterval(tick);
};
}, [thresholdMs]);
return idle;
}