Open History to see the last commit
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: (setFocused: (focused?: boolean) => void) => () => void
16 ): void {
17 if (this.removeEventListener) {
18 this.removeEventListener()
19 }
20 this.removeEventListener = setup(focused => {
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 const listener = () => onFocus()
62 // Listen to visibillitychange and focus
63 window.addEventListener('visibilitychange', listener, false)
64 window.addEventListener('focus', listener, false)
65β
66 return () => {
67 // Be sure to unsubscribe if a new handler is set
68 window.removeEventListener('visibilitychange', listener)
69 window.removeEventListener('focus', listener)
70 }
71 })
72 }
73 }
74}
75β
76export const focusManager = new FocusManager()