forked from vercel/swr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
web-preset.ts
75 lines (67 loc) · 2.01 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
69
70
71
72
73
74
75
import { ProviderConfiguration } from '../types'
import { isUndefined, noop, hasWindow, hasDocument } 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
const hasWin = hasWindow()
const hasDoc = hasDocument()
// For node and React Native, `add/removeEventListener` doesn't exist on window.
const onWindowEvent =
hasWin && window.addEventListener
? window.addEventListener.bind(window)
: noop
const onDocumentEvent = hasDoc ? document.addEventListener.bind(document) : noop
const offWindowEvent =
hasWin && window.removeEventListener
? window.removeEventListener.bind(window)
: noop
const offDocumentEvent = hasDoc
? document.removeEventListener.bind(document)
: noop
const isVisible = () => {
const visibilityState = hasDoc && document.visibilityState
if (!isUndefined(visibilityState)) {
return visibilityState !== 'hidden'
}
return true
}
const initFocus = (callback: () => void) => {
// focus revalidate
onDocumentEvent('visibilitychange', callback)
onWindowEvent('focus', callback)
return () => {
offDocumentEvent('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
}