'use strict'; var solidJs = require('solid-js'); var web = require('solid-js/web'); // src/createIdleTimer.ts var THROTTLE_DELAY = 250; var FIFTEEN_MINUTES = 9e5; var EVENTS = [ "mousemove", "keydown", "wheel", "resize", "wheel", "mousedown", "pointerdown", "touchstart", "touchmove", "visibilitychange" ]; exports.createIdleTimer = ({ element, events = EVENTS, idleTimeout = FIFTEEN_MINUTES, promptTimeout = 0, onActive, onIdle, onPrompt, startManually = false } = {}) => { if (web.isServer) { return { isIdle: () => false, isPrompted: () => false, reset: () => { }, start: () => { }, stop: () => { }, triggerIdle: () => { } }; } let listenersAreOn = false; const [isPrompted, setIsPrompted] = solidJs.createSignal(false); const [isIdle, setIsIdle] = solidJs.createSignal(false); let idle; let prompt; let lastThrottle = 0; function shouldPreventRunning() { const now = (/* @__PURE__ */ new Date()).getTime(); const shouldPrevent = now - lastThrottle < THROTTLE_DELAY; if (!shouldPrevent) lastThrottle = now; return shouldPrevent; } function handleEvent(evt) { if (shouldPreventRunning()) return; if (isIdle()) onActive?.(evt); if (!isPrompted()) timerReset(evt); } function addListeners() { if (listenersAreOn) return; const target = element ?? document; for (const evt of events) { target.addEventListener(evt, handleEvent); } listenersAreOn = true; } function timerReset(evt) { if (!listenersAreOn) return; timerCleanup(); cleanState(); setIdleTimer(evt); } function timerCleanup() { if (typeof idle === "number") clearTimeout(idle); if (typeof prompt === "number") clearTimeout(prompt); } function setIdleTimer(evt) { idle = setTimeout(() => { setIsPrompted(true); onPrompt?.(evt); setPromptTimer(evt); }, idleTimeout); } function setPromptTimer(evt) { prompt = setTimeout(() => { solidJs.batch(() => { setIsIdle(true); setIsPrompted(false); }); onIdle?.(evt); }, promptTimeout); } function cleanState() { solidJs.batch(() => { setIsIdle(false); setIsPrompted(false); }); } function startListening(evt = new CustomEvent("manualstart")) { timerCleanup(); cleanState(); addListeners(); timerReset(evt); } function stopListening() { timerCleanup(); cleanState(); removeListeners(); } function removeListeners() { if (!listenersAreOn) return; const target = element ?? document; for (const evt of events) { target.removeEventListener(evt, handleEvent); } listenersAreOn = false; } function triggerIdle() { stopListening(); setIsIdle(true); onIdle?.(new CustomEvent("manualidle")); addListeners(); } solidJs.onMount(() => { if (startManually) return; startListening(new CustomEvent("mount")); }); solidJs.onCleanup(stopListening); return { isIdle, isPrompted, start: () => startListening(), reset: () => timerReset(new CustomEvent("manualreset")), stop: stopListening, triggerIdle }; };