Skip to content

Commit

Permalink
feat: add useBattery hook (#97)
Browse files Browse the repository at this point in the history
A hook that Tracking the battery status of the device.
  • Loading branch information
immois authored Jul 4, 2024
1 parent ea4a69d commit a3d4f63
Show file tree
Hide file tree
Showing 9 changed files with 422 additions and 4 deletions.
5 changes: 5 additions & 0 deletions .changeset/slow-chicken-drive.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@raddix/use-battery': major
---

Added useBattery hook
18 changes: 14 additions & 4 deletions docs/_config.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,20 @@
}
]
},
{
"title": "Navigator",
"heading": true,
"children": [
{
"title": "useBattery",
"path": "/hooks/use-battery"
},
{
"title": "useClipboard",
"path": "/hooks/use-clipboard"
}
]
},
{
"title": "State",
"heading": true,
Expand Down Expand Up @@ -74,10 +88,6 @@
"title": "Utilities",
"heading": true,
"children": [
{
"title": "useClipboard",
"path": "/hooks/use-clipboard"
},
{
"title": "useCountDown",
"path": "/hooks/use-count-down"
Expand Down
70 changes: 70 additions & 0 deletions docs/en/use-battery.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
---
title: useBattery
description: Tracking the battery status of the device.
---

## Installation

Install the custom hook from your command line.

<Snippet pkg text='@raddix/use-battery' />

## Usage

```jsx
import { useBattery } from '@raddix/use-battery'

const App = () => {
const { level, charging } = useBattery()

return (
<div>
<p>Battery level:{level && level * 100}</p>
<p>{charging ? 'Battery charging' : 'Battery not charging'}</p>
</div>
)
}

export default App
```

## API

### Return

The hook returns an object with the following properties:

<ApiTable
data={[
{
name: 'isSupported',
type: 'boolean',
description: 'Indicates whether the Battery Status API is supported in the user’s browser.',
},
{
name: 'isLoading',
type: 'boolean',
description: 'Indicates if the battery information is still loading.',
},
{
name: 'level',
type: 'number',
description: 'Represents the level of the system’s battery. 0.0 means that the system’s battery is completely discharged, and 1.0 means the battery is completely charged.',
},
{
name: 'charging',
type: 'boolean',
description: 'Indicates whether the system’s battery is charging. true means the battery is charging, false means it’s not.',
},
{
name: 'chargingTime',
type: 'number',
description: 'Represents the time remaining in seconds until the system’s battery is fully charged.',
},
{
name: 'dischargingTime',
type: 'number',
description: 'Represents the time remaining in seconds until the system’s battery is completely discharged and the system is about to be suspended.',
},
]}
/>
71 changes: 71 additions & 0 deletions docs/es/use-battery.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
---
title: useBattery
description: Rastrea el estado de la batería del dispositivo.
---

## Instalación

Instale el custom hook desde su terminal.

<Snippet pkg text='@raddix/use-battery' />

## Uso

```jsx
import { useBattery } from '@raddix/use-battery'

export default function App() {
const { level, charging } = useBattery();

return (
<div>
<p>Battery level:{level && level * 100}</p>
<p>{charging ? 'Battery charging' : 'Battery not charging'}</p>
</div>
)
}
```

## API

### Valor devuelto

El gancho devuelve un objeto con las siguientes propiedades:

<ApiTable
head={{
name: 'Nombre'
}}
data={[
{
name: 'isSupported',
type: 'boolean',
description: 'Indica si la API de estado de la batería es compatible con el navegador del usuario.',
},
{
name: 'isLoading',
type: 'boolean',
description: 'Indica si la información de la batería aún se está cargando.',
},
{
name: 'level',
type: 'number',
description: 'Representa el nivel de la batería del sistema. 0,0 significa que la batería del sistema está completamente descargada y 1,0 significa que la batería está completamente cargada.',
},
{
name: 'charging',
type: 'boolean',
description: 'Indica si la batería del sistema se está cargando. true significa que la batería se está cargando, false significa que no.',
},
{
name: 'chargingTime',
type: 'number',
description: 'Representa el tiempo restante en segundos hasta que la batería del sistema esté completamente cargada.',
},
{
name: 'dischargingTime',
type: 'number',
description: 'Representa el tiempo restante en segundos hasta que la batería del sistema se descargue completamente y el sistema esté a punto de suspenderse.',
},
]}
/>
5 changes: 5 additions & 0 deletions packages/hooks/use-battery/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# useBattery

A hook that tracking the battery status of the device.

Please refer to the [documentation](https://raddix.dev/hooks/use-battery) for more information.
46 changes: 46 additions & 0 deletions packages/hooks/use-battery/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
{
"name": "@raddix/use-battery",
"description": "A hook that tracking the battery status of the device.",
"version": "0.1.0",
"license": "MIT",
"main": "src/index.ts",
"author": "Moises Machuca Valverde <[email protected]> (https://www.moisesmachuca.com)",
"homepage": "https://raddix.dev",
"repository": {
"type": "git",
"url": "https://github.com/gdvu/raddix.git"
},
"keywords": [
"react-hook",
"react-battery-hook",
"react-use-battery",
"use-battery",
"use-battery-hook",
"hook-battery"
],
"sideEffects": false,
"scripts": {
"lint": "eslint \"{src,tests}/*.{ts,tsx,css}\"",
"clean": "rm -rf .turbo && rm -rf node_modules && rm -rf dist",
"build": "tsup src --dts",
"prepack": "clean-package",
"postpack": "clean-package restore"
},
"files": [
"dist",
"README.md"
],
"peerDependencies": {
"react": ">=16.8.0",
"react-dom": ">=16.8.0"
},
"clean-package": "../../../clean-package.config.json",
"tsup": {
"clean": true,
"target": "es2019",
"format": [
"cjs",
"esm"
]
}
}
71 changes: 71 additions & 0 deletions packages/hooks/use-battery/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import { useState, useEffect } from 'react';

interface BatteryInfo {
level: number | null;
charging: boolean | null;
chargingTime: number | null;
dischargingTime: number | null;
}

export type BatteryManager = EventTarget & BatteryInfo;
interface UseBatteryReturn extends BatteryInfo {
isSupported: boolean;
isLoading: boolean;
}

declare global {
interface Navigator {
readonly getBattery: () => Promise<BatteryManager>;
}
}

export function useBattery(): UseBatteryReturn {
const [state, setState] = useState<UseBatteryReturn>({
isSupported: false,
isLoading: true,
level: null,
charging: null,
chargingTime: null,
dischargingTime: null
});

useEffect(() => {
const isSupported = 'getBattery' in navigator;
if (!isSupported) return setState(s => ({ ...s, isLoading: false }));
let battery: BatteryManager | null = null;

const handleChange = () => {
if (battery) {
setState({
isSupported: true,
isLoading: false,
level: battery.level,
charging: battery.charging,
chargingTime: battery.chargingTime,
dischargingTime: battery.dischargingTime
});
}
};

navigator.getBattery().then(batteryManager => {
battery = batteryManager;
handleChange();

batteryManager.addEventListener('levelchange', handleChange);
batteryManager.addEventListener('chargingchange', handleChange);
batteryManager.addEventListener('chargingtimechange', handleChange);
batteryManager.addEventListener('dischargingtimechange', handleChange);
});

return () => {
if (battery) {
battery.removeEventListener('levelchange', handleChange);
battery.removeEventListener('chargingchange', handleChange);
battery.removeEventListener('chargingtimechange', handleChange);
battery.removeEventListener('dischargingtimechange', handleChange);
}
};
}, []);

return state;
}
Loading

0 comments on commit a3d4f63

Please sign in to comment.