Skip to content

Commit

Permalink
Merge pull request #59 from spacemeshos/fix-unfocused-locking
Browse files Browse the repository at this point in the history
Lock on unfocused app after 2 min + 30 seconds countdown
  • Loading branch information
brusherru authored Aug 4, 2024
2 parents 83580ab + 168b3e1 commit 8a6da4c
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 13 deletions.
2 changes: 1 addition & 1 deletion src/components/IdleAlert.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ function IdleAlert(): JSX.Element {
const { isWalletUnlocked } = useWallet();
const lockWallet = useLockWallet();
const isIdle = useIdle(IDLE_TIME_SECONDS * 1000);
const isFocused = useWindowFocus();
const isFocused = useWindowFocus(IDLE_TIME_SECONDS * 1000);
const [showModal, setShowModal] = useState(false);
const [countdown, setCountdown] = useState(IDLE_ALERT_SECONDS);
const [shouldLockWallet, setShouldLockWallet] = useState(false);
Expand Down
25 changes: 13 additions & 12 deletions src/hooks/useWindowFocus.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,32 @@
import { useEffect, useState } from 'react';
import { useEffect, useRef, useState } from 'react';

function useWindowFocus() {
function useWindowFocus(timeout = 0) {
const [focused, setFocused] = useState(true);
const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);

useEffect(() => {
const focusHandler = () => {
if (import.meta.env.DEV) {
// eslint-disable-next-line no-console
console.log('Window is focused');
return;
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
setFocused(true);
};
const blurHandler = () => {
if (import.meta.env.DEV) {
// eslint-disable-next-line no-console
console.log('Window is blurred');
return;
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
setFocused(false);
timeoutRef.current = setTimeout(() => {
setFocused(false);
timeoutRef.current = null;
}, timeout);
};
window.addEventListener('focus', focusHandler);
window.addEventListener('blur', blurHandler);
return () => {
window.removeEventListener('focus', focusHandler);
window.removeEventListener('blur', blurHandler);
};
}, []);
}, [timeout]);

return focused;
}
Expand Down

0 comments on commit 8a6da4c

Please sign in to comment.