|
| 1 | +// Copyright (C) 2017-2025 Smart code 203358507 |
| 2 | + |
| 3 | +import { useState, useEffect } from 'react'; |
| 4 | + |
| 5 | +type DeviceOrientationData = { |
| 6 | + alpha: number | null; |
| 7 | + beta: number | null; |
| 8 | + gamma: number | null; |
| 9 | + absolute: boolean | null; |
| 10 | + permissionGranted: boolean; |
| 11 | +}; |
| 12 | + |
| 13 | +const useOrientation = () => { |
| 14 | + const [orientation, setOrientation] = useState<DeviceOrientationData>({ |
| 15 | + alpha: null, |
| 16 | + beta: null, |
| 17 | + gamma: null, |
| 18 | + absolute: null, |
| 19 | + permissionGranted: false, |
| 20 | + }); |
| 21 | + |
| 22 | + const requestPermission = async () => { |
| 23 | + if ( |
| 24 | + typeof DeviceOrientationEvent !== 'undefined' && |
| 25 | + (DeviceOrientationEvent as any).requestPermission |
| 26 | + ) { |
| 27 | + try { |
| 28 | + const permissionState = await (DeviceOrientationEvent as any).requestPermission(); |
| 29 | + if (permissionState === 'granted') { |
| 30 | + setOrientation((prev) => ({ ...prev, permissionGranted: true })); |
| 31 | + } |
| 32 | + } catch (error) { |
| 33 | + console.error('Error requesting DeviceOrientation permission:', error); |
| 34 | + } |
| 35 | + } else { |
| 36 | + setOrientation((prev) => ({ ...prev, permissionGranted: true })); |
| 37 | + } |
| 38 | + }; |
| 39 | + |
| 40 | + useEffect(() => { |
| 41 | + const handleOrientationChange = (event: DeviceOrientationEvent) => { |
| 42 | + setOrientation((prev) => ({ |
| 43 | + ...prev, |
| 44 | + alpha: event.alpha ?? null, |
| 45 | + beta: event.beta ?? null, |
| 46 | + gamma: event.gamma ?? null, |
| 47 | + absolute: event.absolute ?? null, |
| 48 | + })); |
| 49 | + }; |
| 50 | + |
| 51 | + if (orientation.permissionGranted && window.DeviceOrientationEvent) { |
| 52 | + window.addEventListener('deviceorientation', handleOrientationChange); |
| 53 | + } |
| 54 | + |
| 55 | + return () => { |
| 56 | + window.removeEventListener('deviceorientation', handleOrientationChange); |
| 57 | + }; |
| 58 | + }, [orientation.permissionGranted]); |
| 59 | + |
| 60 | + return { ...orientation, requestPermission }; |
| 61 | +}; |
| 62 | + |
| 63 | +export default useOrientation; |
0 commit comments