Open History to see the last commit
1import { Store } from '@tanstack/store'
2import { isServer } from './utils'
3β
4type SetupFn = (
5 setFocused: (focused?: boolean) => void,
6) => (() => void) | undefined
7β
8export class FocusManager {
9 store = new Store<boolean | undefined>(undefined, {
10 onSubscribe: () => {
11 if (!this.#cleanup) this.setEventListener(this.#setup)
12β
13 return () => {
14 if (!this.store.listeners.size) {
15 this.#cleanup?.()
16 this.#cleanup = undefined;
17 }
18 }
19 },
20 })
21β
22 #cleanup?: () => void
23β
24 #setup: SetupFn = (onFocus) => {
25 // addEventListener does not exist in React Native, but window does
26 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
27 if (!isServer && window.addEventListener) {
28 const listener = () => onFocus()
29 // Listen to visibilitychange
30 window.addEventListener('visibilitychange', listener, false)
31β
32 return () => {
33 // Be sure to unsubscribe if a new handler is set
34 window.removeEventListener('visibilitychange', listener)
35 }
36 }
37 return
38 }
39β
40 setEventListener(setup: SetupFn): void {
41 this.#setup = setup
42 this.#cleanup?.()
43 this.#cleanup = setup(this.setFocused.bind(this))
44 }
45β
46 setFocused(focused?: boolean): void {
47 const changed = this.store.state !== focused;
48 if (!changed) return;
49 this.store.setState(() => focused)
50 }
51β
52 subscribe(fn: () => void) {
53 return this.store.subscribe(fn);
54 }
55β
56 isFocused(): boolean {
57 if (typeof this.store.state === 'boolean') {
58 return this.store.state
59 }
60β
61 // document global can be unavailable in react native
62 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
63 return globalThis.document?.visibilityState !== 'hidden'
64 }
65}
66β
67export const focusManager = new FocusManager()