Skip to content

⬅️ Back to Table of Contents

📄 useDeviceMotion

📊 Analysis Summary

Metric Count
🔧 Functions 3
📦 Imports 13
⚡ Async/Await Patterns 3
📐 Interfaces 3
📑 Type Aliases 1

📚 Table of Contents

🛠️ File Location:

📂 packages/core/useDeviceMotion/index.ts

📦 Imports

Name Source
ConfigurableEventFilter @vueuse/shared
ComputedRef vue
Ref vue
ShallowRef vue
ConfigurableWindow ../_configurable
Supportable ../types
bypassFilter @vueuse/shared
createFilterWrapper @vueuse/shared
deepRef vue
shallowRef vue
defaultWindow ../_configurable
useEventListener ../useEventListener
useSupported ../useSupported

Async/Await Patterns

Type Function Await Expressions Promise Chains
promise-chain useDeviceMotion none ensurePermissions().then
await-expression useDeviceMotion requestPermission() none
async-function ensurePermissions requestPermission() none

Functions

useDeviceMotion(options: UseDeviceMotionOptions): UseDeviceMotionReturn

Reactive DeviceMotionEvent.

Parameters:

  • options any: No description

See: https://vueuse.org/useDeviceMotion

Raw JSDoc
/**
 * Reactive DeviceMotionEvent.
 *
 * @see https://vueuse.org/useDeviceMotion
 * @param options
 */

Calls:

  • useSupported (from ../useSupported)
  • shallowRef (from vue)
  • deepRef (from vue)
  • createFilterWrapper (from @vueuse/shared)
  • useEventListener (from ../useEventListener)
  • requestPermission
  • init
  • console.error
  • ensurePermissions() .then
Code
export function useDeviceMotion(options: UseDeviceMotionOptions = {}): UseDeviceMotionReturn {
  const {
    window = defaultWindow,
    requestPermissions = false,
    eventFilter = bypassFilter,
  } = options

  const isSupported = useSupported(() => typeof DeviceMotionEvent !== 'undefined')
  const requirePermissions = useSupported(() => isSupported.value && 'requestPermission' in DeviceMotionEvent && typeof DeviceMotionEvent.requestPermission === 'function')
  const permissionGranted = shallowRef(false)
  const acceleration: Ref<DeviceMotionEvent['acceleration']> = deepRef({ x: null, y: null, z: null })
  const rotationRate: Ref<DeviceMotionEvent['rotationRate']> = deepRef({ alpha: null, beta: null, gamma: null })
  const interval = shallowRef(0)
  const accelerationIncludingGravity: Ref<DeviceMotionEvent['accelerationIncludingGravity']> = deepRef({
    x: null,
    y: null,
    z: null,
  })

  function init() {
    if (window) {
      const onDeviceMotion = createFilterWrapper(
        eventFilter,
        (event: DeviceMotionEvent) => {
          acceleration.value = {
            x: event.acceleration?.x || null,
            y: event.acceleration?.y || null,
            z: event.acceleration?.z || null,
          }
          accelerationIncludingGravity.value = {
            x: event.accelerationIncludingGravity?.x || null,
            y: event.accelerationIncludingGravity?.y || null,
            z: event.accelerationIncludingGravity?.z || null,
          }
          rotationRate.value = {
            alpha: event.rotationRate?.alpha || null,
            beta: event.rotationRate?.beta || null,
            gamma: event.rotationRate?.gamma || null,
          }
          interval.value = event.interval
        },
      )

      useEventListener(window, 'devicemotion', onDeviceMotion, { passive: true })
    }
  }

  const ensurePermissions = async () => {
    if (!requirePermissions.value)
      permissionGranted.value = true

    if (permissionGranted.value)
      return
    if (requirePermissions.value) {
      const requestPermission = (DeviceMotionEvent as unknown as DeviceMotionEventiOS).requestPermission
      try {
        const response = await requestPermission()
        if (response === 'granted') {
          permissionGranted.value = true
          init()
        }
      }
      catch (error) {
        console.error(error)
      }
    }
  }

  if (isSupported.value) {
    if (requestPermissions && requirePermissions.value) {
      ensurePermissions()
        .then(() => init())
    }
    else {
      init()
    }
  }

  return {
    acceleration,
    accelerationIncludingGravity,
    rotationRate,
    interval,
    isSupported,
    requirePermissions,
    ensurePermissions,
    permissionGranted,
  }
}

