1.0.5 • Published 1 year ago

svelte-battery-status v1.0.5

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

Svelte Battery Status API

This library provides a readable Svelte store to use a PWA's access to the Battery Status API, available on the navigator. It allows you to read charging levels as well as certain charging thresholds.

This package is part of a collection of PWA-related svelte-packages:

Install

npm i -D svelte-battery-status

Usage

Basic

This library provides a simple readable store that automatically subscribes to events of BatteryManager, an API of the navigator to access battery charge information.

<script lang="ts">
  import { batteryStore } from 'svelte-battery-status';
</script>

<ul>
  <li>State: {$batteryStore.state}</li>
  <li>isCharging: {$batteryStore.isCharging}</li>
  <li>chargeCompleteInSec: {$batteryStore.chargeCompleteInSec}</li>
  <li>dischargeCompleteInSec: {$batteryStore.dischargeCompleteInSec}</li>
  <li>level: {$batteryStore.level}</li>
</ul>

Derived

To subscribe to changes for only a specific selection of values, simply create a derived store.

<script lang="ts">
  import { batteryStore } from 'svelte-battery-status';
  import { derived } from 'svelte/store';

  const level = derived(batteryStore, ($store) => $store.level);
</script>

level: {$level}

API

The following values are returned from the store.

KeyValueDescription
stateinit, not-supported, subscribed, unsubscribed, errorinit if not yet loaded, not-supported if browser doesn't support the BatteryManager, subscribed if the store is listening to changes, unsubscribed if the API is supported, but not listening, error in case of an unknown error throw
isChargingboolean / undefinedFlag if the device is charging (please note that a stationary device like a desktop is always charging)
chargeCompleteInSecnumber / undefinedAmount of seconds until device is fully charged
dischargeCompleteInSecnumber / undefinedAmount of seconds until device is empty
levelnumber / undefinedValue between 0 and 1, indicating the percent of current charge

Svelte Development Help