1 | import { useEffect, useState } from 'react';
|
---|
2 | import { throttle } from 'throttle-debounce';
|
---|
3 | import { off, on } from './misc/util';
|
---|
4 | var defaultEvents = ['mousemove', 'mousedown', 'resize', 'keydown', 'touchstart', 'wheel'];
|
---|
5 | var oneMinute = 60e3;
|
---|
6 | var useIdle = function (ms, initialState, events) {
|
---|
7 | if (ms === void 0) { ms = oneMinute; }
|
---|
8 | if (initialState === void 0) { initialState = false; }
|
---|
9 | if (events === void 0) { events = defaultEvents; }
|
---|
10 | var _a = useState(initialState), state = _a[0], setState = _a[1];
|
---|
11 | useEffect(function () {
|
---|
12 | var mounted = true;
|
---|
13 | var timeout;
|
---|
14 | var localState = state;
|
---|
15 | var set = function (newState) {
|
---|
16 | if (mounted) {
|
---|
17 | localState = newState;
|
---|
18 | setState(newState);
|
---|
19 | }
|
---|
20 | };
|
---|
21 | var onEvent = throttle(50, function () {
|
---|
22 | if (localState) {
|
---|
23 | set(false);
|
---|
24 | }
|
---|
25 | clearTimeout(timeout);
|
---|
26 | timeout = setTimeout(function () { return set(true); }, ms);
|
---|
27 | });
|
---|
28 | var onVisibility = function () {
|
---|
29 | if (!document.hidden) {
|
---|
30 | onEvent();
|
---|
31 | }
|
---|
32 | };
|
---|
33 | for (var i = 0; i < events.length; i++) {
|
---|
34 | on(window, events[i], onEvent);
|
---|
35 | }
|
---|
36 | on(document, 'visibilitychange', onVisibility);
|
---|
37 | timeout = setTimeout(function () { return set(true); }, ms);
|
---|
38 | return function () {
|
---|
39 | mounted = false;
|
---|
40 | for (var i = 0; i < events.length; i++) {
|
---|
41 | off(window, events[i], onEvent);
|
---|
42 | }
|
---|
43 | off(document, 'visibilitychange', onVisibility);
|
---|
44 | };
|
---|
45 | }, [ms, events]);
|
---|
46 | return state;
|
---|
47 | };
|
---|
48 | export default useIdle;
|
---|