browser-window-hook.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import { useEffect, useState } from 'react'
  2. let titleIsFlashing = false
  3. let originalTitle
  4. let flashIntervalHandle
  5. export function flashTitle(message) {
  6. if (document.hasFocus() || titleIsFlashing) {
  7. return
  8. }
  9. function swapTitle() {
  10. if (window.document.title === originalTitle) {
  11. window.document.title = message
  12. } else {
  13. window.document.title = originalTitle
  14. }
  15. }
  16. originalTitle = window.document.title
  17. window.document.title = message
  18. titleIsFlashing = true
  19. flashIntervalHandle = setInterval(swapTitle, 800)
  20. }
  21. export function stopFlashingTitle() {
  22. if (!titleIsFlashing) {
  23. return
  24. }
  25. clearInterval(flashIntervalHandle)
  26. window.document.title = originalTitle
  27. originalTitle = undefined
  28. titleIsFlashing = false
  29. }
  30. function useBrowserWindow() {
  31. const [hasFocus, setHasFocus] = useState(document.hasFocus())
  32. useEffect(() => {
  33. function handleFocusEvent() {
  34. setHasFocus(true)
  35. }
  36. function handleBlurEvent() {
  37. setHasFocus(false)
  38. }
  39. window.addEventListener('focus', handleFocusEvent)
  40. window.addEventListener('blur', handleBlurEvent)
  41. return () => {
  42. window.removeEventListener('focus', handleFocusEvent)
  43. window.removeEventListener('blur', handleBlurEvent)
  44. }
  45. }, [])
  46. return { hasFocus, flashTitle, stopFlashingTitle }
  47. }
  48. export default useBrowserWindow