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

focusManager.ts

75 lines1.8 KB

1import { Subscribable } from './subscribable'
2import { isServer } from './utils'
3​
4class FocusManager extends Subscribable {
5 private focused?: boolean
6 private removeEventListener?: () => void
7​
8 protected onSubscribe(): void {
9 if (!this.removeEventListener) {
10 this.setDefaultEventListener()
11 }
12 }
13​
14 setEventListener(
15 setup: (onFocus: () => void) => (focused?: boolean) => void
16 ): void {
17 if (this.removeEventListener) {
18 this.removeEventListener()
19 }
20 this.removeEventListener = setup((focused?: boolean) => {
21 if (typeof focused === 'boolean') {
22 this.setFocused(focused)
23 } else {
24 this.onFocus()
25 }
26 })
27 }
28​
29 setFocused(focused?: boolean): void {
30 this.focused = focused
31​
32 if (focused) {
33 this.onFocus()
34 }
35 }
36​
37 onFocus(): void {
38 this.listeners.forEach(listener => {
39 listener()
40 })
41 }
42​
43 isFocused(): boolean {
44 if (typeof this.focused === 'boolean') {
45 return this.focused
46 }
47​
48 // document global can be unavailable in react native
49 if (typeof document === 'undefined') {
50 return true
51 }
52​
53 return [undefined, 'visible', 'prerender'].includes(
54 document.visibilityState
55 )
56 }
57​
58 private setDefaultEventListener() {
59 if (!isServer && window?.addEventListener) {
60 this.setEventListener(onFocus => {
61 // Listen to visibillitychange and focus
62 window.addEventListener('visibilitychange', onFocus, false)
63 window.addEventListener('focus', onFocus, false)
64​
65 return () => {
66 // Be sure to unsubscribe if a new handler is set
67 window.removeEventListener('visibilitychange', onFocus)
68 window.removeEventListener('focus', onFocus)
69 }
70 })
71 }
72 }
74​
75export const focusManager = new FocusManager()