zy-react-library 1.0.158 → 1.0.159
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/hooks/useIdle/index.d.ts +11 -0
- package/hooks/useIdle/index.js +51 -0
- package/package.json +1 -1
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export interface UseIdleOptions {
|
|
2
|
+
/** 空闲超时时间(毫秒),默认值 10000 */
|
|
3
|
+
timeout?: number;
|
|
4
|
+
/** 监听的事件列表,默认值 ['mousedown', 'mousemove', 'keypress', 'scroll', 'touchstart', 'wheel'] */
|
|
5
|
+
events?: string[];
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* 检测用户是否处于空闲状态
|
|
10
|
+
*/
|
|
11
|
+
export default function useIdle(options?: UseIdleOptions): boolean;
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { useEffect, useState } from "react";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* 检测用户是否处于空闲状态
|
|
5
|
+
*/
|
|
6
|
+
function useIdle(options = {}) {
|
|
7
|
+
const {
|
|
8
|
+
timeout = 10000,
|
|
9
|
+
events = [
|
|
10
|
+
"mousedown",
|
|
11
|
+
"mousemove",
|
|
12
|
+
"keypress",
|
|
13
|
+
"scroll",
|
|
14
|
+
"touchstart",
|
|
15
|
+
"wheel",
|
|
16
|
+
],
|
|
17
|
+
} = options;
|
|
18
|
+
|
|
19
|
+
const [isIdle, setIsIdle] = useState(false);
|
|
20
|
+
|
|
21
|
+
useEffect(() => {
|
|
22
|
+
let idleTimer;
|
|
23
|
+
|
|
24
|
+
// 重置空闲计时器
|
|
25
|
+
const resetTimer = () => {
|
|
26
|
+
setIsIdle(false);
|
|
27
|
+
clearTimeout(idleTimer);
|
|
28
|
+
idleTimer = setTimeout(() => setIsIdle(true), timeout);
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
// 初始化计时器
|
|
32
|
+
resetTimer();
|
|
33
|
+
|
|
34
|
+
// 添加事件监听器
|
|
35
|
+
events.forEach((event) => {
|
|
36
|
+
window.addEventListener(event, resetTimer, { passive: true });
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
// 清理函数
|
|
40
|
+
return () => {
|
|
41
|
+
clearTimeout(idleTimer);
|
|
42
|
+
events.forEach((event) => {
|
|
43
|
+
window.removeEventListener(event, resetTimer);
|
|
44
|
+
});
|
|
45
|
+
};
|
|
46
|
+
}, [timeout, events]);
|
|
47
|
+
|
|
48
|
+
return isIdle;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export default useIdle;
|