Open History to see the last commit
1import { Subscribable } from './subscribable'
2import { isServer } from './utils'
3β
4type Listener = (focused: boolean) => void
5β
6type SetupFn = (
7 setFocused: (focused?: boolean) => void,
8) => (() => void) | undefined
9β
10export class FocusManager extends Subscribable<Listener> {
11 #focused?: boolean
12 #cleanup?: () => void
13β
14 #setup: SetupFn
15β
16 constructor() {
17 super()
18 this.#setup = (onFocus) => {
19 // addEventListener does not exist in React Native, but window does
20 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
21 if (!isServer && window.addEventListener) {
22 const listener = () => onFocus()
23 // Listen to visibilitychange
24 window.addEventListener('visibilitychange', listener, false)
25β
26 return () => {
27 // Be sure to unsubscribe if a new handler is set
28 window.removeEventListener('visibilitychange', 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 const isFocused = this.isFocused()
70 this.listeners.forEach((listener) => {
71 listener(isFocused)
72 })
73 }
74β
75 isFocused(): boolean {
76 if (typeof this.#focused === 'boolean') {
77 return this.#focused
78 }
79β
80 // document global can be unavailable in react native
81 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
82 return globalThis.document?.visibilityState !== 'hidden'
83 }
84}
85β
86export const focusManager = new FocusManager()