1 | import type {
|
2 | ThunkDispatch,
|
3 | ActionCreatorWithoutPayload,
|
4 | } from '@reduxjs/toolkit'
|
5 | import { createAction } from './rtkImports'
|
6 |
|
7 | export const onFocus = createAction('__rtkq/focused')
|
8 | export const onFocusLost = createAction('__rtkq/unfocused')
|
9 | export const onOnline = createAction('__rtkq/online')
|
10 | export const onOffline = createAction('__rtkq/offline')
|
11 |
|
12 | let initialized = false
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 | export function setupListeners(
|
31 | dispatch: ThunkDispatch<any, any, any>,
|
32 | customHandler?: (
|
33 | dispatch: ThunkDispatch<any, any, any>,
|
34 | actions: {
|
35 | onFocus: typeof onFocus
|
36 | onFocusLost: typeof onFocusLost
|
37 | onOnline: typeof onOnline
|
38 | onOffline: typeof onOffline
|
39 | },
|
40 | ) => () => void,
|
41 | ) {
|
42 | function defaultHandler() {
|
43 | const handleFocus = () => dispatch(onFocus())
|
44 | const handleFocusLost = () => dispatch(onFocusLost())
|
45 | const handleOnline = () => dispatch(onOnline())
|
46 | const handleOffline = () => dispatch(onOffline())
|
47 | const handleVisibilityChange = () => {
|
48 | if (window.document.visibilityState === 'visible') {
|
49 | handleFocus()
|
50 | } else {
|
51 | handleFocusLost()
|
52 | }
|
53 | }
|
54 |
|
55 | if (!initialized) {
|
56 | if (typeof window !== 'undefined' && window.addEventListener) {
|
57 |
|
58 | window.addEventListener(
|
59 | 'visibilitychange',
|
60 | handleVisibilityChange,
|
61 | false,
|
62 | )
|
63 | window.addEventListener('focus', handleFocus, false)
|
64 |
|
65 |
|
66 | window.addEventListener('online', handleOnline, false)
|
67 | window.addEventListener('offline', handleOffline, false)
|
68 | initialized = true
|
69 | }
|
70 | }
|
71 | const unsubscribe = () => {
|
72 | window.removeEventListener('focus', handleFocus)
|
73 | window.removeEventListener('visibilitychange', handleVisibilityChange)
|
74 | window.removeEventListener('online', handleOnline)
|
75 | window.removeEventListener('offline', handleOffline)
|
76 | initialized = false
|
77 | }
|
78 | return unsubscribe
|
79 | }
|
80 |
|
81 | return customHandler
|
82 | ? customHandler(dispatch, { onFocus, onFocusLost, onOffline, onOnline })
|
83 | : defaultHandler()
|
84 | }
|