1 | "use strict";
|
---|
2 | Object.defineProperty(exports, "__esModule", { value: true });
|
---|
3 | var react_1 = require("react");
|
---|
4 | var util_1 = require("./misc/util");
|
---|
5 | var nav = util_1.isNavigator ? navigator : undefined;
|
---|
6 | var conn = nav && (nav.connection || nav.mozConnection || nav.webkitConnection);
|
---|
7 | function getConnectionState(previousState) {
|
---|
8 | var online = nav === null || nav === void 0 ? void 0 : nav.onLine;
|
---|
9 | var previousOnline = previousState === null || previousState === void 0 ? void 0 : previousState.online;
|
---|
10 | return {
|
---|
11 | online: online,
|
---|
12 | previous: previousOnline,
|
---|
13 | since: online !== previousOnline ? new Date() : previousState === null || previousState === void 0 ? void 0 : previousState.since,
|
---|
14 | downlink: conn === null || conn === void 0 ? void 0 : conn.downlink,
|
---|
15 | downlinkMax: conn === null || conn === void 0 ? void 0 : conn.downlinkMax,
|
---|
16 | effectiveType: conn === null || conn === void 0 ? void 0 : conn.effectiveType,
|
---|
17 | rtt: conn === null || conn === void 0 ? void 0 : conn.rtt,
|
---|
18 | saveData: conn === null || conn === void 0 ? void 0 : conn.saveData,
|
---|
19 | type: conn === null || conn === void 0 ? void 0 : conn.type,
|
---|
20 | };
|
---|
21 | }
|
---|
22 | function useNetworkState(initialState) {
|
---|
23 | var _a = react_1.useState(initialState !== null && initialState !== void 0 ? initialState : getConnectionState), state = _a[0], setState = _a[1];
|
---|
24 | react_1.useEffect(function () {
|
---|
25 | var handleStateChange = function () {
|
---|
26 | setState(getConnectionState);
|
---|
27 | };
|
---|
28 | util_1.on(window, 'online', handleStateChange, { passive: true });
|
---|
29 | util_1.on(window, 'offline', handleStateChange, { passive: true });
|
---|
30 | if (conn) {
|
---|
31 | util_1.on(conn, 'change', handleStateChange, { passive: true });
|
---|
32 | }
|
---|
33 | return function () {
|
---|
34 | util_1.off(window, 'online', handleStateChange);
|
---|
35 | util_1.off(window, 'offline', handleStateChange);
|
---|
36 | if (conn) {
|
---|
37 | util_1.off(conn, 'change', handleStateChange);
|
---|
38 | }
|
---|
39 | };
|
---|
40 | }, []);
|
---|
41 | return state;
|
---|
42 | }
|
---|
43 | exports.default = useNetworkState;
|
---|