From 9c6d0aeb7a447f0009a7470abbbe7e5379ab914c Mon Sep 17 00:00:00 2001 From: luojiahao Date: Thu, 13 Oct 2022 09:59:43 +0800 Subject: [PATCH] TASK: #103649 - add battery widget --- src/widgets/battery/battery.ts | 98 ++++++++++++++++++++++++++++++++++ 1 file changed, 98 insertions(+) create mode 100644 src/widgets/battery/battery.ts diff --git a/src/widgets/battery/battery.ts b/src/widgets/battery/battery.ts new file mode 100644 index 0000000..cd46c75 --- /dev/null +++ b/src/widgets/battery/battery.ts @@ -0,0 +1,98 @@ +import GaiaWidget from '../gaia-widget' +import '../../components/battery/battery' +import {StarBattery} from '../../components/battery/battery' +import {customElement} from 'lit/decorators.js' + +@customElement('gaia-battery') +class BatteryWidget extends GaiaWidget { + constructor({ + url, + appName, + origin, + size, + manifestWidgetName, + }: { + url: string + size: [number, number] + origin: string + appName: string + manifestWidgetName: string + }) { + super({ + url: url || 'js/widgets/battery.js', + appName: appName || 'homescreen', + origin: origin || 'http://homescreen.localhost/manifest.webmanifest', + size: size || [2, 2], + manifestWidgetName: manifestWidgetName || 'battery', + }) + } + + _battery: any + async init() { + // @ts-ignore + this._battery = await navigator.getBattery() + this.percent = this._battery.level + this.charge = this._battery.charging + this._battery.addEventListener('levelchange', this) + this._battery.addEventListener('chargingchange', this) + } + + handleEvent(event: Event): void { + switch (event.type) { + case 'levelchange': + this.percent = this._battery.level + break + case 'chargingchange': + this.charge = this._battery.charging + break + } + } + + battery!: StarBattery + connectedCallback() { + this.battery = this.shadowRoot!.querySelector('star-battery')! + } + + get percent() { + return this.battery.percent + } + + set percent(value) { + this.battery.percent = value + } + + get charge() { + return this.battery.charge + } + + set charge(value) { + // this.battery.charge = !!value + if (value) { + setTimeout(() => { + this.battery.charge = false + }) + } + this.battery.charge = value + } + + get template() { + return ` + + + ` + } +} + +export default BatteryWidget