2021-02-09 10:37:48 -05:00
|
|
|
import { useEffect, useState } from 'react'
|
|
|
|
|
|
|
|
let titleIsFlashing = false
|
2023-01-09 09:33:43 -05:00
|
|
|
let originalTitle = ''
|
|
|
|
let flashIntervalHandle: ReturnType<typeof setInterval>
|
2021-02-09 10:37:48 -05:00
|
|
|
|
2023-01-09 09:33:43 -05:00
|
|
|
function flashTitle(message: string) {
|
2021-02-09 10:37:48 -05:00
|
|
|
if (document.hasFocus() || titleIsFlashing) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
function swapTitle() {
|
|
|
|
if (window.document.title === originalTitle) {
|
|
|
|
window.document.title = message
|
|
|
|
} else {
|
|
|
|
window.document.title = originalTitle
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
originalTitle = window.document.title
|
|
|
|
window.document.title = message
|
|
|
|
titleIsFlashing = true
|
|
|
|
flashIntervalHandle = setInterval(swapTitle, 800)
|
|
|
|
}
|
|
|
|
|
2021-03-10 07:19:54 -05:00
|
|
|
function stopFlashingTitle() {
|
2021-02-09 10:37:48 -05:00
|
|
|
if (!titleIsFlashing) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
clearInterval(flashIntervalHandle)
|
|
|
|
window.document.title = originalTitle
|
2023-01-09 09:33:43 -05:00
|
|
|
originalTitle = ''
|
2021-02-09 10:37:48 -05:00
|
|
|
titleIsFlashing = false
|
|
|
|
}
|
|
|
|
|
2023-01-09 09:33:43 -05:00
|
|
|
function setTitle(title: string) {
|
2021-03-10 07:19:54 -05:00
|
|
|
if (titleIsFlashing) {
|
|
|
|
originalTitle = title
|
|
|
|
} else {
|
|
|
|
window.document.title = title
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-02-09 10:37:48 -05:00
|
|
|
function useBrowserWindow() {
|
2024-02-01 04:41:12 -05:00
|
|
|
const [hasFocus, setHasFocus] = useState(() => document.hasFocus())
|
2021-02-09 10:37:48 -05:00
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
function handleFocusEvent() {
|
|
|
|
setHasFocus(true)
|
|
|
|
}
|
|
|
|
|
|
|
|
function handleBlurEvent() {
|
|
|
|
setHasFocus(false)
|
|
|
|
}
|
|
|
|
|
|
|
|
window.addEventListener('focus', handleFocusEvent)
|
|
|
|
window.addEventListener('blur', handleBlurEvent)
|
|
|
|
return () => {
|
|
|
|
window.removeEventListener('focus', handleFocusEvent)
|
|
|
|
window.removeEventListener('blur', handleBlurEvent)
|
|
|
|
}
|
|
|
|
}, [])
|
|
|
|
|
2021-03-10 07:19:54 -05:00
|
|
|
return { hasFocus, flashTitle, stopFlashingTitle, setTitle }
|
2021-02-09 10:37:48 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
export default useBrowserWindow
|