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

focusManager.ts

89 lines2.1 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 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 }
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 this.focused = focused
61​
62 if (focused) {
63 this.onFocus()
64 }
65 }
66​
67 onFocus(): void {
68 this.listeners.forEach((listener) => {
69 listener()
70 })
71 }
72​
73 isFocused(): boolean {
74 if (typeof this.focused === 'boolean') {
75 return this.focused
76 }
77​
78 // document global can be unavailable in react native
79 if (typeof document === 'undefined') {
80 return true
81 }
82​
83 return [undefined, 'visible', 'prerender'].includes(
84 document.visibilityState,
85 )
86 }
88​
89export const focusManager = new FocusManager()