|
| 1 | +import {useState, useEffect} from './react'; |
| 2 | +import {on, off} from './util'; |
| 3 | + |
| 4 | +export interface NetworkState { |
| 5 | + online?: boolean; |
| 6 | + since?: Date; |
| 7 | + downlink?: number; |
| 8 | + downlinkMax?: number; |
| 9 | + effectiveType?: string; |
| 10 | + rtt?: number; |
| 11 | + type?: string; |
| 12 | +} |
| 13 | + |
| 14 | +const getConnection = () => { |
| 15 | + if (typeof navigator !== 'object') { |
| 16 | + return null; |
| 17 | + } |
| 18 | + const nav = navigator as any; |
| 19 | + return nav.connection || nav.mozConnection || nav.webkitConnection; |
| 20 | +}; |
| 21 | + |
| 22 | +const getConnectionState = (): NetworkState => { |
| 23 | + const connection = getConnection(); |
| 24 | + if (!connection) { |
| 25 | + return {}; |
| 26 | + } |
| 27 | + const {downlink, downlinkMax, effectiveType, type, rtt} = connection; |
| 28 | + return { |
| 29 | + downlink, |
| 30 | + downlinkMax, |
| 31 | + effectiveType, |
| 32 | + type, |
| 33 | + rtt |
| 34 | + }; |
| 35 | +} |
| 36 | + |
| 37 | +const useNetwork = (initialState: NetworkState = {}) => { |
| 38 | + const [state, setState] = useState(initialState); |
| 39 | + |
| 40 | + useEffect(() => { |
| 41 | + let localState = state; |
| 42 | + const localSetState = (patch) => { |
| 43 | + localState = {...localState, ...patch}; |
| 44 | + setState(localState); |
| 45 | + }; |
| 46 | + const connection = getConnection(); |
| 47 | + |
| 48 | + const onOnline = () => { |
| 49 | + localSetState({ |
| 50 | + online: true, |
| 51 | + since: new Date() |
| 52 | + }); |
| 53 | + }; |
| 54 | + const onOffline = () => { |
| 55 | + localSetState({ |
| 56 | + online: false, |
| 57 | + since: new Date() |
| 58 | + }); |
| 59 | + }; |
| 60 | + const onConnectionChange = () => { |
| 61 | + localSetState(getConnectionState()); |
| 62 | + }; |
| 63 | + |
| 64 | + on(window, 'online', onOnline); |
| 65 | + on(window, 'offline', onOffline); |
| 66 | + if (connection) { |
| 67 | + on(connection, 'change', onConnectionChange); |
| 68 | + localSetState({ |
| 69 | + ...state, |
| 70 | + online: navigator.onLine, |
| 71 | + since: undefined, |
| 72 | + ...getConnectionState(), |
| 73 | + }); |
| 74 | + } |
| 75 | + |
| 76 | + return () => { |
| 77 | + off(window, 'online', onOnline); |
| 78 | + off(window, 'offline', onOffline); |
| 79 | + if (connection) { |
| 80 | + off(connection, 'change', onConnectionChange); |
| 81 | + } |
| 82 | + }; |
| 83 | + }, [0]); |
| 84 | + |
| 85 | + return state; |
| 86 | +}; |
| 87 | + |
| 88 | +export default useNetwork; |
0 commit comments