UNPKG

smart-idle

Version:

Lightweight browser library to detect user inactivity with event dispatching

116 lines (114 loc) 3.03 kB
"use strict"; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/SmartIdle.ts var SmartIdle_exports = {}; __export(SmartIdle_exports, { SmartIdle: () => SmartIdle }); module.exports = __toCommonJS(SmartIdle_exports); var SmartIdle = class { constructor(options = {}) { this._timer = null; this._idle = false; this._paused = false; this._events = []; this.timeout = options.timeout || 6e4; this.onIdle = options.onIdle || (() => { }); this.onActive = options.onActive || (() => { }); this._events = options.events || [ "mousemove", "keydown", "scroll", "touchstart", "visibilitychange" ]; this._handleEvent = this._handleEvent.bind(this); } start() { this._events.forEach((e) => window.addEventListener(e, this._handleEvent)); this._resetTimer(); } stop() { this._events.forEach((e) => window.removeEventListener(e, this._handleEvent)); if (this._timer) clearTimeout(this._timer); } pause() { this._paused = true; if (this._timer) clearTimeout(this._timer); } resume() { if (!this._paused) return; this._paused = false; this._resetTimer(); } isIdle() { return this._idle; } triggerIdle() { if (!this._idle) { this._idle = true; this.onIdle(); window.dispatchEvent(new CustomEvent("idle")); } } triggerActive() { if (this._idle) { this._idle = false; this.onActive(); window.dispatchEvent(new CustomEvent("active")); this._resetTimer(); } } destroy() { this.stop(); this._idle = false; this._paused = false; this._timer = null; } _handleEvent() { if (this._paused) return; if (this._idle) { this._idle = false; this.onActive(); window.dispatchEvent(new CustomEvent("active")); } this._resetTimer(); } _resetTimer() { if (this._timer) clearTimeout(this._timer); if (this._paused || document.hidden) return; this._timer = setTimeout(() => { this._idle = true; this.onIdle(); window.dispatchEvent(new CustomEvent("idle")); }, this.timeout); } }; // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { SmartIdle });