forked from vercel/swr
-
Notifications
You must be signed in to change notification settings - Fork 2
/
web-preset.ts
68 lines (61 loc) · 1.85 KB
/
web-preset.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import { ProviderConfiguration } from '../types'
import { isUndefined, noop, isWindowDefined, isDocumentDefined } from './helper'
/**
* Due to bug https://bugs.chromium.org/p/chromium/issues/detail?id=678075,
* it's not reliable to detect if the browser is currently online or offline
* based on `navigator.onLine`.
* As a work around, we always assume it's online on first load, and change
* the status upon `online` or `offline` events.
*/
let online = true
const isOnline = () => online
// For node and React Native, `add/removeEventListener` doesn't exist on window.
const [onWindowEvent, offWindowEvent] =
isWindowDefined && window.addEventListener
? [
window.addEventListener.bind(window),
window.removeEventListener.bind(window)
]
: [noop, noop]
const isVisible = () => {
const visibilityState = isDocumentDefined && document.visibilityState
return isUndefined(visibilityState) || visibilityState !== 'hidden'
}
const initFocus = (callback: () => void) => {
// focus revalidate
if (isDocumentDefined) {
document.addEventListener('visibilitychange', callback)
}
onWindowEvent('focus', callback)
return () => {
if (isDocumentDefined) {
document.removeEventListener('visibilitychange', callback)
}
offWindowEvent('focus', callback)
}
}
const initReconnect = (callback: () => void) => {
// revalidate on reconnected
const onOnline = () => {
online = true
callback()
}
// nothing to revalidate, just update the status
const onOffline = () => {
online = false
}
onWindowEvent('online', onOnline)
onWindowEvent('offline', onOffline)
return () => {
offWindowEvent('online', onOnline)
offWindowEvent('offline', onOffline)
}
}
export const preset = {
isOnline,
isVisible
} as const
export const defaultConfigOptions: ProviderConfiguration = {
initFocus,
initReconnect
}