Open History to see the last commit
1import { Subscribable } from './subscribable'
2import { isServer } from './utils'
3β
4type SetupFn = (
5 setFocused: (focused?: boolean) => void,
6) => (() => void) | undefined
7β
8export class FocusManager extends Subscribable {
9 private focused?: boolean
10 private cleanup?: () => void
11β
12 private setup: SetupFn
13β
14 constructor() {
15 super()
16 this.setup = (onFocus) => {
17 // addEventListener does not exist in React Native, but window does
18 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
19 if (!isServer && window.addEventListener) {
20 const listener = () => onFocus()
21 // Listen to visibillitychange and focus
22 window.addEventListener('visibilitychange', listener, false)
23 window.addEventListener('focus', listener, false)
24β
25 return () => {
26 // Be sure to unsubscribe if a new handler is set
27 window.removeEventListener('visibilitychange', listener)
28 window.removeEventListener('focus', listener)
29 }
30 }
31 return
32 }
33 }
34β
35 protected onSubscribe(): void {
36 if (!this.cleanup) {
37 this.setEventListener(this.setup)
38 }
39 }
40β
41 protected onUnsubscribe() {
42 if (!this.hasListeners()) {
43 this.cleanup?.()
44 this.cleanup = undefined
45 }
46 }
47β
48 setEventListener(setup: SetupFn): void {
49 this.setup = setup
50 this.cleanup?.()
51 this.cleanup = setup((focused) => {
52 if (typeof focused === 'boolean') {
53 this.setFocused(focused)
54 } else {
55 this.onFocus()
56 }
57 })
58 }
59β
60 setFocused(focused?: boolean): void {
61 const changed = this.focused !== focused
62 if (changed) {
63 this.focused = focused
64 this.onFocus()
65 }
66 }
67β
68 onFocus(): void {
69 this.listeners.forEach(({ listener }) => {
70 listener()
71 })
72 }
73β
74 isFocused(): boolean {
75 if (typeof this.focused === 'boolean') {
76 return this.focused
77 }
78β
79 // document global can be unavailable in react native
80 if (typeof document === 'undefined') {
81 return true
82 }
83β
84 return [undefined, 'visible', 'prerender'].includes(
85 document.visibilityState,
86 )
87 }
88}
89β
90export const focusManager = new FocusManager()