Update selected item color in Pass menu
[ProtonMail-WebClient.git] / packages / pass / hooks / useVisibleEffect.ts
blob0c83369ba652281e375666b6c3d24438f65cb604
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;
17     useEffect(() => {
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);
29                 }
30             }, FOCUS_CHECK_DELAY);
31         };
33         window.addEventListener('focus', handler);
34         window.addEventListener('blur', handler);
35         document.addEventListener('visibilitychange', handler);
37         handler();
39         return () => {
40             window.removeEventListener('focus', handler);
41             window.removeEventListener('blur', handler);
42             document.removeEventListener('visibilitychange', handler);
43             return clearTimeout(timer.current);
44         };
45     }, deps);