|
| 1 | +import { useState, useEffect } from "vue-hooks"; |
| 2 | + |
| 3 | +const useDeviceOrientation = () => { |
| 4 | + let unsupported; |
| 5 | + if (typeof window !== "undefined" && "ondeviceorientation" in window) |
| 6 | + unsupported = false; |
| 7 | + else unsupported = true; |
| 8 | + |
| 9 | + const initialDeviceOrientation = { |
| 10 | + unsupported, |
| 11 | + absolute: 0, |
| 12 | + alpha: 0, |
| 13 | + beta: 0, |
| 14 | + gamma: 0 |
| 15 | + }; |
| 16 | + const [deviceOrientation, setDeviceOrientation] = useState( |
| 17 | + initialDeviceOrientation |
| 18 | + ); |
| 19 | + |
| 20 | + useEffect(() => { |
| 21 | + if (!unsupported) { |
| 22 | + const updateOrientation = event => { |
| 23 | + setDeviceOrientation({ |
| 24 | + absolute: event.absolute, |
| 25 | + alpha: event.alpha, |
| 26 | + beta: event.beta, |
| 27 | + gamma: event.gamma |
| 28 | + }); |
| 29 | + }; |
| 30 | + window.addEventListener( |
| 31 | + "deviceorientation", |
| 32 | + updateOrientation, |
| 33 | + true |
| 34 | + ); |
| 35 | + |
| 36 | + return () => { |
| 37 | + navigatorConnection.removeEventListener( |
| 38 | + "change", |
| 39 | + updateOrientation |
| 40 | + ); |
| 41 | + }; |
| 42 | + } |
| 43 | + }, []); |
| 44 | + |
| 45 | + return { |
| 46 | + ...deviceOrientation, |
| 47 | + setDeviceOrientation |
| 48 | + }; |
| 49 | +}; |
| 50 | + |
| 51 | +const useDeviceMotion = () => { |
| 52 | + let unsupported; |
| 53 | + if (typeof window !== "undefined" && "ondevicemotion" in window) |
| 54 | + unsupported = false; |
| 55 | + else unsupported = true; |
| 56 | + |
| 57 | + const initialDeviceMotion = { |
| 58 | + unsupported, |
| 59 | + acceleration: null, |
| 60 | + accelerationIncludingGravity: null, |
| 61 | + rotationRate: null, |
| 62 | + interval: null |
| 63 | + }; |
| 64 | + const [deviceMotion, setDeviceMotion] = useState(initialDeviceMotion); |
| 65 | + |
| 66 | + useEffect(() => { |
| 67 | + if (!unsupported) { |
| 68 | + const updateMotion = event => { |
| 69 | + setDeviceMotion({ |
| 70 | + acceleration: event.acceleration, |
| 71 | + accelerationIncludingGravity: |
| 72 | + event.accelerationIncludingGravity, |
| 73 | + rotationRate: event.rotationRate, |
| 74 | + interval: event.interval |
| 75 | + }); |
| 76 | + }; |
| 77 | + window.addEventListener("devicemotion", updateMotion, true); |
| 78 | + |
| 79 | + return () => { |
| 80 | + navigatorConnection.removeEventListener("change", updateMotion); |
| 81 | + }; |
| 82 | + } |
| 83 | + }, []); |
| 84 | + |
| 85 | + return { |
| 86 | + ...deviceMotion, |
| 87 | + setDeviceMotion |
| 88 | + }; |
| 89 | +}; |
| 90 | + |
| 91 | +export { useDeviceOrientation, useDeviceMotion }; |
0 commit comments