UNPKG

@sv-use/core

Version:

A collection of Svelte 5 utilities.

70 lines (69 loc) 2.51 kB
import { onDestroy } from 'svelte'; import { getDocumentVisibility } from '../get-document-visibility/index.svelte.js'; import { whenever } from '../whenever/index.svelte.js'; import { handleEventListener } from '../handle-event-listener/index.svelte.js'; import { noop } from '../__internal__/utils.svelte.js'; import { defaultDocument, defaultNavigator } from '../__internal__/configurable.js'; /** * Provides a way to prevent devices from dimming or locking the screen when an application needs to keep running. * @param options Additional options to customize the behavior. * @see https://svelte-librarian.github.io/sv-use/docs/core/create-vibration */ export function handleWakeLock(options = {}) { const { autoCleanup = true, navigator = defaultNavigator, document = defaultDocument } = options; let eventListenerCleanup = noop; let requestedType = $state(false); let sentinel = $state(null); const documentVisibility = getDocumentVisibility({ autoCleanup, document }); const isSupported = $derived.by(() => !!navigator && 'wakeLock' in navigator); const isActive = $derived.by(() => !!sentinel && documentVisibility.current === 'visible'); if (isSupported) { eventListenerCleanup = handleEventListener(sentinel, 'release', () => { requestedType = sentinel?.type ?? false; }, { autoCleanup, passive: true }); whenever(() => documentVisibility.current === 'visible' && !!requestedType, () => { requestedType = false; forceRequest('screen'); }); } if (autoCleanup) { onDestroy(() => cleanup()); } async function forceRequest(type) { await sentinel?.release(); sentinel = isSupported ? await navigator.wakeLock.request(type) : null; } async function request(type) { if (documentVisibility.current === 'visible') { await forceRequest(type); } else { requestedType = type; } } async function release() { requestedType = false; sentinel?.release().then(() => { sentinel = null; }); } function cleanup() { documentVisibility.cleanup(); eventListenerCleanup(); } return { get isSupported() { return isSupported; }, get isActive() { return isActive; }, sentinel, request, forceRequest, release, cleanup }; }