-
Notifications
You must be signed in to change notification settings - Fork 120
Expand file tree
/
Copy pathbattery.js
More file actions
70 lines (57 loc) · 1.57 KB
/
battery.js
File metadata and controls
70 lines (57 loc) · 1.57 KB
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
62
63
64
65
66
67
68
69
70
/* eslint no-undef: 0 */
// Note: This is to stop XO from complaining about {navigator}
import React, { Component } from 'react'
import leftPad from 'left-pad'
import BatteryIcon from './battery/battery-icon'
export default class Battery extends Component {
static displayName() {
return 'battery'
}
constructor(props) {
super(props)
this.state = {
charging: false,
percentage: '--'
}
this.batteryEvents = [ 'chargingchange', 'chargingtimechange', 'dischargingtimechange', 'levelchange' ]
this.handleEvent = this.handleEvent.bind(this)
}
setBatteryStatus(battery) {
this.setState({
charging: battery.charging,
percentage: Math.floor(battery.level * 100)
})
}
handleEvent(event) {
this.setBatteryStatus(event.target)
}
componentDidMount() {
navigator.getBattery().then(battery => {
this.setBatteryStatus(battery)
this.batteryEvents.forEach(event => {
battery.addEventListener(event, this.handleEvent, false)
})
})
}
componentWillUnmount() {
navigator.getBattery().then(battery => {
this.batteryEvents.forEach(event => {
battery.removeEventListener(event, this.handleEvent)
})
})
}
render() {
const { charging, percentage } = this.state
return (
<div className='wrapper'>
<BatteryIcon charging={charging} percentage={Number(percentage)} /> {leftPad(percentage, 2, 0)}%
<style jsx>{`
.wrapper {
display: flex;
align-items: center;
}
`}</style>
</div>
)
}
}