-
Notifications
You must be signed in to change notification settings - Fork 105
feat: add useBattery hook #1667
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
samithahansaka
wants to merge
2
commits into
react-hookz:master
Choose a base branch
from
samithahansaka:feat/use-battery
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 1 commit
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,133 @@ | ||
| import {act, renderHook} from '@ver0/react-hooks-testing'; | ||
| import type {vi} from 'vitest'; | ||
| import {describe, expect, it, beforeEach} from 'vitest'; | ||
| import {useBattery} from '../index.js'; | ||
| import {expectResultValue} from '../util/testing/test-helpers.js'; | ||
|
|
||
| type MockFn = ReturnType<typeof vi.fn>; | ||
|
|
||
| type BatteryManager = { | ||
| charging: boolean; | ||
| chargingTime: number; | ||
| dischargingTime: number; | ||
| level: number; | ||
| addEventListener: MockFn; | ||
| removeEventListener: MockFn; | ||
| }; | ||
|
|
||
| describe('useBattery', () => { | ||
| // Use the global getBattery mock that's already set up in the test environment | ||
| // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion | ||
| const getBatteryMock = globalThis.navigator.getBattery as MockFn; | ||
|
|
||
| // Access the mock battery object from the getBattery mock | ||
| let mockBattery: BatteryManager; | ||
|
|
||
| beforeEach(async () => { | ||
| getBatteryMock.mockClear(); | ||
| // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment | ||
| mockBattery = await getBatteryMock(); | ||
| mockBattery.addEventListener.mockClear(); | ||
| mockBattery.removeEventListener.mockClear(); | ||
| }); | ||
|
|
||
| it('should be defined', () => { | ||
| expect(useBattery).toBeDefined(); | ||
| }); | ||
|
|
||
| it('should render', async () => { | ||
| const {result} = await renderHook(() => useBattery()); | ||
| expectResultValue(result); | ||
| }); | ||
|
|
||
| it('should return an object of certain structure', async () => { | ||
| const {result} = await renderHook(() => useBattery()); | ||
| const value = expectResultValue(result); | ||
|
|
||
| expect(typeof value).toBe('object'); | ||
| expect(Object.keys(value)).toEqual([ | ||
| 'isSupported', | ||
| 'fetched', | ||
| 'charging', | ||
| 'chargingTime', | ||
| 'dischargingTime', | ||
| 'level', | ||
| ]); | ||
| }); | ||
|
|
||
| it('should return isSupported: true when API is available', async () => { | ||
| const {result} = await renderHook(() => useBattery()); | ||
| const value = expectResultValue(result); | ||
| expect(value.isSupported).toBe(true); | ||
| }); | ||
|
|
||
| it('should fetch battery state when API is supported', async () => { | ||
| const {result} = await renderHook(() => useBattery()); | ||
|
|
||
| await act(async () => { | ||
| await Promise.resolve(); | ||
| }); | ||
|
|
||
| const value = expectResultValue(result); | ||
| expect(value.fetched).toBe(true); | ||
| expect(value.charging).toBe(true); | ||
| expect(value.chargingTime).toBe(3600); | ||
| expect(value.dischargingTime).toBe(Infinity); | ||
| expect(value.level).toBe(0.75); | ||
| }); | ||
|
|
||
| it('should subscribe to battery events', async () => { | ||
| await renderHook(() => useBattery()); | ||
|
|
||
| await act(async () => { | ||
| await Promise.resolve(); | ||
| }); | ||
|
|
||
| expect(mockBattery.addEventListener).toHaveBeenCalledWith('chargingchange', expect.any(Function)); | ||
| expect(mockBattery.addEventListener).toHaveBeenCalledWith('chargingtimechange', expect.any(Function)); | ||
| expect(mockBattery.addEventListener).toHaveBeenCalledWith('dischargingtimechange', expect.any(Function)); | ||
| expect(mockBattery.addEventListener).toHaveBeenCalledWith('levelchange', expect.any(Function)); | ||
| }); | ||
|
|
||
| it('should unsubscribe from battery events on unmount', async () => { | ||
| const {unmount} = await renderHook(() => useBattery()); | ||
|
|
||
| await act(async () => { | ||
| await Promise.resolve(); | ||
| }); | ||
|
|
||
| await unmount(); | ||
|
|
||
| expect(mockBattery.removeEventListener).toHaveBeenCalledWith('chargingchange', expect.any(Function)); | ||
| expect(mockBattery.removeEventListener).toHaveBeenCalledWith('chargingtimechange', expect.any(Function)); | ||
| expect(mockBattery.removeEventListener).toHaveBeenCalledWith('dischargingtimechange', expect.any(Function)); | ||
| expect(mockBattery.removeEventListener).toHaveBeenCalledWith('levelchange', expect.any(Function)); | ||
| }); | ||
|
|
||
| it('should update state when battery events fire', async () => { | ||
| const {result} = await renderHook(() => useBattery()); | ||
|
|
||
| await act(async () => { | ||
| await Promise.resolve(); | ||
| }); | ||
|
|
||
| let value = expectResultValue(result); | ||
| expect(value.level).toBe(0.75); | ||
|
|
||
| // Simulate battery level change | ||
| mockBattery.level = 0.5; | ||
|
|
||
| // Get the handler that was registered for levelchange | ||
| // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion | ||
| const levelChangeHandler = mockBattery.addEventListener.mock.calls.find( | ||
| (call) => call[0] === 'levelchange', | ||
| )?.[1] as () => void; | ||
|
|
||
| await act(async () => { | ||
| levelChangeHandler(); | ||
| }); | ||
|
|
||
| value = expectResultValue(result); | ||
| expect(value.level).toBe(0.5); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,32 @@ | ||
| import {renderHookServer as renderHook} from '@ver0/react-hooks-testing'; | ||
| import {describe, expect, it} from 'vitest'; | ||
| import {useBattery} from '../index.js'; | ||
|
|
||
| describe('useBattery', () => { | ||
| it('should be defined', () => { | ||
| expect(useBattery).toBeDefined(); | ||
| }); | ||
|
|
||
| it('should render', async () => { | ||
| const {result} = await renderHook(() => useBattery()); | ||
| expect(result.error).toBeUndefined(); | ||
| }); | ||
|
|
||
| it('should return isSupported as false in SSR', async () => { | ||
| const {result} = await renderHook(() => useBattery()); | ||
| expect(result.value?.isSupported).toBe(false); | ||
| }); | ||
|
|
||
| it('should return fetched as false in SSR', async () => { | ||
| const {result} = await renderHook(() => useBattery()); | ||
| expect(result.value?.fetched).toBe(false); | ||
| }); | ||
|
|
||
| it('should return undefined values in SSR', async () => { | ||
| const {result} = await renderHook(() => useBattery()); | ||
| expect(result.value?.charging).toBeUndefined(); | ||
| expect(result.value?.chargingTime).toBeUndefined(); | ||
| expect(result.value?.dischargingTime).toBeUndefined(); | ||
| expect(result.value?.level).toBeUndefined(); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,128 @@ | ||
| import {useEffect, useState} from 'react'; | ||
| import {isBrowser} from '../util/const.js'; | ||
| import {off, on} from '../util/misc.js'; | ||
|
|
||
| export type BatteryState = { | ||
| /** | ||
| * Whether the battery is currently being charged. | ||
| */ | ||
| charging: boolean | undefined; | ||
| /** | ||
| * Time in seconds until the battery is fully charged, or Infinity if not charging. | ||
| */ | ||
| chargingTime: number | undefined; | ||
| /** | ||
| * Time in seconds until the battery is fully discharged, or Infinity if charging. | ||
| */ | ||
| dischargingTime: number | undefined; | ||
| /** | ||
| * Battery charge level between 0 and 1. | ||
| */ | ||
| level: number | undefined; | ||
| }; | ||
|
|
||
| export type UseBatteryState = BatteryState & { | ||
| /** | ||
| * Whether the Battery Status API is supported by the browser. | ||
| */ | ||
| isSupported: boolean; | ||
| /** | ||
| * Whether the battery state is currently being fetched. | ||
| */ | ||
| fetched: boolean; | ||
| }; | ||
|
|
||
| type BatteryManager = { | ||
| charging: boolean; | ||
| chargingTime: number; | ||
| dischargingTime: number; | ||
| level: number; | ||
| } & EventTarget; | ||
|
|
||
| type NavigatorWithBattery = Navigator & { | ||
| getBattery?: () => Promise<BatteryManager>; | ||
| }; | ||
|
|
||
| const nav = isBrowser ? (globalThis.navigator as NavigatorWithBattery) : undefined; | ||
| const isSupported = Boolean(nav?.getBattery); | ||
|
|
||
| function getBatteryState(battery: BatteryManager | null): UseBatteryState { | ||
| if (!battery) { | ||
| return { | ||
| isSupported, | ||
| fetched: false, | ||
| charging: undefined, | ||
| chargingTime: undefined, | ||
| dischargingTime: undefined, | ||
| level: undefined, | ||
| }; | ||
| } | ||
|
|
||
| return { | ||
| isSupported, | ||
| fetched: true, | ||
| charging: battery.charging, | ||
| chargingTime: battery.chargingTime, | ||
| dischargingTime: battery.dischargingTime, | ||
| level: battery.level, | ||
| }; | ||
| } | ||
|
|
||
| /** | ||
| * Tracks the state of device's battery. | ||
| * | ||
| * @returns An object containing the battery state and whether the API is supported. | ||
| * | ||
| * @example | ||
| * const { isSupported, level, charging } = useBattery(); | ||
| * | ||
| * if (!isSupported) { | ||
| * return <p>Battery API not supported</p>; | ||
| * } | ||
| * | ||
| * return ( | ||
| * <p> | ||
| * Battery level: {level ? `${Math.round(level * 100)}%` : 'Unknown'} | ||
| * {charging && ' (Charging)'} | ||
| * </p> | ||
| * ); | ||
| */ | ||
| export function useBattery(): UseBatteryState { | ||
| const [state, setState] = useState<UseBatteryState>(() => getBatteryState(null)); | ||
|
|
||
| useEffect(() => { | ||
| if (!isSupported || !nav?.getBattery) { | ||
| return; | ||
| } | ||
|
|
||
| let battery: BatteryManager | null = null; | ||
|
|
||
| const handleChange = () => { | ||
| if (battery) { | ||
| setState(getBatteryState(battery)); | ||
| } | ||
| }; | ||
|
|
||
| // eslint-disable-next-line @typescript-eslint/no-floating-promises,promise/catch-or-return,promise/prefer-await-to-then,promise/always-return | ||
| nav.getBattery().then((b) => { | ||
| battery = b; | ||
| setState(getBatteryState(battery)); | ||
|
|
||
| on(battery, 'chargingchange', handleChange); | ||
| on(battery, 'chargingtimechange', handleChange); | ||
| on(battery, 'dischargingtimechange', handleChange); | ||
| on(battery, 'levelchange', handleChange); | ||
| }); | ||
|
samithahansaka marked this conversation as resolved.
Outdated
samithahansaka marked this conversation as resolved.
Outdated
|
||
|
|
||
| return () => { | ||
| if (battery) { | ||
| off(battery, 'chargingchange', handleChange); | ||
| off(battery, 'chargingtimechange', handleChange); | ||
| off(battery, 'dischargingtimechange', handleChange); | ||
| off(battery, 'levelchange', handleChange); | ||
| } | ||
| }; | ||
| }, []); | ||
|
|
||
| return state; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| import {vi} from 'vitest'; | ||
|
|
||
| type BatteryManager = { | ||
| charging: boolean; | ||
| chargingTime: number; | ||
| dischargingTime: number; | ||
| level: number; | ||
| addEventListener: ReturnType<typeof vi.fn>; | ||
| removeEventListener: ReturnType<typeof vi.fn>; | ||
| }; | ||
|
|
||
| const mockBattery: BatteryManager = { | ||
| charging: true, | ||
| chargingTime: 3600, | ||
| dischargingTime: Infinity, | ||
| level: 0.75, | ||
| addEventListener: vi.fn(), | ||
| removeEventListener: vi.fn(), | ||
| }; | ||
|
|
||
| const getBatteryMock = vi.fn<() => Promise<BatteryManager>>(async () => mockBattery); | ||
|
|
||
| Object.defineProperty(globalThis.navigator, 'getBattery', { | ||
| value: getBatteryMock, | ||
| writable: true, | ||
| configurable: true, | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.