UNPKG

@sv-use/core

Version:

A collection of Svelte 5 utilities.

66 lines (65 loc) 1.99 kB
import { onDestroy } from 'svelte'; import { handleEventListener } from '../handle-event-listener/index.svelte.js'; import { isSupported } from '../__internal__/is.svelte.js'; import { noop } from '../__internal__/utils.svelte.js'; /** * Provides information about the device's motion, including acceleration and rotation rate. * @see https://svelte-librarian.github.io/sv-use/docs/core/get-device-motion */ export function getDeviceMotion(options = {}) { const { autoCleanup = true } = options; let cleanup = noop; const _isSupported = isSupported(() => window !== undefined && 'DeviceMotionEvent' in window); let _acceleration = $state({ x: null, y: null, z: null }); let _accelerationIncludingGravity = $state({ x: null, y: null, z: null }); let _rotationRate = $state({ alpha: null, beta: null, gamma: null }); let _interval = $state(0); if (_isSupported.current) { cleanup = handleEventListener('devicemotion', onDeviceMotion, { autoCleanup }); } if (autoCleanup) { onDestroy(() => cleanup()); } function onDeviceMotion(event) { if (event.acceleration) { _acceleration = event.acceleration; } if (event.accelerationIncludingGravity) { _accelerationIncludingGravity = event.accelerationIncludingGravity; } if (event.rotationRate) { _rotationRate = event.rotationRate; } _interval = event.interval; } return { get isSupported() { return _isSupported.current; }, get acceleration() { return _acceleration; }, get accelerationIncludingGravity() { return _accelerationIncludingGravity; }, get rotationRate() { return _rotationRate; }, get interval() { return _interval; }, cleanup }; }