(options: UseNetworkOptions = {})
| 65 | * @__NO_SIDE_EFFECTS__ |
| 66 | */ |
| 67 | export function useNetwork(options: UseNetworkOptions = {}): UseNetworkReturn { |
| 68 | const { window = defaultWindow } = options |
| 69 | const navigator = window?.navigator |
| 70 | const isSupported = useSupported(() => navigator && 'connection' in navigator) |
| 71 | |
| 72 | const isOnline = shallowRef(true) |
| 73 | const saveData = shallowRef(false) |
| 74 | const offlineAt = shallowRef<number | undefined>(undefined) |
| 75 | const onlineAt = shallowRef<number | undefined>(undefined) |
| 76 | const downlink = shallowRef<number | undefined>(undefined) |
| 77 | const downlinkMax = shallowRef<number | undefined>(undefined) |
| 78 | const rtt = shallowRef<number | undefined>(undefined) |
| 79 | const effectiveType = shallowRef<NetworkEffectiveType>(undefined) |
| 80 | const type = shallowRef<NetworkType>('unknown') |
| 81 | |
| 82 | const connection = isSupported.value && (navigator as any).connection |
| 83 | |
| 84 | function updateNetworkInformation() { |
| 85 | if (!navigator) |
| 86 | return |
| 87 | |
| 88 | isOnline.value = navigator.onLine |
| 89 | offlineAt.value = isOnline.value ? undefined : Date.now() |
| 90 | onlineAt.value = isOnline.value ? Date.now() : undefined |
| 91 | |
| 92 | if (connection) { |
| 93 | downlink.value = connection.downlink |
| 94 | downlinkMax.value = connection.downlinkMax |
| 95 | effectiveType.value = connection.effectiveType |
| 96 | rtt.value = connection.rtt |
| 97 | saveData.value = connection.saveData |
| 98 | type.value = connection.type |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | const listenerOptions = { passive: true } |
| 103 | |
| 104 | if (window) { |
| 105 | useEventListener(window, 'offline', () => { |
| 106 | isOnline.value = false |
| 107 | offlineAt.value = Date.now() |
| 108 | }, listenerOptions) |
| 109 | |
| 110 | useEventListener(window, 'online', () => { |
| 111 | isOnline.value = true |
| 112 | onlineAt.value = Date.now() |
| 113 | }, listenerOptions) |
| 114 | } |
| 115 | |
| 116 | if (connection) |
| 117 | useEventListener(connection, 'change', updateNetworkInformation, listenerOptions) |
| 118 | |
| 119 | updateNetworkInformation() |
| 120 | |
| 121 | return { |
| 122 | isSupported, |
| 123 | isOnline: shallowReadonly(isOnline), |
| 124 | saveData: shallowReadonly(saveData), |
no test coverage detected