@afex-dapps/idle-timer
Version:
Idle Timer library for detecting user inactivity and managing session timeouts
777 lines (754 loc) • 35.1 kB
JavaScript
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var __defProp = Object.defineProperty;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b2) => {
for (var prop in b2 || (b2 = {}))
if (__hasOwnProp.call(b2, prop))
__defNormalProp(a, prop, b2[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b2)) {
if (__propIsEnum.call(b2, prop))
__defNormalProp(a, prop, b2[prop]);
}
return a;
};
var __objRest = (source, exclude) => {
var target = {};
for (var prop in source)
if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
target[prop] = source[prop];
if (source != null && __getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(source)) {
if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
target[prop] = source[prop];
}
return target;
};
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
var __async = (__this, __arguments, generator) => {
return new Promise((resolve, reject) => {
var fulfilled = (value) => {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
};
var rejected = (value) => {
try {
step(generator.throw(value));
} catch (e) {
reject(e);
}
};
var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
step((generator = generator.apply(__this, __arguments)).next());
});
};
// src/hooks/use-idle-timeout.ts
var _react = require('react');
// ../../node_modules/.pnpm/react-idle-timer@5.7.2_react-dom@19.1.0_react@19.1.0__react@19.1.0/node_modules/react-idle-timer/dist/index.esm.js
var _jsxruntime = require('react/jsx-runtime');
var Et = Object.create;
var Ye = Object.defineProperty;
var bt = Object.getOwnPropertyDescriptor;
var gt = Object.getOwnPropertyNames;
var yt = Object.getPrototypeOf;
var wt = Object.prototype.hasOwnProperty;
var Lt = (n, e) => () => (e || n((e = { exports: {} }).exports, e), e.exports);
var Pt = (n, e, r, i) => {
if (e && typeof e == "object" || typeof e == "function") for (let o of gt(e)) !wt.call(n, o) && o !== r && Ye(n, o, { get: () => e[o], enumerable: !(i = bt(e, o)) || i.enumerable });
return n;
};
var St = (n, e, r) => (r = n != null ? Et(yt(n)) : {}, Pt(e || !n || !n.__esModule ? Ye(r, "default", { value: n, enumerable: true }) : r, n));
var je = Lt((he, Je) => {
(function(n, e) {
typeof he == "object" && typeof Je < "u" ? e(he) : typeof define == "function" && define.amd ? define(["exports"], e) : (n = typeof globalThis < "u" ? globalThis : n || self, e(n.fastUniqueNumbers = {}));
})(he, function(n) {
"use strict";
var e = function(l) {
return function(p) {
var f = l(p);
return p.add(f), f;
};
}, r = function(l) {
return function(p, f) {
return l.set(p, f), f;
};
}, i = Number.MAX_SAFE_INTEGER === void 0 ? 9007199254740991 : Number.MAX_SAFE_INTEGER, o = 536870912, u = o * 2, g = function(l, p) {
return function(f) {
var B = p.get(f), y = B === void 0 ? f.size : B < u ? B + 1 : 0;
if (!f.has(y)) return l(f, y);
if (f.size < o) {
for (; f.has(y); ) y = Math.floor(Math.random() * u);
return l(f, y);
}
if (f.size > i) throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");
for (; f.has(y); ) y = Math.floor(Math.random() * i);
return l(f, y);
};
}, O = /* @__PURE__ */ new WeakMap(), W = r(O), m = g(W, O), a = e(m);
n.addUniqueNumber = a, n.generateUniqueNumber = m;
});
});
var oe = St(je());
var Xe = (n) => n.method !== void 0 && n.method === "call";
var ze = (n) => n.error === null && typeof n.id == "number";
var Ke = (n) => {
let e = /* @__PURE__ */ new Map([[0, () => {
}]]), r = /* @__PURE__ */ new Map([[0, () => {
}]]), i = /* @__PURE__ */ new Map(), o = new Worker(n);
return o.addEventListener("message", ({ data: m }) => {
if (Xe(m)) {
let { params: { timerId: a, timerType: d } } = m;
if (d === "interval") {
let l = e.get(a);
if (typeof l == "number") {
let p = i.get(l);
if (p === void 0 || p.timerId !== a || p.timerType !== d) throw new Error("The timer is in an undefined state.");
} else if (typeof l < "u") l();
else throw new Error("The timer is in an undefined state.");
} else if (d === "timeout") {
let l = r.get(a);
if (typeof l == "number") {
let p = i.get(l);
if (p === void 0 || p.timerId !== a || p.timerType !== d) throw new Error("The timer is in an undefined state.");
} else if (typeof l < "u") l(), r.delete(a);
else throw new Error("The timer is in an undefined state.");
}
} else if (ze(m)) {
let { id: a } = m, d = i.get(a);
if (d === void 0) throw new Error("The timer is in an undefined state.");
let { timerId: l, timerType: p } = d;
i.delete(a), p === "interval" ? e.delete(l) : r.delete(l);
} else {
let { error: { message: a } } = m;
throw new Error(a);
}
}), { clearInterval: (m) => {
let a = (0, oe.generateUniqueNumber)(i);
i.set(a, { timerId: m, timerType: "interval" }), e.set(m, a), o.postMessage({ id: a, method: "clear", params: { timerId: m, timerType: "interval" } });
}, clearTimeout: (m) => {
let a = (0, oe.generateUniqueNumber)(i);
i.set(a, { timerId: m, timerType: "timeout" }), r.set(m, a), o.postMessage({ id: a, method: "clear", params: { timerId: m, timerType: "timeout" } });
}, setInterval: (m, a) => {
let d = (0, oe.generateUniqueNumber)(e);
return e.set(d, () => {
m(), typeof e.get(d) == "function" && o.postMessage({ id: null, method: "set", params: { delay: a, now: performance.now(), timerId: d, timerType: "interval" } });
}), o.postMessage({ id: null, method: "set", params: { delay: a, now: performance.now(), timerId: d, timerType: "interval" } }), d;
}, setTimeout: (m, a) => {
let d = (0, oe.generateUniqueNumber)(r);
return r.set(d, m), o.postMessage({ id: null, method: "set", params: { delay: a, now: performance.now(), timerId: d, timerType: "timeout" } }), d;
} };
};
var Qe = (n, e) => {
let r = null;
return () => {
if (r !== null) return r;
let i = new Blob([e], { type: "application/javascript; charset=utf-8" }), o = URL.createObjectURL(i);
return r = n(o), setTimeout(() => URL.revokeObjectURL(o)), r;
};
};
var Ze = `(()=>{"use strict";const e=new Map,t=new Map,r=(e,t)=>{let r,o;const i=performance.now();r=i,o=e-Math.max(0,i-t);return{expected:r+o,remainingDelay:o}},o=(e,t,r,i)=>{const s=performance.now();s>r?postMessage({id:null,method:"call",params:{timerId:t,timerType:i}}):e.set(t,setTimeout(o,r-s,e,t,r,i))};addEventListener("message",(i=>{let{data:s}=i;try{if("clear"===s.method){const{id:r,params:{timerId:o,timerType:i}}=s;if("interval"===i)(t=>{const r=e.get(t);if(void 0===r)throw new Error('There is no interval scheduled with the given id "'.concat(t,'".'));clearTimeout(r),e.delete(t)})(o),postMessage({error:null,id:r});else{if("timeout"!==i)throw new Error('The given type "'.concat(i,'" is not supported'));(e=>{const r=t.get(e);if(void 0===r)throw new Error('There is no timeout scheduled with the given id "'.concat(e,'".'));clearTimeout(r),t.delete(e)})(o),postMessage({error:null,id:r})}}else{if("set"!==s.method)throw new Error('The given method "'.concat(s.method,'" is not supported'));{const{params:{delay:i,now:n,timerId:a,timerType:d}}=s;if("interval"===d)((t,i,s)=>{const{expected:n,remainingDelay:a}=r(t,s);e.set(i,setTimeout(o,a,e,i,n,"interval"))})(i,a,n);else{if("timeout"!==d)throw new Error('The given type "'.concat(d,'" is not supported'));((e,i,s)=>{const{expected:n,remainingDelay:a}=r(e,s);t.set(i,setTimeout(o,a,t,i,n,"timeout"))})(i,a,n)}}}}catch(e){postMessage({error:{message:e.message},id:s.id,result:null})}}))})();`;
var ve = Qe(Ke, Ze);
var M = (typeof window > "u" ? "undefined" : typeof window) == "object";
var I = { setTimeout: M ? setTimeout.bind(window) : setTimeout, clearTimeout: M ? clearTimeout.bind(window) : clearTimeout, setInterval: M ? setInterval.bind(window) : setInterval, clearInterval: M ? clearInterval.bind(window) : clearInterval };
function it(n) {
I.setTimeout = n.setTimeout, I.clearTimeout = n.clearTimeout, I.setInterval = n.setInterval, I.clearInterval = n.clearInterval;
}
var Q = {};
var Ae = class {
constructor(e) {
__publicField(this, "name");
__publicField(this, "closed", false);
__publicField(this, "mc", new MessageChannel());
this.name = e, Q[e] = Q[e] || [], Q[e].push(this), this.mc.port1.start(), this.mc.port2.start(), this.onStorage = this.onStorage.bind(this), window.addEventListener("storage", this.onStorage);
}
onStorage(e) {
if (e.storageArea !== window.localStorage || e.key.substring(0, this.name.length) !== this.name || e.newValue === null) return;
let r = JSON.parse(e.newValue);
this.mc.port2.postMessage(r);
}
postMessage(e) {
if (this.closed) throw new Error("InvalidStateError");
let r = JSON.stringify(e), i = `${this.name}:${String(Date.now())}${String(Math.random())}`;
window.localStorage.setItem(i, r), I.setTimeout(() => {
window.localStorage.removeItem(i);
}, 500), Q[this.name].forEach((o) => {
o !== this && o.mc.port2.postMessage(JSON.parse(r));
});
}
close() {
if (this.closed) return;
this.closed = true, this.mc.port1.close(), this.mc.port2.close(), window.removeEventListener("storage", this.onStorage);
let e = Q[this.name].indexOf(this);
Q[this.name].splice(e, 1);
}
get onmessage() {
return this.mc.port1.onmessage;
}
set onmessage(e) {
this.mc.port1.onmessage = e;
}
get onmessageerror() {
return this.mc.port1.onmessageerror;
}
set onmessageerror(e) {
this.mc.port1.onmessageerror = e;
}
addEventListener(e, r) {
return this.mc.port1.addEventListener(e, r);
}
removeEventListener(e, r) {
return this.mc.port1.removeEventListener(e, r);
}
dispatchEvent(e) {
return this.mc.port1.dispatchEvent(e);
}
};
var st = typeof window > "u" ? void 0 : typeof window.BroadcastChannel == "function" ? window.BroadcastChannel : Ae;
function ot(n = 0) {
return new Promise((e) => I.setTimeout(e, n));
}
function Te() {
return Math.random().toString(36).substring(2);
}
var Ie = class {
constructor(e, r) {
__publicField(this, "options");
__publicField(this, "channel");
__publicField(this, "token", Te());
__publicField(this, "isLeader", false);
__publicField(this, "isDead", false);
__publicField(this, "isApplying", false);
__publicField(this, "reApply", false);
__publicField(this, "intervals", []);
__publicField(this, "listeners", []);
__publicField(this, "deferred");
this.channel = e, this.options = r, this.apply = this.apply.bind(this), this.awaitLeadership = this.awaitLeadership.bind(this), this.sendAction = this.sendAction.bind(this);
}
apply() {
return __async(this, null, function* () {
if (this.isLeader || this.isDead) return false;
if (this.isApplying) return this.reApply = true, false;
this.isApplying = true;
let e = false, r = (i) => {
let { token: o, action: u } = i.data;
o !== this.token && (u === 0 && o > this.token && (e = true), u === 1 && (e = true));
};
this.channel.addEventListener("message", r);
try {
return this.sendAction(0), yield ot(this.options.responseTime), this.channel.removeEventListener("message", r), this.isApplying = false, e ? this.reApply ? this.apply() : false : (this.assumeLead(), true);
} catch (e2) {
return false;
}
});
}
awaitLeadership() {
if (this.isLeader) return Promise.resolve();
let e = false, r = null;
return new Promise((i) => {
let o = () => {
if (e) return;
e = true;
try {
I.clearInterval(r);
} catch (e2) {
}
let g = this.intervals.indexOf(r);
g >= 0 && this.intervals.splice(g, 1), this.channel.removeEventListener("message", u), i();
};
r = I.setInterval(() => {
this.apply().then(() => {
this.isLeader && o();
});
}, this.options.fallbackInterval), this.intervals.push(r);
let u = (g) => {
let { action: O } = g.data;
O === 2 && this.apply().then(() => {
this.isLeader && o();
});
};
this.channel.addEventListener("message", u);
});
}
sendAction(e) {
this.channel.postMessage({ action: e, token: this.token });
}
assumeLead() {
this.isLeader = true;
let e = (r) => {
let { action: i } = r.data;
i === 0 && this.sendAction(1);
};
return this.channel.addEventListener("message", e), this.listeners.push(e), this.sendAction(1);
}
waitForLeadership() {
return this.deferred ? this.deferred : (this.deferred = this.awaitLeadership(), this.deferred);
}
close() {
if (!this.isDead) {
this.isDead = true, this.isLeader = false, this.sendAction(2);
try {
this.listeners.forEach((e) => this.channel.removeEventListener("message", e)), this.intervals.forEach((e) => I.clearInterval(e));
} catch (e) {
}
}
}
};
var Ee = class {
constructor(e) {
__publicField(this, "channel");
__publicField(this, "options");
__publicField(this, "elector");
__publicField(this, "token", Te());
__publicField(this, "registry", /* @__PURE__ */ new Map());
__publicField(this, "allIdle", false);
__publicField(this, "isLastActive", false);
let { channelName: r } = e;
if (this.options = e, this.channel = new st(r), this.registry.set(this.token, 1), e.leaderElection) {
let i = { fallbackInterval: 2e3, responseTime: 100 };
this.elector = new Ie(this.channel, i), this.elector.waitForLeadership();
}
this.channel.addEventListener("message", (i) => {
let { action: o, token: u, data: g } = i.data;
switch (o) {
case 3:
this.registry.set(u, 2);
break;
case 4:
this.registry.delete(u);
break;
case 5:
this.idle(u);
break;
case 6:
this.active(u);
break;
case 7:
this.prompt(u);
break;
case 8:
this.start(u);
break;
case 9:
this.reset(u);
break;
case 10:
this.activate(u);
break;
case 11:
this.pause(u);
break;
case 12:
this.resume(u);
break;
case 13:
this.options.onMessage(g);
break;
}
}), this.send(3);
}
get isLeader() {
if (!this.elector) throw new Error('\u274C Leader election is not enabled. To Enable it set the "leaderElection" property to true.');
return this.elector.isLeader;
}
prompt(e = this.token) {
this.registry.set(e, 0);
let r = [...this.registry.values()].every((i) => i === 0);
e === this.token && this.send(7), r && this.options.onPrompt();
}
idle(e = this.token) {
this.registry.set(e, 2);
let r = [...this.registry.values()].every((i) => i === 2);
e === this.token && this.send(5), !this.allIdle && r && (this.allIdle = true, this.options.onIdle());
}
active(e = this.token) {
this.allIdle = false, this.registry.set(e, 1);
let r = [...this.registry.values()].some((i) => i === 1);
e === this.token && this.send(6), r && this.options.onActive(), this.isLastActive = e === this.token;
}
start(e = this.token) {
this.allIdle = false, this.registry.set(e, 1), e === this.token ? this.send(8) : this.options.start(true), this.isLastActive = e === this.token;
}
reset(e = this.token) {
this.allIdle = false, this.registry.set(e, 1), e === this.token ? this.send(9) : this.options.reset(true), this.isLastActive = e === this.token;
}
activate(e = this.token) {
this.allIdle = false, this.registry.set(e, 1), e === this.token ? this.send(10) : this.options.activate(true), this.isLastActive = e === this.token;
}
pause(e = this.token) {
e === this.token ? this.send(11) : this.options.pause(true);
}
resume(e = this.token) {
e === this.token ? this.send(12) : this.options.resume(true);
}
message(e) {
try {
this.channel.postMessage({ action: 13, token: this.token, data: e });
} catch (e2) {
}
}
send(e) {
try {
this.channel.postMessage({ action: e, token: this.token });
} catch (e2) {
}
}
close() {
this.options.leaderElection && this.elector.close(), this.send(4), this.channel.close();
}
};
var at = M ? document : null;
var xe = ["mousemove", "keydown", "wheel", "DOMMouseScroll", "mousewheel", "mousedown", "touchstart", "touchmove", "MSPointerDown", "MSPointerMove", "visibilitychange", "focus"];
function ct(n, e) {
let r;
function i(...o) {
r && clearTimeout(r), r = setTimeout(() => {
n(...o), r = null;
}, e);
}
return i.cancel = function() {
clearTimeout(r);
}, i;
}
function be(n, e) {
let r = 0;
return function(...i) {
let o = (/* @__PURE__ */ new Date()).getTime();
if (!(o - r < e)) return r = o, n(...i);
};
}
var v = () => Date.now();
var Z = 2147483647;
function se({ timeout: n = 1e3 * 60 * 20, promptTimeout: e = 0, promptBeforeIdle: r = 0, element: i = at, events: o = xe, timers: u = void 0, immediateEvents: g = [], onPresenceChange: O = () => {
}, onPrompt: W = () => {
}, onIdle: m = () => {
}, onActive: a = () => {
}, onAction: d = () => {
}, onMessage: l = () => {
}, debounce: p = 0, throttle: f = 0, eventsThrottle: B = 200, startOnMount: y = true, startManually: D = false, stopOnIdle: ce = false, crossTab: j = false, name: Oe = "idle-timer", syncTimers: ee = 0, leaderElection: Ce = false, disabled: C = false } = {}) {
let De = _react.useRef.call(void 0, v()), ue = _react.useRef.call(void 0, v()), w = _react.useRef.call(void 0, null), R = _react.useRef.call(void 0, null), F = _react.useRef.call(void 0, 0), te = _react.useRef.call(void 0, 0), N = _react.useRef.call(void 0, 0), S = _react.useRef.call(void 0, 0), h = _react.useRef.call(void 0, false), E = _react.useRef.call(void 0, false), H = _react.useRef.call(void 0, false), _ = _react.useRef.call(void 0, true), re = _react.useRef.call(void 0, false), U = _react.useRef.call(void 0, null), s = _react.useRef.call(void 0, null), k = _react.useRef.call(void 0, n), G = _react.useRef.call(void 0, 0);
_react.useEffect.call(void 0, () => {
if (e && console.warn("\u26A0\uFE0F IdleTimer -- The `promptTimeout` property has been deprecated in favor of `promptBeforeIdle`. It will be removed in the next major release."), r && e) throw new Error("\u274C Both promptTimeout and promptBeforeIdle can not be set. The promptTimeout property will be deprecated in a future version.");
if (n >= Z) throw new Error(`\u274C The value for the timeout property must fit in a 32 bit signed integer, ${Z}.`);
if (e >= Z) throw new Error(`\u274C The value for the promptTimeout property must fit in a 32 bit signed integer, ${Z}.`);
if (r >= Z) throw new Error(`\u274C The value for the promptBeforeIdle property must fit in a 32 bit signed integer, ${Z}.`);
if (r >= n) throw new Error(`\u274C The value for the promptBeforeIdle property must be less than the timeout property, ${n}.`);
if (r ? (k.current = n - r, G.current = r) : (k.current = n, G.current = e), !_.current) {
if (D || C) return;
h.current && (X.current(null, L), s.current && s.current.active()), J();
}
}, [n, e, r, D, C]);
let Ne = _react.useRef.call(void 0, ce);
_react.useEffect.call(void 0, () => {
Ne.current = ce;
}, [ce]);
let He = _react.useRef.call(void 0, g), ne = _react.useRef.call(void 0, i), ye = _react.useRef.call(void 0, [...(/* @__PURE__ */ new Set([...o, ...g])).values()]), A = _react.useRef.call(void 0, C);
_react.useEffect.call(void 0, () => {
A.current = C, !_.current && (C ? fe() : D || J());
}, [C]);
let ie = _react.useRef.call(void 0, O);
_react.useEffect.call(void 0, () => {
ie.current = O;
}, [O]);
let le = _react.useRef.call(void 0, W);
_react.useEffect.call(void 0, () => {
le.current = W;
}, [W]);
let me = _react.useRef.call(void 0, m);
_react.useEffect.call(void 0, () => {
me.current = m;
}, [m]);
let X = _react.useRef.call(void 0, a);
_react.useEffect.call(void 0, () => {
X.current = a;
}, [a]);
let de = _react.useRef.call(void 0, d);
_react.useEffect.call(void 0, () => {
de.current = d;
}, [d]);
let z = _react.useRef.call(void 0, l);
_react.useEffect.call(void 0, () => {
z.current = l;
}, [l]);
let q = _react.useMemo.call(void 0, () => {
let t = (P, K) => de.current(P, K);
return p > 0 ? ct(t, p) : f > 0 ? be(t, f) : t;
}, [f, p]), _e = _react.useRef.call(void 0, );
_react.useEffect.call(void 0, () => {
j && ee && (_e.current = be(() => {
s.current.active();
}, ee));
}, [j, ee]);
let x = () => {
U.current !== null && (I.clearTimeout(U.current), U.current = null);
}, $ = (t, P = true) => {
x(), U.current = I.setTimeout(Le, t || k.current), P && (R.current = v());
}, Ue = (t) => {
!E.current && !h.current && (le.current(t, L), ie.current({ type: "active", prompted: true }, L)), S.current = 0, N.current = v(), E.current = true, $(G.current, false);
}, Fe = () => {
x(), h.current || (me.current(null, L), ie.current({ type: "idle" }, L)), h.current = true, w.current = v(), Ne.current ? Y() : E.current && (N.current = 0, E.current = false);
}, we = (t) => {
x(), (h.current || E.current) && (X.current(t, L), ie.current({ type: "active", prompted: false }, L)), E.current = false, N.current = 0, h.current = false, F.current += v() - w.current, te.current += v() - w.current, V(), $();
}, Le = (t) => {
if (!h.current) {
q.cancel && q.cancel();
let K = v() - R.current;
if (!(k.current + G.current < K) && G.current > 0 && !E.current) {
s.current ? s.current.prompt() : Ue(t);
return;
}
s.current ? s.current.idle() : Fe();
return;
}
s.current ? s.current.active() : we(t);
}, Pe = (t) => {
if (!y && !R.current && (R.current = v(), X.current(null, L)), q(t, L), E.current) return;
if (x(), !h.current && He.current.includes(t.type)) {
Le(t);
return;
}
let P = v() - R.current;
if (h.current && !ce || !h.current && P >= k.current) {
Le(t);
return;
}
H.current = false, S.current = 0, N.current = 0, $(), j && ee && _e.current();
}, pe = _react.useRef.call(void 0, Pe);
_react.useEffect.call(void 0, () => {
let t = re.current;
t && Y(), B > 0 ? pe.current = be(Pe, B) : pe.current = Pe, t && V();
}, [B, f, p, de, j, ee]);
let V = () => {
M && ne.current && (re.current || (ye.current.forEach((t) => {
ne.current.addEventListener(t, pe.current, { capture: true, passive: true });
}), re.current = true));
}, Y = (t = false) => {
M && ne.current && (re.current || t) && (ye.current.forEach((P) => {
ne.current.removeEventListener(P, pe.current, { capture: true });
}), re.current = false);
}, J = _react.useCallback.call(void 0, (t) => A.current ? false : (x(), V(), h.current = false, E.current = false, H.current = false, S.current = 0, N.current = 0, s.current && !t && s.current.start(), $(), true), [U, h, A, k, s]), Se = _react.useCallback.call(void 0, (t) => A.current ? false : (x(), V(), ue.current = v(), F.current += v() - w.current, te.current += v() - w.current, F.current = 0, h.current = false, E.current = false, H.current = false, S.current = 0, N.current = 0, s.current && !t && s.current.reset(), D || $(), true), [U, h, k, D, A, s]), Ve = _react.useCallback.call(void 0, (t) => A.current ? false : (x(), V(), (h.current || E.current) && we(), h.current = false, E.current = false, H.current = false, S.current = 0, N.current = 0, ue.current = v(), s.current && !t && s.current.activate(), $(), true), [U, h, E, A, k, s]), fe = _react.useCallback.call(void 0, (t = false) => A.current || H.current ? false : (S.current = We(), H.current = true, Y(), x(), s.current && !t && s.current.pause(), true), [U, A, s]), Me = _react.useCallback.call(void 0, (t = false) => A.current || !H.current ? false : (H.current = false, E.current || V(), h.current || $(S.current), N.current && (N.current = v()), s.current && !t && s.current.resume(), true), [U, k, A, S, s]), ut = _react.useCallback.call(void 0, (t, P) => (s.current ? (P && z.current(t, L), s.current.message(t)) : P && z.current(t, L), true), [l]), lt = _react.useCallback.call(void 0, () => h.current, [h]), mt = _react.useCallback.call(void 0, () => E.current, [E]), dt = _react.useCallback.call(void 0, () => s.current ? s.current.isLeader : null, [s]), pt = _react.useCallback.call(void 0, () => s.current ? s.current.isLastActive : null, [s]), ft = _react.useCallback.call(void 0, () => s.current ? s.current.token : null, [s]), We = _react.useCallback.call(void 0, () => {
if (H.current) return S.current;
let t = S.current ? S.current : G.current + k.current, P = R.current ? v() - R.current : 0, K = Math.floor(t - P);
return K < 0 ? 0 : Math.abs(K);
}, [k, G, E, S, R]), Be = _react.useCallback.call(void 0, () => Math.round(v() - ue.current), [ue]), Ge = _react.useCallback.call(void 0, () => Math.round(v() - De.current), [De]), ht = _react.useCallback.call(void 0, () => w.current ? new Date(w.current) : null, [w]), vt = _react.useCallback.call(void 0, () => R.current ? new Date(R.current) : null, [R]), qe = _react.useCallback.call(void 0, () => h.current ? Math.round(v() - w.current + F.current) : Math.round(F.current), [w, F]), $e = _react.useCallback.call(void 0, () => h.current ? Math.round(v() - w.current + te.current) : Math.round(te.current), [w, te]), Tt = _react.useCallback.call(void 0, () => {
let t = Math.round(Be() - qe());
return t >= 0 ? t : 0;
}, [w, F]), It = _react.useCallback.call(void 0, () => {
let t = Math.round(Ge() - $e());
return t >= 0 ? t : 0;
}, [w, F]);
_react.useEffect.call(void 0, () => {
if (p > 0 && f > 0) throw new Error("\u274C onAction can either be throttled or debounced, not both.");
u && it(u);
let t = () => {
s.current && s.current.close(), q.cancel && q.cancel(), x(), Y(true);
};
return M && window.addEventListener("beforeunload", t), () => {
M && window.removeEventListener("beforeunload", t), s.current && s.current.close(), q.cancel && q.cancel(), x(), Y(true);
};
}, []), _react.useEffect.call(void 0, () => {
s.current && s.current.close(), j ? s.current = new Ee({ channelName: Oe, leaderElection: Ce, onPrompt: () => {
Ue();
}, onIdle: () => {
Fe();
}, onActive: () => {
we();
}, onMessage: (t) => {
z.current(t, L);
}, start: J, reset: Se, activate: Ve, pause: fe, resume: Me }) : s.current = null;
}, [j, Oe, Ce, le, me, X, z, J, Se, fe, Me]), _react.useEffect.call(void 0, () => {
_.current || (x(), Y(true)), !(D || C) && (y ? J() : V());
}, [D, y, C, _]), _react.useEffect.call(void 0, () => {
if (!_.current) {
let t = [...(/* @__PURE__ */ new Set([...o, ...g])).values()];
if (Y(), ye.current = t, ne.current = i, He.current = g, D || C) return;
y ? J() : V();
}
}, [i, JSON.stringify(o), JSON.stringify(g), _, C, D, y]), _react.useEffect.call(void 0, () => {
_.current && (_.current = false);
}, [_]);
let L = { message: ut, start: J, reset: Se, activate: Ve, pause: fe, resume: Me, isIdle: lt, isPrompted: mt, isLeader: dt, isLastActiveTab: pt, getTabId: ft, getRemainingTime: We, getElapsedTime: Be, getTotalElapsedTime: Ge, getLastIdleTime: ht, getLastActiveTime: vt, getIdleTime: qe, getTotalIdleTime: $e, getActiveTime: Tt, getTotalActiveTime: It, setOnPresenceChange: (t) => {
O = t, ie.current = t;
}, setOnPrompt: (t) => {
W = t, le.current = t;
}, setOnIdle: (t) => {
m = t, me.current = t;
}, setOnActive: (t) => {
a = t, X.current = t;
}, setOnAction: (t) => {
d = t, de.current = t;
}, setOnMessage: (t) => {
l = t, z.current = t;
} };
return L;
}
var ge = _react.createContext.call(void 0, null);
var Ut = ge.Consumer;
// src/hooks/use-idle-timer-prompt.ts
function useIdleTimerPrompt(initialValue = false) {
const [showIdleTimerPrompt, setOpened] = _react.useState.call(void 0, initialValue);
const openIdleTimerPrompt = () => setOpened(true);
const closeIdleTimerPrompt = () => setOpened(false);
return {
showIdleTimerPrompt,
openIdleTimerPrompt,
closeIdleTimerPrompt
};
}
// src/hooks/use-idle-timer-countdown.ts
var useIdleTimerCountdown = (callback, delay = 1e3) => {
const intervalId = _react.useRef.call(void 0, null);
const fn = _react.useRef.call(void 0, callback);
const startIdleTimerCountdown = _react.useCallback.call(void 0,
(timer) => {
if (intervalId.current) return;
const handler = () => fn.current(timer);
const id = setInterval(handler, delay);
intervalId.current = id;
},
[delay]
);
const stopIdleTimerCountdown = _react.useCallback.call(void 0, () => {
if (intervalId.current) {
clearInterval(intervalId.current);
intervalId.current = null;
}
}, []);
const interval = { startIdleTimerCountdown, stopIdleTimerCountdown };
_react.useEffect.call(void 0, () => stopIdleTimerCountdown, [stopIdleTimerCountdown]);
return interval;
};
// src/constants/index.ts
var DEFAULT_INACTIVITY_TIME = 1e3 * 60 * 5;
var DEFAULT_PROMPT_TIME = 1e3 * 60;
var DEFAULT_SYNC_TIMERS = 500;
// src/hooks/use-idle-timeout.ts
function useIdleTimeout(config = {}) {
const _a = config, {
timeout = DEFAULT_INACTIVITY_TIME,
promptBeforeIdle = DEFAULT_PROMPT_TIME,
syncTimers = DEFAULT_SYNC_TIMERS,
crossTab = true,
leaderElection = true,
disabled = false
} = _a, idleTimeConfigurationHandlers = __objRest(_a, [
"timeout",
"promptBeforeIdle",
"syncTimers",
"crossTab",
"leaderElection",
"disabled"
]);
const [remainingTime, setRemainingTime] = _react.useState.call(void 0, promptBeforeIdle);
const _b = idleTimeConfigurationHandlers, { onIdle, onPrompt, onAction } = _b, idleTimeConfiguration = __objRest(_b, ["onIdle", "onPrompt", "onAction"]);
const { showIdleTimerPrompt, openIdleTimerPrompt, closeIdleTimerPrompt } = useIdleTimerPrompt();
const { startIdleTimerCountdown, stopIdleTimerCountdown } = useIdleTimerCountdown((idleTimer2) => {
if (!idleTimer2 || !idleTimer2.isPrompted()) return;
const remainingTime2 = idleTimer2.getRemainingTime();
setRemainingTime(Math.max(0, remainingTime2));
});
const handleIdle = _react.useCallback.call(void 0,
(event, idleTimer2) => {
if (!idleTimer2 || !idleTimer2.isPrompted()) return;
closeIdleTimerPrompt();
stopIdleTimerCountdown();
onIdle == null ? void 0 : onIdle(event, idleTimer2);
},
[closeIdleTimerPrompt, stopIdleTimerCountdown, onIdle]
);
const handlePrompt = _react.useCallback.call(void 0,
(event, idleTimer2) => {
if (!idleTimer2) return;
const remainingTime2 = idleTimer2.getRemainingTime();
setRemainingTime(remainingTime2);
openIdleTimerPrompt();
startIdleTimerCountdown(idleTimer2);
onPrompt == null ? void 0 : onPrompt(event, idleTimer2);
},
[openIdleTimerPrompt, startIdleTimerCountdown, onPrompt]
);
const handleAction = _react.useCallback.call(void 0,
(event, idleTimer2) => {
if (!idleTimer2 || idleTimer2.isPrompted()) return;
idleTimer2.reset();
onAction == null ? void 0 : onAction(event, idleTimer2);
},
[onAction]
);
const idleTimer = se(__spreadValues({
timeout,
promptBeforeIdle,
onPrompt: handlePrompt,
onIdle: handleIdle,
onAction: handleAction,
crossTab,
leaderElection,
syncTimers,
disabled
}, idleTimeConfiguration));
const continueUserSession = _react.useCallback.call(void 0, () => {
closeIdleTimerPrompt();
stopIdleTimerCountdown();
idleTimer.reset();
}, [closeIdleTimerPrompt, stopIdleTimerCountdown, idleTimer]);
return {
remainingTime,
continueUserSession,
showIdleTimerPrompt,
idleTimer
};
}
// src/hooks/use-idle-timer-debug.ts
var useIdleTimerDebug = (idleTimer, enabled = false) => {
const extractIdleTimerState = (idleTimer2) => ({
isIdle: idleTimer2.isIdle(),
isPrompted: idleTimer2.isPrompted(),
remainingTime: idleTimer2.getRemainingTime(),
elapsedTime: idleTimer2.getElapsedTime(),
totalActiveTime: idleTimer2.getTotalActiveTime(),
totalIdleTime: idleTimer2.getTotalIdleTime(),
totalElapsedTime: idleTimer2.getTotalElapsedTime()
});
const [idleTimerState, setIdleTimerState] = _react.useState.call(void 0,
extractIdleTimerState(idleTimer)
);
const { startIdleTimerCountdown, stopIdleTimerCountdown } = useIdleTimerCountdown((idleTimer2) => {
if (!idleTimer2 || !enabled) return;
setIdleTimerState(extractIdleTimerState(idleTimer2));
});
_react.useEffect.call(void 0, () => {
if (idleTimer && enabled) {
setIdleTimerState(extractIdleTimerState(idleTimer));
startIdleTimerCountdown(idleTimer);
} else {
stopIdleTimerCountdown();
}
return stopIdleTimerCountdown;
}, [idleTimer, enabled]);
return idleTimerState;
};
// src/utils/milliseconds-to-seconds/index.ts
var millisecondsToSeconds = (milliseconds) => {
return Math.floor(milliseconds / 1e3);
};
// src/utils/format-time/index.ts
var formatTime = (ms) => {
const timeInSeconds = millisecondsToSeconds(ms);
const hours = Math.floor(timeInSeconds / 3600);
const minutes = Math.floor(timeInSeconds % 3600 / 60);
const seconds = Math.floor(timeInSeconds % 60);
if (hours > 0) {
return `${hours}:${minutes.toString().padStart(2, "0")}:${seconds.toString().padStart(2, "0")}`;
}
return `${minutes.toString().padStart(2, "0")}:${seconds.toString().padStart(2, "0")}`;
};
// src/utils/seconds-to-milliseconds/index.ts
var secondsToMilliseconds = (seconds) => {
return seconds * 1e3;
};
exports.formatTime = formatTime; exports.millisecondsToSeconds = millisecondsToSeconds; exports.secondsToMilliseconds = secondsToMilliseconds; exports.useIdleTimeout = useIdleTimeout; exports.useIdleTimerDebug = useIdleTimerDebug;
//# sourceMappingURL=index.cjs.map