zy-react-library 1.0.159 → 1.0.160
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 +1 -1
- package/hooks/useIdle/index.js +32 -16
- package/package.json +1 -1
package/hooks/useIdle/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
export interface UseIdleOptions {
|
|
2
2
|
/** 空闲超时时间(毫秒),默认值 10000 */
|
|
3
3
|
timeout?: number;
|
|
4
|
-
/** 监听的事件列表,默认值 [
|
|
4
|
+
/** 监听的事件列表,默认值 ["mousemove", "mousedown", "resize", "keydown", "touchstart", "wheel"] */
|
|
5
5
|
events?: string[];
|
|
6
6
|
}
|
|
7
7
|
|
package/hooks/useIdle/index.js
CHANGED
|
@@ -6,14 +6,7 @@ import { useEffect, useState } from "react";
|
|
|
6
6
|
function useIdle(options = {}) {
|
|
7
7
|
const {
|
|
8
8
|
timeout = 10000,
|
|
9
|
-
events = [
|
|
10
|
-
"mousedown",
|
|
11
|
-
"mousemove",
|
|
12
|
-
"keypress",
|
|
13
|
-
"scroll",
|
|
14
|
-
"touchstart",
|
|
15
|
-
"wheel",
|
|
16
|
-
],
|
|
9
|
+
events = ["mousemove", "mousedown", "resize", "keydown", "touchstart", "wheel"],
|
|
17
10
|
} = options;
|
|
18
11
|
|
|
19
12
|
const [isIdle, setIsIdle] = useState(false);
|
|
@@ -21,29 +14,52 @@ function useIdle(options = {}) {
|
|
|
21
14
|
useEffect(() => {
|
|
22
15
|
let idleTimer;
|
|
23
16
|
|
|
24
|
-
//
|
|
25
|
-
const
|
|
17
|
+
// 设置空闲状态
|
|
18
|
+
const setIdle = () => {
|
|
19
|
+
setIsIdle(true);
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
// 重置为空闲前的状态
|
|
23
|
+
const setActive = () => {
|
|
26
24
|
setIsIdle(false);
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
// 重置计时器
|
|
28
|
+
const resetTimer = () => {
|
|
27
29
|
clearTimeout(idleTimer);
|
|
28
|
-
idleTimer = setTimeout(
|
|
30
|
+
idleTimer = setTimeout(setIdle, timeout);
|
|
29
31
|
};
|
|
30
32
|
|
|
31
|
-
//
|
|
32
|
-
|
|
33
|
+
// 初始化计时器(仅在非空闲状态下)
|
|
34
|
+
if (!isIdle) {
|
|
35
|
+
resetTimer();
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// 事件处理函数
|
|
39
|
+
const handleUserActivity = () => {
|
|
40
|
+
// 如果当前是空闲状态,用户操作后重置为活跃状态
|
|
41
|
+
if (isIdle) {
|
|
42
|
+
setActive();
|
|
43
|
+
}
|
|
44
|
+
else {
|
|
45
|
+
// 如果当前是活跃状态,重置计时器
|
|
46
|
+
resetTimer();
|
|
47
|
+
}
|
|
48
|
+
};
|
|
33
49
|
|
|
34
50
|
// 添加事件监听器
|
|
35
51
|
events.forEach((event) => {
|
|
36
|
-
window.addEventListener(event,
|
|
52
|
+
window.addEventListener(event, handleUserActivity, { passive: true });
|
|
37
53
|
});
|
|
38
54
|
|
|
39
55
|
// 清理函数
|
|
40
56
|
return () => {
|
|
41
57
|
clearTimeout(idleTimer);
|
|
42
58
|
events.forEach((event) => {
|
|
43
|
-
window.removeEventListener(event,
|
|
59
|
+
window.removeEventListener(event, handleUserActivity);
|
|
44
60
|
});
|
|
45
61
|
};
|
|
46
|
-
}, [timeout, events]);
|
|
62
|
+
}, [timeout, events, isIdle]);
|
|
47
63
|
|
|
48
64
|
return isIdle;
|
|
49
65
|
}
|