@supunlakmal/hooks
Version:
A collection of reusable React hooks
43 lines • 1.74 kB
JavaScript
import { useState, useEffect } from 'react';
import { useEventListener } from '../event-handling/useEventListener'; // Assuming useEventListener handles window
const initialOrientationState = {
alpha: null,
beta: null,
gamma: null,
absolute: false,
};
/**
* Custom hook to track the physical orientation of the device.
* Uses the 'deviceorientation' event.
*
* @returns {DeviceOrientationState} An object containing orientation angles (alpha, beta, gamma) and support status.
*/
export const useDeviceOrientation = () => {
const [state, setState] = useState(initialOrientationState);
const [isSupported, setIsSupported] = useState(false);
const handleOrientationChange = (event) => {
setState({
alpha: event.alpha,
beta: event.beta,
gamma: event.gamma,
absolute: event.absolute,
});
};
useEffect(() => {
// Check for API support on mount
if (typeof window !== 'undefined' && 'DeviceOrientationEvent' in window) {
setIsSupported(true);
}
else {
setIsSupported(false);
console.warn('DeviceOrientationEvent API not supported by this browser.');
}
}, []);
// Use useEventListener hook to manage the listener
useEventListener('deviceorientation', handleOrientationChange, // Cast handler to basic EventListener
isSupported && typeof window !== 'undefined' ? window : undefined);
// Note: Some browsers might require HTTPS or user permission for orientation data.
// This basic hook doesn't handle requesting permissions.
return Object.assign(Object.assign({}, state), { isSupported });
};
//# sourceMappingURL=useDeviceOrientation.js.map