2020-05-26 20:35:05 +03:00
|
|
|
import { useCallback, useEffect, useState } from 'react'
|
|
|
|
|
2020-07-25 18:41:03 +03:00
|
|
|
const VISIBILITY_STATE_SUPPORTED = 'visibilityState' in document
|
|
|
|
|
|
|
|
function isWindowVisible() {
|
|
|
|
return !VISIBILITY_STATE_SUPPORTED || document.visibilityState !== 'hidden'
|
|
|
|
}
|
|
|
|
|
2020-05-26 20:35:05 +03:00
|
|
|
/**
|
|
|
|
* Returns whether the window is currently visible to the user.
|
|
|
|
*/
|
|
|
|
export default function useIsWindowVisible(): boolean {
|
2020-07-25 18:41:03 +03:00
|
|
|
const [focused, setFocused] = useState<boolean>(isWindowVisible())
|
2020-05-26 20:35:05 +03:00
|
|
|
const listener = useCallback(() => {
|
2020-07-25 18:41:03 +03:00
|
|
|
setFocused(isWindowVisible())
|
2020-05-26 20:35:05 +03:00
|
|
|
}, [setFocused])
|
|
|
|
|
|
|
|
useEffect(() => {
|
2020-07-25 18:41:03 +03:00
|
|
|
if (!VISIBILITY_STATE_SUPPORTED) return
|
|
|
|
|
2020-05-26 20:35:05 +03:00
|
|
|
document.addEventListener('visibilitychange', listener)
|
|
|
|
return () => {
|
|
|
|
document.removeEventListener('visibilitychange', listener)
|
|
|
|
}
|
|
|
|
}, [listener])
|
|
|
|
|
|
|
|
return focused
|
|
|
|
}
|