1 import { useEffect, useRef } from 'react';
3 import type { Maybe } from '@proton/pass/types/utils';
5 const FOCUS_CHECK_DELAY = 10;
7 export const isDocumentVisible = () => document.visibilityState === 'visible';
8 export const isDocumentFocused = () => document.hasFocus();
10 export const useVisibleEffect = (effect: (visible: boolean) => void, deps: any[] = []) => {
11 const timer = useRef<Maybe<NodeJS.Timeout>>();
12 const active = useRef<boolean>(false);
14 const onVisibilityChange = useRef(effect);
15 onVisibilityChange.current = effect;
18 active.current = false;
20 const handler = () => {
21 clearTimeout(timer.current);
22 timer.current = setTimeout(() => {
23 const wasActive = active.current;
24 const isActive = isDocumentVisible() || isDocumentFocused();
26 if (wasActive !== isActive) {
27 active.current = isActive;
28 onVisibilityChange.current(isActive);
30 }, FOCUS_CHECK_DELAY);
33 window.addEventListener('focus', handler);
34 window.addEventListener('blur', handler);
35 document.addEventListener('visibilitychange', handler);
40 window.removeEventListener('focus', handler);
41 window.removeEventListener('blur', handler);
42 document.removeEventListener('visibilitychange', handler);
43 return clearTimeout(timer.current);