Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

focusManager.ts

85 lines2.0 KB

1import { Subscribable } from './subscribable'
2​
3type Listener = (focused: boolean) => void
4​
5type SetupFn = (
6 setFocused: (focused?: boolean) => void,
7) => (() => void) | undefined
8​
9export class FocusManager extends Subscribable<Listener> {
10 #focused?: boolean
11 #cleanup?: () => void
12​
13 #setup: SetupFn
14​
15 constructor() {
16 super()
17 this.#setup = (onFocus) => {
18 // addEventListener does not exist in React Native, but window does
19 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
20 if (typeof window !== 'undefined' && window.addEventListener) {
21 const listener = () => onFocus()
22 // Listen to visibilitychange
23 window.addEventListener('visibilitychange', listener, false)
24​
25 return () => {
26 // Be sure to unsubscribe if a new handler is set
27 window.removeEventListener('visibilitychange', listener)
28 }
29 }
30 return
31 }
32 }
33​
34 protected onSubscribe(): void {
35 if (!this.#cleanup) {
36 this.setEventListener(this.#setup)
37 }
38 }
39​
40 protected onUnsubscribe() {
41 if (!this.hasListeners()) {
42 this.#cleanup?.()
43 this.#cleanup = undefined
44 }
45 }
46​
47 setEventListener(setup: SetupFn): void {
48 this.#setup = setup
49 this.#cleanup?.()
50 this.#cleanup = setup((focused) => {
51 if (typeof focused === 'boolean') {
52 this.setFocused(focused)
53 } else {
54 this.onFocus()
55 }
56 })
57 }
58​
59 setFocused(focused?: boolean): void {
60 const changed = this.#focused !== focused
61 if (changed) {
62 this.#focused = focused
63 this.onFocus()
64 }
65 }
66​
67 onFocus(): void {
68 const isFocused = this.isFocused()
69 this.listeners.forEach((listener) => {
70 listener(isFocused)
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 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
81 return globalThis.document?.visibilityState !== 'hidden'
82 }
84​
85export const focusManager = new FocusManager()