1 | "use strict";
|
---|
2 | Object.defineProperty(exports, "__esModule", { value: true });
|
---|
3 | var tslib_1 = require("tslib");
|
---|
4 | var react_1 = require("react");
|
---|
5 | var util_1 = require("./misc/util");
|
---|
6 | var isDeepEqual_1 = tslib_1.__importDefault(require("./misc/isDeepEqual"));
|
---|
7 | var nav = util_1.isNavigator ? navigator : undefined;
|
---|
8 | var isBatteryApiSupported = nav && typeof nav.getBattery === 'function';
|
---|
9 | function useBatteryMock() {
|
---|
10 | return { isSupported: false };
|
---|
11 | }
|
---|
12 | function useBattery() {
|
---|
13 | var _a = react_1.useState({ isSupported: true, fetched: false }), state = _a[0], setState = _a[1];
|
---|
14 | react_1.useEffect(function () {
|
---|
15 | var isMounted = true;
|
---|
16 | var battery = null;
|
---|
17 | var handleChange = function () {
|
---|
18 | if (!isMounted || !battery) {
|
---|
19 | return;
|
---|
20 | }
|
---|
21 | var newState = {
|
---|
22 | isSupported: true,
|
---|
23 | fetched: true,
|
---|
24 | level: battery.level,
|
---|
25 | charging: battery.charging,
|
---|
26 | dischargingTime: battery.dischargingTime,
|
---|
27 | chargingTime: battery.chargingTime,
|
---|
28 | };
|
---|
29 | !isDeepEqual_1.default(state, newState) && setState(newState);
|
---|
30 | };
|
---|
31 | nav.getBattery().then(function (bat) {
|
---|
32 | if (!isMounted) {
|
---|
33 | return;
|
---|
34 | }
|
---|
35 | battery = bat;
|
---|
36 | util_1.on(battery, 'chargingchange', handleChange);
|
---|
37 | util_1.on(battery, 'chargingtimechange', handleChange);
|
---|
38 | util_1.on(battery, 'dischargingtimechange', handleChange);
|
---|
39 | util_1.on(battery, 'levelchange', handleChange);
|
---|
40 | handleChange();
|
---|
41 | });
|
---|
42 | return function () {
|
---|
43 | isMounted = false;
|
---|
44 | if (battery) {
|
---|
45 | util_1.off(battery, 'chargingchange', handleChange);
|
---|
46 | util_1.off(battery, 'chargingtimechange', handleChange);
|
---|
47 | util_1.off(battery, 'dischargingtimechange', handleChange);
|
---|
48 | util_1.off(battery, 'levelchange', handleChange);
|
---|
49 | }
|
---|
50 | };
|
---|
51 | }, []);
|
---|
52 | return state;
|
---|
53 | }
|
---|
54 | exports.default = isBatteryApiSupported ? useBattery : useBatteryMock;
|
---|