Hook that fires a handler on rapid window click streaks
A support tool opens a hidden debug panel when someone clicks three times quickly anywhere on the page. A game counts rapid taps to trigger a combo. Both need to watch every click in the window, even clicks on buttons that stop propagation, and decide whether the clicks were fast enough to count as one streak. Implement a React hook, useClickStreak, that calls a handler when the user clicks a number of times in quick succession anywhere in the window.
function useClickStreak(
onStreak: (event: MouseEvent) => void,
options?: { clicks?: number; within?: number; enabled?: boolean },
): void
options.clicks: how many clicks make a streak. Defaults to 3.options.within: the maximum gap, in milliseconds, between one click and the next for them to belong to the same streak. Defaults to 400.options.enabled: defaults to true.click on window in the capture phase, so clicks still count when an element calls event.stopPropagation(). Add exactly one listener.event.button === 0) count. Other clicks are ignored completely: they neither count nor break a streak.Date.now(). A click that comes at most within ms after the previous counted click continues the streak. A click that comes later starts a new streak, and counts as its first click.clicks clicks, call onStreak(event) with the click that completed it, then start over: the next click is the first click of a new streak. Six quick clicks with clicks: 3 call onStreak twice.onStreak. Callers pass an inline handler and an inline options object, so both are new on every render. Neither may remove and re-add the listener.clicks or within values apply from the next click.enabled is false, no listener is attached and no clicks are counted. On unmount, remove the listener.function DebugPanelTrigger() {
const [open, setOpen] = useState(false);
useClickStreak(() => setOpen(true), { clicks: 3, within: 400 });
return open ? <DebugPanel /> : null;
}
// clicks: 3, within: 400 (times from Date.now())
// clicks at 0, 150, 300 -> onStreak once (at 300)
// clicks at 0, 500, 1000 -> nothing: each gap is over 400 ms
// clicks at 0, 400, 800 -> onStreak once: a gap of exactly 400 ms still counts
// clicks at 0, 100, 700, 800, 900 -> onStreak once (at 900): the click at 700 started a new streak
// right-click at 50 between left clicks at 0, 100, 200 -> onStreak once: the right-click is ignored
Date.now with a fake clock, and dispatches click MouseEvents on elements in the page.click listeners added to and removed from window. Re-renders happen inside ReactDOM.flushSync.Object.assign(window, { useClickStreak }); below “Do not edit below this line”. The tests use it to call your hook.