react-idle-timer
Advanced tools
Comparing version
@@ -94,16 +94,16 @@ # Welcome to the IdleTimer contributing guide | ||
- Start the commit message with an applicable emoji: | ||
- :art: `:art:` When improving the format/structure of the code. | ||
- :stopwatch: `:stopwatch:` When improving performance.. | ||
- :memo: `:memo:` When writing docs. | ||
- :zap: `:zap:` When adding a new feature. | ||
- :sparkles: `:sparkles:` When enhancing an existing feature . | ||
- :lady_beetle: `:lady_beetle:` When fixing a bug. | ||
- :fire: `:fire:` When removing code or files. | ||
- :green_heart: `:green_heart:` When fixing the CI build. | ||
- :white_check_mark: `:white_check_mark:` When adding tests. | ||
- :lock: `:lock:` When dealing with security. | ||
- :arrow_up: `:arrow_up:` When upgrading dependencies. | ||
- :arrow_down: `:arrow_down:` When downgrading dependencies. | ||
- :shirt: `:shirt:` When removing linter warnings. | ||
- :shower: `:shower:` When performing generic clean up. | ||
- :art: `:art:` When improving the format/structure of the code. | ||
- :stopwatch: `:stopwatch:` When improving performance.. | ||
- :memo: `:memo:` When writing docs. | ||
- :zap: `:zap:` When adding a new feature. | ||
- :sparkles: `:sparkles:` When enhancing an existing feature . | ||
- :lady_beetle: `:lady_beetle:` When fixing a bug. | ||
- :fire: `:fire:` When removing code or files. | ||
- :green_heart: `:green_heart:` When fixing the CI build. | ||
- :white_check_mark: `:white_check_mark:` When adding tests. | ||
- :lock: `:lock:` When dealing with security. | ||
- :arrow_up: `:arrow_up:` When upgrading dependencies. | ||
- :arrow_down: `:arrow_down:` When downgrading dependencies. | ||
- :shirt: `:shirt:` When removing linter warnings. | ||
- :shower: `:shower:` When performing generic clean up. | ||
@@ -110,0 +110,0 @@ ### Pull Request |
@@ -1,2 +0,2 @@ | ||
var Ke=Object.create,de=Object.defineProperty;var $e=Object.getOwnPropertyDescriptor;var Qe=Object.getOwnPropertyNames;var Ze=Object.getPrototypeOf,et=Object.prototype.hasOwnProperty;var tt=t=>de(t,"__esModule",{value:!0});var rt=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var nt=(t,e,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Qe(e))!et.call(t,r)&&r!=="default"&&de(t,r,{get:()=>e[r],enumerable:!(n=$e(e,r))||n.enumerable});return t},ot=t=>nt(tt(de(t!=null?Ke(Ze(t)):{},"default",t&&t.__esModule&&"default"in t?{get:()=>t.default,enumerable:!0}:{value:t,enumerable:!0})),t);var Le=rt((ne,we)=>{(function(t,e){typeof ne=="object"&&typeof we!="undefined"?e(ne):typeof define=="function"&&define.amd?define(["exports"],e):(t=typeof globalThis!="undefined"?globalThis:t||self,e(t.fastUniqueNumbers={}))})(ne,function(t){"use strict";var e=function(o){return function(p){var d=o(p);return p.add(d),d}},n=function(o){return function(p,d){return o.set(p,d),d}},r=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,i=536870912,h=i*2,b=function(o,p){return function(d){var W=p.get(d),M=W===void 0?d.size:W<h?W+1:0;if(!d.has(M))return o(d,M);if(d.size<i){for(;d.has(M);)M=Math.floor(Math.random()*h);return o(d,M)}if(d.size>r)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;d.has(M);)M=Math.floor(Math.random()*r);return o(d,M)}},y=new WeakMap,L=n(y),m=b(L,y),a=e(m);t.addUniqueNumber=a,t.generateUniqueNumber=m,Object.defineProperty(t,"__esModule",{value:!0})})});function st(t){return function(n){let r={...n};!r.onPrompt&&t.prototype.onPrompt&&(r.onPrompt=()=>{t.prototype.onPrompt()}),!r.onIdle&&t.prototype.onIdle&&(r.onIdle=()=>{t.prototype.onIdle()}),!r.onActive&&t.prototype.onActive&&(r.onActive=h=>{t.prototype.onActive(h)}),!r.onAction&&t.prototype.onAction&&(r.onAction=h=>{t.prototype.onAction(h)});let i=X(r);return React.createElement(t,{...n,...i})}}import{useEffect as B,useRef as f,useCallback as I}from"react";var K=ot(Le());var Me=t=>t.method!==void 0&&t.method==="call";var ke=t=>t.error===null&&typeof t.id=="number";var xe=t=>{let e=new Map([[0,()=>{}]]),n=new Map([[0,()=>{}]]),r=new Map,i=new Worker(t);return i.addEventListener("message",({data:m})=>{if(Me(m)){let{params:{timerId:a,timerType:u}}=m;if(u==="interval"){let o=e.get(a);if(typeof o=="number"){let p=r.get(o);if(p===void 0||p.timerId!==a||p.timerType!==u)throw new Error("The timer is in an undefined state.")}else if(typeof o!="undefined")o();else throw new Error("The timer is in an undefined state.")}else if(u==="timeout"){let o=n.get(a);if(typeof o=="number"){let p=r.get(o);if(p===void 0||p.timerId!==a||p.timerType!==u)throw new Error("The timer is in an undefined state.")}else if(typeof o!="undefined")o(),n.delete(a);else throw new Error("The timer is in an undefined state.")}}else if(ke(m)){let{id:a}=m,u=r.get(a);if(u===void 0)throw new Error("The timer is in an undefined state.");let{timerId:o,timerType:p}=u;r.delete(a),p==="interval"?e.delete(o):n.delete(o)}else{let{error:{message:a}}=m;throw new Error(a)}}),{clearInterval:m=>{let a=(0,K.generateUniqueNumber)(r);r.set(a,{timerId:m,timerType:"interval"}),e.set(m,a),i.postMessage({id:a,method:"clear",params:{timerId:m,timerType:"interval"}})},clearTimeout:m=>{let a=(0,K.generateUniqueNumber)(r);r.set(a,{timerId:m,timerType:"timeout"}),n.set(m,a),i.postMessage({id:a,method:"clear",params:{timerId:m,timerType:"timeout"}})},setInterval:(m,a)=>{let u=(0,K.generateUniqueNumber)(e);return e.set(u,()=>{m(),typeof e.get(u)=="function"&&i.postMessage({id:null,method:"set",params:{delay:a,now:performance.now(),timerId:u,timerType:"interval"}})}),i.postMessage({id:null,method:"set",params:{delay:a,now:performance.now(),timerId:u,timerType:"interval"}}),u},setTimeout:(m,a)=>{let u=(0,K.generateUniqueNumber)(n);return n.set(u,m),i.postMessage({id:null,method:"set",params:{delay:a,now:performance.now(),timerId:u,timerType:"timeout"}}),u}}};var $=null,Se=(t,e)=>()=>{if($!==null)return $;let n=new Blob([e],{type:"application/javascript; charset=utf-8"}),r=URL.createObjectURL(n);return $=t(r),$.setTimeout(()=>URL.revokeObjectURL(r),0),$};var Re=`(()=>{"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 oe=Se(xe,Re),pe=t=>oe().clearInterval(t),Pe=t=>oe().clearTimeout(t),Ae=(t,e)=>oe().setInterval(t,e),G=(t,e)=>oe().setTimeout(t,e);var H=[],De=class{constructor(e){this.closed=!1;this.mc=new MessageChannel;this.name=e,H[e]=H[e]||[],H[e].push(this),this.mc.port1.start(),this.mc.port2.start(),this.onStorage=this.onStorage.bind(this),global.addEventListener("storage",this.onStorage)}onStorage(e){if(e.storageArea!==global.localStorage||e.newValue===null||e.key!==this.name)return;let n=JSON.parse(e.newValue);this.mc.port2.postMessage(n)}postMessage(e){if(this.closed)throw new Error("InvalidStateError");let n=JSON.stringify(e),r=`this.name${String(Date.now())}String(Math.random())`;global.localStorage.setItem(r,n),G(()=>{global.localStorage.removeItem(r)},500),H[this.name].forEach(i=>{i!==this&&i.mc.port2.postMessage(JSON.parse(n))})}close(){if(this.closed)return;this.closed=!0,this.mc.port1.close(),this.mc.port2.close(),global.removeEventListener("storage",this.onStorage);let e=H[this.name].indexOf(this);H[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,n){return this.mc.port1.addEventListener(e,n)}removeEventListener(e,n){return this.mc.port1.removeEventListener(e,n)}dispatchEvent(e){return this.mc.port1.dispatchEvent(e)}},_e=typeof global.BroadcastChannel=="function"?global.BroadcastChannel:De;function Ce(t=0){return new Promise(e=>G(e,t))}var U=(typeof window=="undefined"?"undefined":typeof window)=="object";var E=()=>U?performance.now():Date.now();function Ne(){return E().toString(36).substring(2)}var q;(function(e){e[e.LEADER=0]="LEADER"})(q||(q={}));var k;(function(r){r[r.APPLY=0]="APPLY",r[r.TELL=1]="TELL",r[r.CLOSE=2]="CLOSE"})(k||(k={}));var fe=class{constructor(e,n){this.token=Ne();this.isLeader=!1;this.isDead=!1;this.isApplying=!1;this.intervals=[];this.listeners=[];this.channel=e,this.options=n,this.apply=this.apply.bind(this),this.awaitLeadership=this.awaitLeadership.bind(this),this.sendAction=this.sendAction.bind(this)}async apply(){if(this.isLeader||this.isDead||this.isApplying)return!1;this.isApplying=!0;let e=!1,n=r=>{let{ctx:i,token:h,action:b}=r.data;i===0&&h!==this.token&&(b===0&&h>this.token&&(e=!0),b===1&&(e=!0))};this.channel.addEventListener("message",n);try{if(this.sendAction(0),await Ce(this.options.responseTime),e)throw new Error;return this.sendAction(0),this.assumeLead(),this.channel.removeEventListener("message",n),this.isApplying=!1,!0}catch{return!1}}awaitLeadership(){if(this.isLeader)return Promise.resolve();let e=!1,n=null;return new Promise(r=>{let i=()=>{if(e)return;e=!0,pe(n);let b=this.intervals.indexOf(n);this.intervals.splice(b,1),this.channel.removeEventListener("message",h),r()};n=Ae(()=>{this.apply().then(()=>{this.isLeader&&i()})},this.options.fallbackInterval),this.intervals.push(n);let h=b=>{let{ctx:y,action:L}=b.data;y===0&&L===2&&this.apply().then(()=>{this.isLeader&&i()})};this.channel.addEventListener("message",h)})}sendAction(e){this.channel.postMessage({ctx:0,action:e,token:this.token})}assumeLead(){this.isLeader=!0;let e=n=>{let{ctx:r,action:i}=n.data;r===0&&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(){this.isDead||(this.isDead=!0,this.isLeader=!1,this.sendAction(2),this.listeners.forEach(e=>this.channel.removeEventListener("message",e)),this.intervals.forEach(e=>pe(e)))}};var c;(function(o){o[o.REGISTER=0]="REGISTER",o[o.DEREGISTER=1]="DEREGISTER",o[o.IDLE=2]="IDLE",o[o.ACTIVE=3]="ACTIVE",o[o.EMIT_IDLE=4]="EMIT_IDLE",o[o.EMIT_ACTIVE=5]="EMIT_ACTIVE",o[o.EMIT_MESSAGE=6]="EMIT_MESSAGE",o[o.START=7]="START",o[o.RESET=8]="RESET",o[o.PAUSE=9]="PAUSE",o[o.RESUME=10]="RESUME",o[o.MESSAGE=11]="MESSAGE"})(c||(c={}));var he=class{constructor(e){this.isLeader=!1;this.allIdle=!1;this.registry=new Map;let{channelName:n,fallbackInterval:r,responseTime:i}=e;this.options=e,this.channel=new _e(n),this.elector=new fe(this.channel,{fallbackInterval:r,responseTime:i}),this.elector.waitForLeadership().then(()=>{this.isLeader=!0}),this.channel.addEventListener("message",h=>{let{action:b,token:y,data:L}=h.data;switch(b){case 0:this.registry.set(y,!1);break;case 1:this.registry.delete(y);break;case 2:this.idle(y);break;case 3:this.active(y);break;case 4:this.options.onIdle();break;case 5:this.options.onActive();break;case 6:this.options.onMessage(L);break;case 7:this.options.start(!0);break;case 8:this.options.reset(!0);break;case 9:this.options.pause(!0);break;case 10:this.options.resume(!0);break}}),this.send(0)}idle(e=this.elector.token){this.registry.set(e,!0);let n=[...this.registry.values()].every(r=>r);!this.allIdle&&n&&(this.allIdle=!0,this.isLeader?(this.options.onIdle(),this.options.emitOnAllTabs&&this.send(4)):this.send(2))}active(e=this.elector.token){this.registry.set(e,!1);let n=[...this.registry.values()].some(r=>!r);this.allIdle&&n&&(this.allIdle=!1,this.isLeader?(this.options.onActive(),this.options.emitOnAllTabs&&this.send(5)):this.send(3))}message(e){try{this.channel.postMessage({action:6,token:this.elector.token,data:e})}catch{}}send(e){try{this.channel.postMessage({action:e,token:this.elector.token})}catch{}}close(){this.send(1),this.elector.close(),this.channel.close()}};var Oe=U?document:null,Fe=["mousemove","keydown","wheel","DOMMouseScroll","mousewheel","mousedown","touchstart","touchmove","MSPointerDown","MSPointerMove","visibilitychange"];import{useRef as it,useEffect as at}from"react";function O(t){let e=it(t);return at(()=>{e.current=t},[t]),e}function Ue(t,e){let n;function r(...i){n&&clearTimeout(n),n=setTimeout(()=>{t(...i),n=null},e)}return r.cancel=function(){clearTimeout(n)},r}function Te(t,e){let n=0;return function(...r){let i=new Date().getTime();if(!(i-n<e))return n=i,t(...r)}}function X({timeout:t=1e3*60*20,promptTimeout:e=0,element:n=Oe,events:r=Fe,immediateEvents:i=[],onPrompt:h=()=>{},onIdle:b=()=>{},onActive:y=()=>{},onAction:L=()=>{},onMessage:m=()=>{},debounce:a=0,throttle:u=0,eventsThrottle:o=200,startOnMount:p=!0,startManually:d=!1,stopOnIdle:W=!1,crossTab:M=!1,emitOnAllTabs:x=!1}={}){let V=f(E()),ve=f(Date.now()),R=f(null),P=f(null),j=f(0),T=f(!0),S=f(!1),Q=f(!0),Y=f(!1),g=f(!1),w=f(0),A=f(0),D=f(null),l=f(null),ie=O(e),Be=O(W),We=O(i),ae=f(r),Ge=f(n);B(()=>{Q.current||(F(),ae.current=r,Ge.current=n,N())},[r,n]);let le=O(b),Z=O(y),He=O(h),ee=O(m),_=f();B(()=>{_.current?.cancel&&_.current.cancel(),a>0?_.current=Ue(L,a):u>0?_.current=Te(L,u):_.current=L},[L,u,a]);let C=()=>{D.current!==null&&(Pe(D.current),D.current=null)},z=(s,v=!0)=>{C(),D.current=G(ue,s||t),v&&(P.current=E())},ue=s=>{let v=!T.current;if(v){if(ie.current>0&&!g.current){F(),w.current=0,A.current=E(),g.current=!0,He.current(s),z(ie.current,!1);return}T.current=v,Be.current?(C(),F()):g.current&&(N(),A.current=0,g.current=!1),R.current=E(),l.current?l.current.idle():le.current();return}T.current=v,j.current+=E()-R.current,N(),l.current?l.current.active():Z.current(s)},Ee=s=>{_.current(s),C();let v=E()-P.current;if((T.current&&!W||!T.current&&v>t)&&ue(s),S.current=!1,w.current=0,A.current=0,!T.current&&We.current.includes(s.type)){ue(s);return}z()},te=f();B(()=>{let s=Y.current;s&&F(),o>0?te.current=Te(Ee,o):te.current=Ee,s&&N()},[o]);let N=()=>{!U||Y.current||(ae.current.forEach(s=>{n.addEventListener(s,te.current,{capture:!0,passive:!0})}),Y.current=!0)},F=(s=!1)=>{!U||(Y.current||s)&&(ae.current.forEach(v=>{n.removeEventListener(v,te.current,{capture:!0})}),Y.current=!1)},J=I(s=>{C(),N(),T.current=!1,g.current=!1,S.current=!1,w.current=0,A.current=0,l.current&&(l.current.allIdle=!1,!s&&x&&l.current.send(c.START)),z()},[D,T,t,x]),re=I(s=>{C(),N(),(T.current||g.current)&&(l.current?l.current.active():Z.current()),T.current=!1,g.current=!1,S.current=!1,w.current=0,A.current=0,l.current&&(l.current.allIdle=!1,!s&&x&&l.current.send(c.RESET)),z()},[D,T,t,x]),ce=I((s=!1)=>S.current?!1:(w.current=Ie(),S.current=!0,F(),C(),l.current&&!s&&x&&l.current.send(c.PAUSE),!0),[D,x,l]),me=I((s=!1)=>S.current?(S.current=!1,g.current||N(),T.current||z(w.current),A.current&&(A.current=E()),l.current&&!s&&x&&l.current.send(c.RESUME),!0):!1,[D,w,x,l]),qe=I((s,v)=>{l.current?(v&&ee.current(s),l.current.message(s)):v&&ee.current(s)},[m]),Ve=I(()=>T.current,[T]),je=I(()=>g.current,[g]),Ye=I(()=>l.current?l.current.isLeader:!0,[l]),Ie=I(()=>{if(S.current)return w.current;let s=w.current?w.current:g.current?ie.current:t,v=P.current?g.current?E()-A.current:E()-P.current:0,ye=Math.ceil(s-v);return ye<0?0:Math.abs(ye)},[t,e,g,w,P]),be=I(()=>Math.round(E()-V.current),[V]),ze=I(()=>R.current?new Date(ve.current-V.current+R.current):null,[R]),Je=I(()=>P.current?new Date(ve.current-V.current+P.current):null,[P]),ge=I(()=>T.current?Math.round(E()-R.current+j.current):Math.round(j.current),[R,j]),Xe=I(()=>{let s=Math.round(be()-ge());return s>=0?s:0},[V,R,j]);return B(()=>{if(a>0&&u>0)throw new Error("\u274C onAction can either be throttled or debounced, not both.");return()=>{C(),F(!0),_.current.cancel&&_.current.cancel(),l.current&&l.current.close()}},[]),B(()=>{C(),F(!0),Q.current||(S.current=!0,T.current=!0,w.current=0),!d&&(p?J():N())},[d,p]),B(()=>{if(Q.current)Q.current=!1;else if(T.current){if(d)return;re()}else J()},[t]),B(()=>{l.current&&l.current.close(),M?l.current=new he({channelName:"idle-timer",fallbackInterval:2e3,responseTime:100,emitOnAllTabs:x,onIdle:le.current,onActive:Z.current,onMessage:ee.current,start:J,reset:re,pause:ce,resume:me}):l.current=null},[M,x,le,Z,ee,J,re,ce,me]),{message:qe,start:J,reset:re,pause:ce,resume:me,isIdle:Ve,isPrompted:je,isLeader:Ye,getRemainingTime:Ie,getElapsedTime:be,getLastIdleTime:ze,getLastActiveTime:Je,getTotalIdleTime:ge,getTotalActiveTime:Xe}}import{createContext as lt,useContext as ut}from"react";var se=lt(null);function ct(t){let e=X(t);return React.createElement(se.Provider,{value:e},t.children)}var mt=se.Consumer;function dt(){return ut(se)}export{mt as IdleTimerConsumer,se as IdleTimerContext,ct as IdleTimerProvider,X as useIdleTimer,dt as useIdleTimerContext,st as withIdleTimer}; | ||
var rt=Object.create,re=Object.defineProperty;var nt=Object.getOwnPropertyDescriptor;var ot=Object.getOwnPropertyNames;var st=Object.getPrototypeOf,it=Object.prototype.hasOwnProperty;var Le=t=>re(t,"__esModule",{value:!0});var at=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),lt=(t,e)=>{for(var r in e)re(t,r,{get:e[r],enumerable:!0})},ut=(t,e,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of ot(e))!it.call(t,n)&&n!=="default"&&re(t,n,{get:()=>e[n],enumerable:!(r=nt(e,n))||r.enumerable});return t},ne=t=>ut(Le(re(t!=null?rt(st(t)):{},"default",t&&t.__esModule&&"default"in t?{get:()=>t.default,enumerable:!0}:{value:t,enumerable:!0})),t);var xe=at((oe,ke)=>{(function(t,e){typeof oe=="object"&&typeof ke!="undefined"?e(oe):typeof define=="function"&&define.amd?define(["exports"],e):(t=typeof globalThis!="undefined"?globalThis:t||self,e(t.fastUniqueNumbers={}))})(oe,function(t){"use strict";var e=function(o){return function(f){var p=o(f);return f.add(p),p}},r=function(o){return function(f,p){return o.set(f,p),p}},n=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,a=536870912,h=a*2,I=function(o,f){return function(p){var U=f.get(p),L=U===void 0?p.size:U<h?U+1:0;if(!p.has(L))return o(p,L);if(p.size<a){for(;p.has(L);)L=Math.floor(Math.random()*h);return o(p,L)}if(p.size>n)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;p.has(L);)L=Math.floor(Math.random()*n);return o(p,L)}},g=new WeakMap,w=r(g),d=I(w,g),l=e(d);t.addUniqueNumber=l,t.generateUniqueNumber=d,Object.defineProperty(t,"__esModule",{value:!0})})});Le(exports);lt(exports,{IdleTimerConsumer:()=>qe,IdleTimerContext:()=>K,IdleTimerProvider:()=>He,useIdleTimer:()=>B,useIdleTimerContext:()=>Ve,withIdleTimer:()=>Me});function Me(t){return function(r){let n={...r};!n.onPrompt&&t.prototype.onPrompt&&(n.onPrompt=()=>{t.prototype.onPrompt()}),!n.onIdle&&t.prototype.onIdle&&(n.onIdle=()=>{t.prototype.onIdle()}),!n.onActive&&t.prototype.onActive&&(n.onActive=h=>{t.prototype.onActive(h)}),!n.onAction&&t.prototype.onAction&&(n.onAction=h=>{t.prototype.onAction(h)});let a=B(n);return React.createElement(t,{...r,...a})}}var s=ne(require("react"));var J=ne(xe());var Se=t=>t.method!==void 0&&t.method==="call";var Re=t=>t.error===null&&typeof t.id=="number";var Pe=t=>{let e=new Map([[0,()=>{}]]),r=new Map([[0,()=>{}]]),n=new Map,a=new Worker(t);return a.addEventListener("message",({data:d})=>{if(Se(d)){let{params:{timerId:l,timerType:c}}=d;if(c==="interval"){let o=e.get(l);if(typeof o=="number"){let f=n.get(o);if(f===void 0||f.timerId!==l||f.timerType!==c)throw new Error("The timer is in an undefined state.")}else if(typeof o!="undefined")o();else throw new Error("The timer is in an undefined state.")}else if(c==="timeout"){let o=r.get(l);if(typeof o=="number"){let f=n.get(o);if(f===void 0||f.timerId!==l||f.timerType!==c)throw new Error("The timer is in an undefined state.")}else if(typeof o!="undefined")o(),r.delete(l);else throw new Error("The timer is in an undefined state.")}}else if(Re(d)){let{id:l}=d,c=n.get(l);if(c===void 0)throw new Error("The timer is in an undefined state.");let{timerId:o,timerType:f}=c;n.delete(l),f==="interval"?e.delete(o):r.delete(o)}else{let{error:{message:l}}=d;throw new Error(l)}}),{clearInterval:d=>{let l=(0,J.generateUniqueNumber)(n);n.set(l,{timerId:d,timerType:"interval"}),e.set(d,l),a.postMessage({id:l,method:"clear",params:{timerId:d,timerType:"interval"}})},clearTimeout:d=>{let l=(0,J.generateUniqueNumber)(n);n.set(l,{timerId:d,timerType:"timeout"}),r.set(d,l),a.postMessage({id:l,method:"clear",params:{timerId:d,timerType:"timeout"}})},setInterval:(d,l)=>{let c=(0,J.generateUniqueNumber)(e);return e.set(c,()=>{d(),typeof e.get(c)=="function"&&a.postMessage({id:null,method:"set",params:{delay:l,now:performance.now(),timerId:c,timerType:"interval"}})}),a.postMessage({id:null,method:"set",params:{delay:l,now:performance.now(),timerId:c,timerType:"interval"}}),c},setTimeout:(d,l)=>{let c=(0,J.generateUniqueNumber)(r);return r.set(c,d),a.postMessage({id:null,method:"set",params:{delay:l,now:performance.now(),timerId:c,timerType:"timeout"}}),c}}};var X=null,Ae=(t,e)=>()=>{if(X!==null)return X;let r=new Blob([e],{type:"application/javascript; charset=utf-8"}),n=URL.createObjectURL(r);return X=t(n),X.setTimeout(()=>URL.revokeObjectURL(n),0),X};var De=`(()=>{"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 se=Ae(Pe,De),fe=t=>se().clearInterval(t),_e=t=>se().clearTimeout(t),Ce=(t,e)=>se().setInterval(t,e),W=(t,e)=>se().setTimeout(t,e);var G=[],Ne=class{constructor(e){this.closed=!1;this.mc=new MessageChannel;this.name=e,G[e]=G[e]||[],G[e].push(this),this.mc.port1.start(),this.mc.port2.start(),this.onStorage=this.onStorage.bind(this),global.addEventListener("storage",this.onStorage)}onStorage(e){if(e.storageArea!==global.localStorage||e.newValue===null||e.key!==this.name)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),n=`this.name${String(Date.now())}String(Math.random())`;global.localStorage.setItem(n,r),W(()=>{global.localStorage.removeItem(n)},500),G[this.name].forEach(a=>{a!==this&&a.mc.port2.postMessage(JSON.parse(r))})}close(){if(this.closed)return;this.closed=!0,this.mc.port1.close(),this.mc.port2.close(),global.removeEventListener("storage",this.onStorage);let e=G[this.name].indexOf(this);G[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)}},Oe=typeof global.BroadcastChannel=="function"?global.BroadcastChannel:Ne;function Fe(t=0){return new Promise(e=>W(e,t))}var F=(typeof window=="undefined"?"undefined":typeof window)=="object";var E=()=>F?performance.now():Date.now();function Ue(){return E().toString(36).substring(2)}var H;(function(e){e[e.LEADER=0]="LEADER"})(H||(H={}));var M;(function(n){n[n.APPLY=0]="APPLY",n[n.TELL=1]="TELL",n[n.CLOSE=2]="CLOSE"})(M||(M={}));var he=class{constructor(e,r){this.token=Ue();this.isLeader=!1;this.isDead=!1;this.isApplying=!1;this.intervals=[];this.listeners=[];this.channel=e,this.options=r,this.apply=this.apply.bind(this),this.awaitLeadership=this.awaitLeadership.bind(this),this.sendAction=this.sendAction.bind(this)}async apply(){if(this.isLeader||this.isDead||this.isApplying)return!1;this.isApplying=!0;let e=!1,r=n=>{let{ctx:a,token:h,action:I}=n.data;a===0&&h!==this.token&&(I===0&&h>this.token&&(e=!0),I===1&&(e=!0))};this.channel.addEventListener("message",r);try{if(this.sendAction(0),await Fe(this.options.responseTime),e)throw new Error;return this.sendAction(0),this.assumeLead(),this.channel.removeEventListener("message",r),this.isApplying=!1,!0}catch{return!1}}awaitLeadership(){if(this.isLeader)return Promise.resolve();let e=!1,r=null;return new Promise(n=>{let a=()=>{if(e)return;e=!0,fe(r);let I=this.intervals.indexOf(r);this.intervals.splice(I,1),this.channel.removeEventListener("message",h),n()};r=Ce(()=>{this.apply().then(()=>{this.isLeader&&a()})},this.options.fallbackInterval),this.intervals.push(r);let h=I=>{let{ctx:g,action:w}=I.data;g===0&&w===2&&this.apply().then(()=>{this.isLeader&&a()})};this.channel.addEventListener("message",h)})}sendAction(e){this.channel.postMessage({ctx:0,action:e,token:this.token})}assumeLead(){this.isLeader=!0;let e=r=>{let{ctx:n,action:a}=r.data;n===0&&a===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(){this.isDead||(this.isDead=!0,this.isLeader=!1,this.sendAction(2),this.listeners.forEach(e=>this.channel.removeEventListener("message",e)),this.intervals.forEach(e=>fe(e)))}};var m;(function(o){o[o.REGISTER=0]="REGISTER",o[o.DEREGISTER=1]="DEREGISTER",o[o.IDLE=2]="IDLE",o[o.ACTIVE=3]="ACTIVE",o[o.EMIT_IDLE=4]="EMIT_IDLE",o[o.EMIT_ACTIVE=5]="EMIT_ACTIVE",o[o.EMIT_MESSAGE=6]="EMIT_MESSAGE",o[o.START=7]="START",o[o.RESET=8]="RESET",o[o.PAUSE=9]="PAUSE",o[o.RESUME=10]="RESUME",o[o.MESSAGE=11]="MESSAGE"})(m||(m={}));var Te=class{constructor(e){this.isLeader=!1;this.allIdle=!1;this.registry=new Map;let{channelName:r,fallbackInterval:n,responseTime:a}=e;this.options=e,this.channel=new Oe(r),this.elector=new he(this.channel,{fallbackInterval:n,responseTime:a}),this.elector.waitForLeadership().then(()=>{this.isLeader=!0}),this.channel.addEventListener("message",h=>{let{action:I,token:g,data:w}=h.data;switch(I){case 0:this.registry.set(g,!1);break;case 1:this.registry.delete(g);break;case 2:this.idle(g);break;case 3:this.active(g);break;case 4:this.options.onIdle();break;case 5:this.options.onActive();break;case 6:this.options.onMessage(w);break;case 7:this.options.start(!0);break;case 8:this.options.reset(!0);break;case 9:this.options.pause(!0);break;case 10:this.options.resume(!0);break}}),this.send(0)}idle(e=this.elector.token){this.registry.set(e,!0);let r=[...this.registry.values()].every(n=>n);!this.allIdle&&r&&(this.allIdle=!0,this.isLeader?(this.options.onIdle(),this.options.emitOnAllTabs&&this.send(4)):this.send(2))}active(e=this.elector.token){this.registry.set(e,!1);let r=[...this.registry.values()].some(n=>!n);this.allIdle&&r&&(this.allIdle=!1,this.isLeader?(this.options.onActive(),this.options.emitOnAllTabs&&this.send(5)):this.send(3))}message(e){try{this.channel.postMessage({action:6,token:this.elector.token,data:e})}catch{}}send(e){try{this.channel.postMessage({action:e,token:this.elector.token})}catch{}}close(){this.send(1),this.elector.close(),this.channel.close()}};var Be=F?document:null,We=["mousemove","keydown","wheel","DOMMouseScroll","mousewheel","mousedown","touchstart","touchmove","MSPointerDown","MSPointerMove","visibilitychange"];var ie=ne(require("react"));function N(t){let e=(0,ie.useRef)(t);return(0,ie.useEffect)(()=>{e.current=t},[t]),e}function Ge(t,e){let r;function n(...a){r&&clearTimeout(r),r=setTimeout(()=>{t(...a),r=null},e)}return n.cancel=function(){clearTimeout(r)},n}function ve(t,e){let r=0;return function(...n){let a=new Date().getTime();if(!(a-r<e))return r=a,t(...n)}}function B({timeout:t=1e3*60*20,promptTimeout:e=0,element:r=Be,events:n=We,immediateEvents:a=[],onPrompt:h=()=>{},onIdle:I=()=>{},onActive:g=()=>{},onAction:w=()=>{},onMessage:d=()=>{},debounce:l=0,throttle:c=0,eventsThrottle:o=200,startOnMount:f=!0,startManually:p=!1,stopOnIdle:U=!1,crossTab:L=!1,emitOnAllTabs:k=!1}={}){let q=(0,s.useRef)(E()),Ee=(0,s.useRef)(Date.now()),S=(0,s.useRef)(null),R=(0,s.useRef)(null),V=(0,s.useRef)(0),T=(0,s.useRef)(!0),x=(0,s.useRef)(!1),$=(0,s.useRef)(!0),j=(0,s.useRef)(!1),b=(0,s.useRef)(!1),y=(0,s.useRef)(0),P=(0,s.useRef)(0),A=(0,s.useRef)(null),u=(0,s.useRef)(null),le=N(e),je=N(U),Ye=N(a),ue=(0,s.useRef)(n),ze=(0,s.useRef)(r);(0,s.useEffect)(()=>{$.current||(O(),ue.current=n,ze.current=r,C())},[n,r]);let ce=N(I),Q=N(g),Je=N(h),Z=N(d),D=(0,s.useRef)();(0,s.useEffect)(()=>{D.current?.cancel&&D.current.cancel(),l>0?D.current=Ge(w,l):c>0?D.current=ve(w,c):D.current=w},[w,c,l]);let _=()=>{A.current!==null&&(_e(A.current),A.current=null)},Y=(i,v=!0)=>{_(),A.current=W(me,i||t),v&&(R.current=E())},me=i=>{let v=!T.current;if(v){if(le.current>0&&!b.current){O(),y.current=0,P.current=E(),b.current=!0,Je.current(i),Y(le.current,!1);return}T.current=v,je.current?(_(),O()):b.current&&(C(),P.current=0,b.current=!1),S.current=E(),u.current?u.current.idle():ce.current();return}T.current=v,V.current+=E()-S.current,C(),u.current?u.current.active():Q.current(i)},Ie=i=>{D.current(i),_();let v=E()-R.current;if((T.current&&!U||!T.current&&v>t)&&me(i),x.current=!1,y.current=0,P.current=0,!T.current&&Ye.current.includes(i.type)){me(i);return}Y()},ee=(0,s.useRef)();(0,s.useEffect)(()=>{let i=j.current;i&&O(),o>0?ee.current=ve(Ie,o):ee.current=Ie,i&&C()},[o]);let C=()=>{!F||j.current||(ue.current.forEach(i=>{r.addEventListener(i,ee.current,{capture:!0,passive:!0})}),j.current=!0)},O=(i=!1)=>{!F||(j.current||i)&&(ue.current.forEach(v=>{r.removeEventListener(v,ee.current,{capture:!0})}),j.current=!1)},z=(0,s.useCallback)(i=>{_(),C(),T.current=!1,b.current=!1,x.current=!1,y.current=0,P.current=0,u.current&&(u.current.allIdle=!1,!i&&k&&u.current.send(m.START)),Y()},[A,T,t,k]),te=(0,s.useCallback)(i=>{_(),C(),(T.current||b.current)&&(u.current?u.current.active():Q.current()),T.current=!1,b.current=!1,x.current=!1,y.current=0,P.current=0,u.current&&(u.current.allIdle=!1,!i&&k&&u.current.send(m.RESET)),Y()},[A,T,t,k]),de=(0,s.useCallback)((i=!1)=>x.current?!1:(y.current=be(),x.current=!0,O(),_(),u.current&&!i&&k&&u.current.send(m.PAUSE),!0),[A,k,u]),pe=(0,s.useCallback)((i=!1)=>x.current?(x.current=!1,b.current||C(),T.current||Y(y.current),P.current&&(P.current=E()),u.current&&!i&&k&&u.current.send(m.RESUME),!0):!1,[A,y,k,u]),Xe=(0,s.useCallback)((i,v)=>{u.current?(v&&Z.current(i),u.current.message(i)):v&&Z.current(i)},[d]),Ke=(0,s.useCallback)(()=>T.current,[T]),$e=(0,s.useCallback)(()=>b.current,[b]),Qe=(0,s.useCallback)(()=>u.current?u.current.isLeader:!0,[u]),be=(0,s.useCallback)(()=>{if(x.current)return y.current;let i=y.current?y.current:b.current?le.current:t,v=R.current?b.current?E()-P.current:E()-R.current:0,we=Math.ceil(i-v);return we<0?0:Math.abs(we)},[t,e,b,y,R]),ge=(0,s.useCallback)(()=>Math.round(E()-q.current),[q]),Ze=(0,s.useCallback)(()=>S.current?new Date(Ee.current-q.current+S.current):null,[S]),et=(0,s.useCallback)(()=>R.current?new Date(Ee.current-q.current+R.current):null,[R]),ye=(0,s.useCallback)(()=>T.current?Math.round(E()-S.current+V.current):Math.round(V.current),[S,V]),tt=(0,s.useCallback)(()=>{let i=Math.round(ge()-ye());return i>=0?i:0},[q,S,V]);return(0,s.useEffect)(()=>{if(l>0&&c>0)throw new Error("\u274C onAction can either be throttled or debounced, not both.");return()=>{_(),O(!0),D.current.cancel&&D.current.cancel(),u.current&&u.current.close()}},[]),(0,s.useEffect)(()=>{_(),O(!0),$.current||(x.current=!0,T.current=!0,y.current=0),!p&&(f?z():C())},[p,f]),(0,s.useEffect)(()=>{if($.current)$.current=!1;else if(T.current){if(p)return;te()}else z()},[t]),(0,s.useEffect)(()=>{u.current&&u.current.close(),L?u.current=new Te({channelName:"idle-timer",fallbackInterval:2e3,responseTime:100,emitOnAllTabs:k,onIdle:ce.current,onActive:Q.current,onMessage:Z.current,start:z,reset:te,pause:de,resume:pe}):u.current=null},[L,k,ce,Q,Z,z,te,de,pe]),{message:Xe,start:z,reset:te,pause:de,resume:pe,isIdle:Ke,isPrompted:$e,isLeader:Qe,getRemainingTime:be,getElapsedTime:ge,getLastIdleTime:Ze,getLastActiveTime:et,getTotalIdleTime:ye,getTotalActiveTime:tt}}var ae=ne(require("react"));var K=(0,ae.createContext)(null);function He(t){let e=B(t);return React.createElement(K.Provider,{value:e},t.children)}var qe=K.Consumer;function Ve(){return(0,ae.useContext)(K)} | ||
//# sourceMappingURL=index.js.map |
{ | ||
"name": "react-idle-timer", | ||
"version": "5.0.0-rc.1", | ||
"version": "5.0.0-rc.2", | ||
"description": "Activity detection for React.js", | ||
"main": "./dist/index.js", | ||
"module": "./dist/index.mjs", | ||
"types": "./dist/index.d.ts", | ||
"exports": { | ||
".": { | ||
"require": "./dist/index.js", | ||
"import": "./dist/index.mjs", | ||
"types": "./dist/index.d.ts" | ||
} | ||
}, | ||
"scripts": { | ||
@@ -37,2 +45,3 @@ "start": "nps", | ||
"@babel/core": "^7.17.0", | ||
"@next/eslint-plugin-next": "^12.0.10", | ||
"@testing-library/jest-dom": "^5.16.2", | ||
@@ -55,3 +64,2 @@ "@testing-library/react": "^12.1.2", | ||
"jest": "^27.4.7", | ||
"nps-utils": "^1.7.0", | ||
"ts-jest": "^27.1.3", | ||
@@ -58,0 +66,0 @@ "typescript": "^4.5.5", |
Sorry, the diff of this file is not supported yet
Minified code
QualityThis package contains minified code. This may be harmless in some cases where minified code is included in packaged libraries, however packages on npm should not minify code.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
88731
47.44%552
9.52%0
-100%2
100%