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