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

focusManager.ts

83 lines2.0 KB

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 #focused?: boolean
10 #cleanup?: () => void
11​
12 #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 visibilitychange
22 window.addEventListener('visibilitychange', listener, false)
23​
24 return () => {
25 // Be sure to unsubscribe if a new handler is set
26 window.removeEventListener('visibilitychange', listener)
27 }
28 }
29 return
30 }
31 }
32​
33 protected onSubscribe(): void {
34 if (!this.#cleanup) {
35 this.setEventListener(this.#setup)
36 }
37 }
38​
39 protected onUnsubscribe() {
40 if (!this.hasListeners()) {
41 this.#cleanup?.()
42 this.#cleanup = undefined
43 }
44 }
45​
46 setEventListener(setup: SetupFn): void {
47 this.#setup = setup
48 this.#cleanup?.()
49 this.#cleanup = setup((focused) => {
50 if (typeof focused === 'boolean') {
51 this.setFocused(focused)
52 } else {
53 this.onFocus()
54 }
55 })
56 }
57​
58 setFocused(focused?: boolean): void {
59 const changed = this.#focused !== focused
60 if (changed) {
61 this.#focused = focused
62 this.onFocus()
63 }
64 }
65​
66 onFocus(): void {
67 this.listeners.forEach((listener) => {
68 listener()
69 })
70 }
71​
72 isFocused(): boolean {
73 if (typeof this.#focused === 'boolean') {
74 return this.#focused
75 }
76​
77 // document global can be unavailable in react native
78 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
79 return globalThis.document?.visibilityState !== 'hidden'
80 }
82​
83export const focusManager = new FocusManager()