Skip to content

Commit

Permalink
feat: add battery hooks
Browse files Browse the repository at this point in the history
  • Loading branch information
TenviLi committed Nov 19, 2019
1 parent 3af0c41 commit 5ccd174
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 0 deletions.
68 changes: 68 additions & 0 deletions battery.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import { useState, useEffect } from "vue-hooks";

let unsupported;

const useBatteryStatus = () => {
// 检查浏览器是否支持 navigator.getBattery
if ("getBattery" in navigator) {
unsupported = false;
} else {
unsupported = true;
}

const initialBatteryStatus = !unsupported
? {
charging: null, // the charging state of the system's battery
chargingTime: null, // the time remaining in seconds until the system's battery is fully charged
dischargingTime: null, // the time remaining in seconds until the system's battery is completely discharged and the system is about to be suspended
level: null // the level of the system's battery
}
: {
unsupported
};

const [batteryStatus, setBatteryStatus] = useState(initialBatteryStatus);

const updateBatteryStatus = battery => {
setBatteryStatus({
chargingTime: battery.chargingTime,
dischargingTime: battery.dischargingTime,
level: battery.level,
charging: battery.charging
});
};

useEffect(() => {
if (!unsupported) {
const monitorBattery = battery => {
updateBatteryStatus(battery);

battery.addEventListener(
"levelchange",
updateBatteryStatus.bind(null, battery)
);
battery.addEventListener(
"chargingchange",
updateBatteryStatus.bind(null, battery)
);
battery.addEventListener(
"dischargingtimechange",
updateBatteryStatus.bind(null, battery)
);
battery.addEventListener(
"chargingtimechange",
updateBatteryStatus.bind(null, battery)
);
};

navigator.getBattery().then(monitorBattery);
}
}, []);

return {
...batteryStatus,
updateBatteryStatus
};
};

export { useBatteryStatus };
1 change: 1 addition & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ export { default as useNetworkStatus } from "./network";
export { default as useMemoryStatus } from "./memory";
export { default as useSaveData } from "./save-data";
export { default as useHardwareConcurrency } from "./hardware-concurrency";
export { default as useBatteryStatus } from "./battery";

0 comments on commit 5ccd174

Please # to comment.