Internal helpers

Declared inside another function in this file.

init(): void

Returns: void

Calls:

  • createFilterWrapper (from @vueuse/shared)
  • useEventListener (from ../useEventListener)
Code
function init() {
    if (window) {
      const onDeviceMotion = createFilterWrapper(
        eventFilter,
        (event: DeviceMotionEvent) => {
          acceleration.value = {
            x: event.acceleration?.x || null,
            y: event.acceleration?.y || null,
            z: event.acceleration?.z || null,
          }
          accelerationIncludingGravity.value = {
            x: event.accelerationIncludingGravity?.x || null,
            y: event.accelerationIncludingGravity?.y || null,
            z: event.accelerationIncludingGravity?.z || null,
          }
          rotationRate.value = {
            alpha: event.rotationRate?.alpha || null,
            beta: event.rotationRate?.beta || null,
            gamma: event.rotationRate?.gamma || null,
          }
          interval.value = event.interval
        },
      )

      useEventListener(window, 'devicemotion', onDeviceMotion, { passive: true })
    }
  }

ensurePermissions(): Promise<void>

Returns: Promise<void>

Calls:

  • requestPermission
  • init
  • console.error
Code
async () => {
    if (!requirePermissions.value)
      permissionGranted.value = true

    if (permissionGranted.value)
      return
    if (requirePermissions.value) {
      const requestPermission = (DeviceMotionEvent as unknown as DeviceMotionEventiOS).requestPermission
      try {
        const response = await requestPermission()
        if (response === 'granted') {
          permissionGranted.value = true
          init()
        }
      }
      catch (error) {
        console.error(error)
      }
    }
  }

Interfaces

UseDeviceMotionOptions

Interface Code
export interface UseDeviceMotionOptions extends ConfigurableWindow, ConfigurableEventFilter {
  /**
   * Request for permissions immediately if it's not granted,
   * otherwise label and deviceIds could be empty
   *
   * @default false
   */
  requestPermissions?: boolean
}

Properties

Name Type Optional Description
requestPermissions boolean not shown

DeviceMotionEventiOS

Interface Code
interface DeviceMotionEventiOS extends UseDeviceMotionOptions {
  requestPermission: () => Promise<'granted' | 'denied'>
}

Properties

Name Type Optional Description
requestPermission () => Promise<'granted' \| 'denied'> not shown

UseDeviceMotionReturn

Interface Code
export interface UseDeviceMotionReturn extends Supportable {
  acceleration: Ref<DeviceMotionEventAcceleration | null>
  accelerationIncludingGravity: Ref<DeviceMotionEventAcceleration | null>
  rotationRate: Ref<DeviceMotionEventRotationRate | null>
  interval: ShallowRef<number>
  requirePermissions: ComputedRef<boolean>
  ensurePermissions: () => Promise<void>
  permissionGranted: ShallowRef<boolean>
}

Properties

Name Type Optional Description
acceleration Ref<DeviceMotionEventAcceleration \| null> not shown
accelerationIncludingGravity Ref<DeviceMotionEventAcceleration \| null> not shown
rotationRate Ref<DeviceMotionEventRotationRate \| null> not shown
interval ShallowRef<number> not shown
requirePermissions ComputedRef<boolean> not shown
ensurePermissions () => Promise<void> not shown
permissionGranted ShallowRef<boolean> not shown

Type Aliases

DeviceMotionOptions

/* @deprecated use {@link UseDeviceMotionOptions} instead /

type DeviceMotionOptions = UseDeviceMotionOptions;

Generated by Syntax Scribe