-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
index.ts
61 lines (51 loc) · 1.6 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/* this implementation is original ported from https://github.com/logaretm/vue-use-web by Abdelrahman Awad */
import { ref } from 'vue-demi'
import { useEventListener } from '../useEventListener'
import { ConfigurableNavigator, defaultNavigator } from '../_configurable'
export interface BatteryManager extends EventTarget {
charging: boolean
chargingTime: number
dischargingTime: number
level: number
}
type NavigatorWithBattery = Navigator & {
getBattery: () => Promise<BatteryManager>
}
/**
* Reactive Battery Status API.
*
* @see https://vueuse.org/useBattery
* @param options
*/
export function useBattery({ navigator = defaultNavigator }: ConfigurableNavigator = {}) {
const events = ['chargingchange', 'chargingtimechange', 'dischargingtimechange', 'levelchange']
const isSupported = navigator && 'getBattery' in navigator
const charging = ref(false)
const chargingTime = ref(0)
const dischargingTime = ref(0)
const level = ref(1)
let battery: BatteryManager | null
function updateBatteryInfo(this: BatteryManager) {
charging.value = this.charging
chargingTime.value = this.chargingTime || 0
dischargingTime.value = this.dischargingTime || 0
level.value = this.level
}
if (isSupported) {
(navigator as NavigatorWithBattery)
.getBattery()
.then((_battery) => {
battery = _battery
updateBatteryInfo.call(battery)
for (const event of events)
useEventListener(battery, event, updateBatteryInfo, { passive: true })
})
}
return {
isSupported,
charging,
chargingTime,
dischargingTime,
level,
}
}