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