Derive active, idle, or away status from user activity
A team chat app shows a green dot next to people who are using the app, a yellow dot when they have stepped away for a moment, and a grey dot when they have been gone for a while. The client decides which one to report from the user’s own mouse, keyboard and touch activity. Implement a React hook, usePresenceStatus, that turns that activity into a status.
function usePresenceStatus(idleAfter: number, awayAfter: number): 'active' | 'idle' | 'away'
idleAfter: milliseconds without activity before the status becomes 'idle'.awayAfter: milliseconds without activity before the status becomes 'away'. You can assume awayAfter > idleAfter > 0, and that neither argument changes while the component is mounted.'active' on mount, and the clock starts at mount.idleAfter ms pass with no activity, return 'idle'. Once awayAfter ms pass with no activity, return 'away'. Both are measured from the last activity (or mount).mousemove, mousedown, keydown, touchstart, wheel, scroll. Any activity sets the status back to 'active' and restarts both countdowns.window in the capture phase, so activity is still seen when page code calls event.stopPropagation().'active' (for example, a stream of mousemove events) must not re-render the component.setTimeout) so the status changes exactly when the time is up. Do not poll.const status = usePresenceStatus(5000, 20000);
// t = 0 mount -> 'active'
// t = 5000 no activity -> 'idle'
// t = 7000 mouse moves -> 'active' (countdowns restart)
// t = 12000 no activity since 7000 -> 'idle'
// t = 27000 no activity since 7000 -> 'away'
// t = 30000 key pressed -> 'active'
setTimeout, clearTimeout, setInterval, clearInterval, Date.now and performance.now with a fake clock and move it forward by exact amounts (for example, 4999 ms, then 1 ms).document.body or one of its children. Some tests count the listeners added to window and document, the pending timers, or the number of renders.Object.assign(window, { usePresenceStatus }); below “Do not edit below this line”. The tests use it to call your hook.