UNPKG

battery-status-lib

Version:

A React hook for battery status

80 lines (79 loc) 3.19 kB
import { useState as o, useEffect as h } from "react"; function b() { const [n, d] = o(null), [r, s] = o(null), [c, u] = o(null), [t, i] = o(null), [v, g] = o(!0); return h(() => { const l = navigator; if (typeof l.getBattery != "function") { console.warn("Battery Status API is not supported in this browser."), g(!1); return; } let e = null; const a = () => { e && (d(e.level * 100), s(e.charging), u( e.charging && e.chargingTime !== 1 / 0 ? e.chargingTime : null ), i( !e.charging && e.dischargingTime !== 1 / 0 ? e.dischargingTime : null )); }; return (async () => { try { e = await l.getBattery(), a(), e.addEventListener("chargingchange", a), e.addEventListener("levelchange", a), e.addEventListener("chargingtimechange", a), e.addEventListener("dischargingtimechange", a); } catch (m) { console.error("Failed to access Battery API:", m), g(!1); } })(), () => { e && (e.removeEventListener("chargingchange", a), e.removeEventListener("levelchange", a), e.removeEventListener("chargingtimechange", a), e.removeEventListener("dischargingtimechange", a)); }; }, []), { level: n, charging: r, chargingTime: c, dischargingTime: t, supported: v }; } const w = () => { const n = () => "hidden" in document ? "hidden" : "webkitHidden" in document ? "webkitHidden" : "mozHidden" in document ? "mozHidden" : "msHidden" in document ? "msHidden" : null, d = () => "visibilitychange" in document ? "visibilitychange" : "webkitvisibilitychange" in document ? "webkitvisibilitychange" : "mozvisibilitychange" in document ? "mozvisibilitychange" : "msvisibilitychange" in document ? "msvisibilitychange" : null, r = n(), s = d(), [c, u] = o( r ? !document[r] : !0 ); return h(() => { if (!s) return; const t = () => { u( r ? !document[r] : !0 ); }; return document.addEventListener(s, t), () => { document.removeEventListener( s, t ); }; }, [r, s]), c; }, E = () => { var s, c, u; const n = () => { const t = navigator; return t.connection || t.mozConnection || t.webkitConnection || null; }, [d, r] = o({ isOnline: navigator.onLine, effectiveType: (s = n()) == null ? void 0 : s.effectiveType, downlink: (c = n()) == null ? void 0 : c.downlink, rtt: (u = n()) == null ? void 0 : u.rtt }); return h(() => { const t = () => { var v, g, l; r({ isOnline: navigator.onLine, effectiveType: (v = n()) == null ? void 0 : v.effectiveType, downlink: (g = n()) == null ? void 0 : g.downlink, rtt: (l = n()) == null ? void 0 : l.rtt }); }; window.addEventListener("online", t), window.addEventListener("offline", t); const i = n(); return i != null && i.addEventListener && i.addEventListener("change", t), () => { window.removeEventListener("online", t), window.removeEventListener("offline", t), i != null && i.removeEventListener && i.removeEventListener("change", t); }; }, []), d; }; export { b as useGetBatteryStatus, E as useGetNetworkStatus, w as useGetTabVisibility };