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

focusManager.ts

87 lines1.9 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 if (!isServer && window?.addEventListener) {
18 const listener = () => onFocus()
19 // Listen to visibillitychange and focus
20 window.addEventListener('visibilitychange', listener, false)
21 window.addEventListener('focus', listener, false)
22​
23 return () => {
24 // Be sure to unsubscribe if a new handler is set
25 window.removeEventListener('visibilitychange', listener)
26 window.removeEventListener('focus', listener)
27 }
28 }
29 }
30 }
31​
32 protected onSubscribe(): void {
33 if (!this.cleanup) {
34 this.setEventListener(this.setup)
35 }
36 }
37​
38 protected onUnsubscribe() {
39 if (!this.hasListeners()) {
40 this.cleanup?.()
41 this.cleanup = undefined
42 }
43 }
44​
45 setEventListener(setup: SetupFn): void {
46 this.setup = setup
47 this.cleanup?.()
48 this.cleanup = setup(focused => {
49 if (typeof focused === 'boolean') {
50 this.setFocused(focused)
51 } else {
52 this.onFocus()
53 }
54 })
55 }
56​
57 setFocused(focused?: boolean): void {
58 this.focused = focused
59​
60 if (focused) {
61 this.onFocus()
62 }
63 }
64​
65 onFocus(): void {
66 this.listeners.forEach(listener => {
67 listener()
68 })
69 }
70​
71 isFocused(): boolean {
72 if (typeof this.focused === 'boolean') {
73 return this.focused
74 }
75​
76 // document global can be unavailable in react native
77 if (typeof document === 'undefined') {
78 return true
79 }
80​
81 return [undefined, 'visible', 'prerender'].includes(
82 document.visibilityState
83 )
84 }
86​
87export const focusManager = new FocusManager()