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

focusManager.ts

86 lines2.1 KB

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 }
85​
86export const focusManager = new FocusManager()