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-08-27 20:05:09 +03:00
|
|
|
if (!VISIBILITY_STATE_SUPPORTED) return undefined
|
2020-07-25 18:41:03 +03:00
|
|
|
|
2020-05-26 20:35:05 +03:00
|
|
|
document.addEventListener('visibilitychange', listener)
|
|
|
|
return () => {
|
|
|
|
document.removeEventListener('visibilitychange', listener)
|
|
|
|
}
|
|
|
|
}, [listener])
|
|
|
|
|
|
|
|
return focused
|
|
|
|
}
|