1 | import '../../utils/index.js';
|
2 | import { CallbackManager, MethodHandler } from '../../utils/handler.js';
|
3 | import { throttle } from '../../utils/lodash.js';
|
4 |
|
5 | const callbackManager = new CallbackManager();
|
6 | let deviceMotionListener;
|
7 | const INTERVAL_MAP = {
|
8 | game: {
|
9 | interval: 20,
|
10 | frequency: 50
|
11 | },
|
12 | ui: {
|
13 | interval: 60,
|
14 | frequency: 16.67
|
15 | },
|
16 | normal: {
|
17 | interval: 200,
|
18 | frequency: 5
|
19 | }
|
20 | };
|
21 |
|
22 |
|
23 |
|
24 | const stopDeviceMotionListening = ({ success, fail, complete } = {}) => {
|
25 | const handle = new MethodHandler({ name: 'stopDeviceMotionListening', success, fail, complete });
|
26 | try {
|
27 | window.removeEventListener('deviceorientation', deviceMotionListener, true);
|
28 | return handle.success();
|
29 | }
|
30 | catch (e) {
|
31 | return handle.fail({ errMsg: e.message });
|
32 | }
|
33 | };
|
34 |
|
35 |
|
36 |
|
37 | const startDeviceMotionListening = ({ interval = 'normal', success, fail, complete } = {}) => {
|
38 | const handle = new MethodHandler({ name: 'startDeviceMotionListening', success, fail, complete });
|
39 | try {
|
40 | const intervalObj = INTERVAL_MAP[interval];
|
41 | if (window.DeviceOrientationEvent) {
|
42 | if (deviceMotionListener) {
|
43 | stopDeviceMotionListening();
|
44 | }
|
45 | deviceMotionListener = throttle((evt) => {
|
46 | callbackManager.trigger({
|
47 | alpha: evt.alpha,
|
48 | beta: evt.beta,
|
49 | gamma: evt.gamma
|
50 | });
|
51 | }, intervalObj.interval);
|
52 | window.addEventListener('deviceorientation', deviceMotionListener, true);
|
53 | }
|
54 | else {
|
55 | throw new Error('deviceMotion is not supported');
|
56 | }
|
57 | return handle.success();
|
58 | }
|
59 | catch (e) {
|
60 | return handle.fail({ errMsg: e.message });
|
61 | }
|
62 | };
|
63 |
|
64 |
|
65 |
|
66 | const onDeviceMotionChange = callback => {
|
67 | callbackManager.add(callback);
|
68 | };
|
69 |
|
70 |
|
71 |
|
72 | const offDeviceMotionChange = callback => {
|
73 | callbackManager.remove(callback);
|
74 | };
|
75 |
|
76 | export { offDeviceMotionChange, onDeviceMotionChange, startDeviceMotionListening, stopDeviceMotionListening };
|
77 |
|