feat: Add idle detection and disconnect collaboration socket (#2629)
This commit is contained in:
54
app/hooks/useIdle.js
Normal file
54
app/hooks/useIdle.js
Normal file
@@ -0,0 +1,54 @@
|
||||
// @flow
|
||||
import * as React from "react";
|
||||
|
||||
const activityEvents = [
|
||||
"click",
|
||||
"mousemove",
|
||||
"keydown",
|
||||
"DOMMouseScroll",
|
||||
"mousewheel",
|
||||
"mousedown",
|
||||
"touchstart",
|
||||
"touchmove",
|
||||
"focus",
|
||||
];
|
||||
|
||||
/**
|
||||
* Hook to detect user idle state.
|
||||
*
|
||||
* @param {number} timeToIdle
|
||||
* @returns boolean if the user is idle
|
||||
*/
|
||||
export default function useIdle(timeToIdle: number = 3 * 60 * 1000) {
|
||||
const [isIdle, setIsIdle] = React.useState(false);
|
||||
const timeout = React.useRef();
|
||||
|
||||
const onActivity = React.useCallback(() => {
|
||||
if (timeout.current) {
|
||||
clearTimeout(timeout.current);
|
||||
}
|
||||
|
||||
timeout.current = setTimeout(() => {
|
||||
setIsIdle(true);
|
||||
}, timeToIdle);
|
||||
}, [timeToIdle]);
|
||||
|
||||
React.useEffect(() => {
|
||||
const handleUserActivityEvent = () => {
|
||||
setIsIdle(false);
|
||||
onActivity();
|
||||
};
|
||||
|
||||
activityEvents.forEach((eventName) =>
|
||||
window.addEventListener(eventName, handleUserActivityEvent)
|
||||
);
|
||||
|
||||
return () => {
|
||||
activityEvents.forEach((eventName) =>
|
||||
window.removeEventListener(eventName, handleUserActivityEvent)
|
||||
);
|
||||
};
|
||||
}, [onActivity]);
|
||||
|
||||
return isIdle;
|
||||
}
|
||||
22
app/hooks/usePageVisibility.js
Normal file
22
app/hooks/usePageVisibility.js
Normal file
@@ -0,0 +1,22 @@
|
||||
// @flow
|
||||
import * as React from "react";
|
||||
|
||||
/**
|
||||
* Hook to return page visibility state.
|
||||
*
|
||||
* @returns boolean if the page is visible
|
||||
*/
|
||||
export default function usePageVisibility(): boolean {
|
||||
const [visible, setVisible] = React.useState(true);
|
||||
|
||||
React.useEffect(() => {
|
||||
const handleVisibilityChange = () => setVisible(!document.hidden);
|
||||
document.addEventListener("visibilitychange", handleVisibilityChange);
|
||||
|
||||
return () => {
|
||||
document.removeEventListener("visibilitychange", handleVisibilityChange);
|
||||
};
|
||||
}, []);
|
||||
|
||||
return visible;
|
||||
}
|
||||
Reference in New Issue
Block a user