[battery] Add BatteryStatusManager

Summary:
This adds a simple service to monitor whether the computer is plugged in
or not.

Test Plan: Run locally, verify that we correctly detect battery charging state

Reviewers: evan, spang, juan

Reviewed By: evan, spang, juan

Differential Revision: https://phab.nylas.com/D3937
This commit is contained in:
Mark Hahnenberg 2017-02-15 17:32:57 -08:00
parent f7e5683ec7
commit 71e2397ef3
2 changed files with 44 additions and 0 deletions

View file

@ -219,8 +219,10 @@ lazyLoad(`QuotedHTMLTransformer`, 'services/quoted-html-transformer');
lazyLoad(`InlineStyleTransformer`, 'services/inline-style-transformer');
lazyLoad(`SearchableComponentMaker`, 'searchable-components/searchable-component-maker');
lazyLoad(`QuotedPlainTextTransformer`, 'services/quoted-plain-text-transformer');
lazyLoad(`BatteryStatusManager`, 'services/battery-status-manager');
lazyLoadWithGetter(`BackoffScheduler`, () => require('../services/backoff-schedulers').BackoffScheduler);
lazyLoadWithGetter(`ExponentialBackoffScheduler`, () => require('../services/backoff-schedulers').ExponentialBackoffScheduler);
// Errors
lazyLoadWithGetter(`APIError`, () => require('../flux/errors').APIError);

View file

@ -0,0 +1,42 @@
class BatteryStatusManager {
constructor() {
this._callbacks = [];
this._battery = null;
}
async activate() {
if (this._battery) {
return;
}
this._battery = await navigator.getBattery();
this._battery.addEventListener('chargingchange', this._onChargingChange);
}
deactivate() {
if (!this._battery) {
return;
}
this._battery.removeEventListener('chargingchange', this._onChargingChange);
this._battery = null;
}
_onChargingChange = () => {
this._callbacks.forEach(cb => cb());
}
onChange(callback) {
this._callbacks.push(callback);
}
isBatteryCharging() {
if (!this._battery) {
return false;
}
return this._battery.charging;
}
}
const manager = new BatteryStatusManager();
manager.activate();
export default manager;