@mirawision/reactive-hooks
Version:
A comprehensive collection of 50+ React hooks for state management, UI interactions, device APIs, async operations, drag & drop, audio/speech, and more. Full TypeScript support with SSR safety.
67 lines (66 loc) • 2.43 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.useDeviceOrientation = useDeviceOrientation;
exports.requestDeviceOrientationPermission = requestDeviceOrientationPermission;
const react_1 = require("react");
/**
* A hook that provides access to the device's orientation sensors.
* Returns null values when sensors are not available or permission is not granted.
* On iOS, permission may need to be requested via DeviceOrientationEvent.requestPermission().
*
* @returns Object containing:
* - alpha: rotation around z-axis (0-360)
* - beta: front/back tilt (-180 to 180)
* - gamma: left/right tilt (-90 to 90)
* - supported: whether the device supports orientation events
*/
function useDeviceOrientation() {
const [orientation, setOrientation] = (0, react_1.useState)({
alpha: null,
beta: null,
gamma: null,
supported: false,
});
(0, react_1.useEffect)(() => {
// Check if device orientation is supported
const isSupported = Boolean(window && 'DeviceOrientationEvent' in window);
if (!isSupported) {
return;
}
setOrientation(prev => ({ ...prev, supported: true }));
const handleOrientation = (event) => {
setOrientation({
alpha: event.alpha,
beta: event.beta,
gamma: event.gamma,
supported: true,
});
};
window.addEventListener('deviceorientation', handleOrientation, true);
return () => {
window.removeEventListener('deviceorientation', handleOrientation, true);
};
}, []);
return orientation;
}
/**
* Request permission for device orientation events (iOS only).
* @returns Promise that resolves to true if permission is granted, false otherwise
*/
async function requestDeviceOrientationPermission() {
if (typeof window === 'undefined')
return false;
// Check if permission request is needed (iOS 13+)
if (typeof DeviceOrientationEvent !== 'undefined' &&
typeof DeviceOrientationEvent.requestPermission === 'function') {
try {
const permission = await DeviceOrientationEvent.requestPermission();
return permission === 'granted';
}
catch (err) {
return false;
}
}
// Permission not needed (non-iOS or older iOS)
return true;
}