fuzzyworld

nuts / files / src / motion.ts

motion.ts

3.8 KB · history · blame

1import { CONFIG } from './config'
2import { vibrateShake } from './vibration'
3import { dbg, dbgError } from './debug'
4
5export interface MotionCallbacks {
6 onShake: (intensity: number) => void
7 onOrientation: (gravX: number, gravY: number) => void
8}
9
10/** Request iOS 13+ permission for DeviceMotion/DeviceOrientation. */
11export async function requestMotionPermission(): Promise<void> {
12 // DeviceMotionEvent
13 if (
14 typeof DeviceMotionEvent !== 'undefined' &&
15 'requestPermission' in DeviceMotionEvent &&
16 typeof (DeviceMotionEvent as unknown as { requestPermission: () => Promise<string> })
17 .requestPermission === 'function'
18 ) {
19 const result = await (
20 DeviceMotionEvent as unknown as { requestPermission: () => Promise<string> }
21 ).requestPermission()
22 dbg('DeviceMotionEvent permission:', result)
23 } else {
24 dbg('DeviceMotionEvent: no permission API (Android or desktop)')
25 }
26
27 // DeviceOrientationEvent
28 if (
29 typeof DeviceOrientationEvent !== 'undefined' &&
30 'requestPermission' in DeviceOrientationEvent &&
31 typeof (DeviceOrientationEvent as unknown as { requestPermission: () => Promise<string> })
32 .requestPermission === 'function'
33 ) {
34 const result = await (
35 DeviceOrientationEvent as unknown as { requestPermission: () => Promise<string> }
36 ).requestPermission()
37 dbg('DeviceOrientationEvent permission:', result)
38 }
39}
40
41/** Attach DeviceMotion (shake) and DeviceOrientation (gravity tilt) listeners. */
42export function initMotion(callbacks: MotionCallbacks): () => void {
43 dbg('initMotion: attaching listeners, secure?', location.protocol)
44
45 if (typeof DeviceMotionEvent === 'undefined') {
46 dbgError('DeviceMotionEvent not available')
47 }
48 if (typeof DeviceOrientationEvent === 'undefined') {
49 dbgError('DeviceOrientationEvent not available')
50 }
51
52 let prevX = 0
53 let prevY = 0
54 let prevZ = 0
55 let lastCheckAt = 0
56 let motionCount = 0
57 let orientationCount = 0
58
59 function onMotion(event: DeviceMotionEvent): void {
60 motionCount++
61 if (motionCount === 1) dbg('first devicemotion event')
62 const acc = event.accelerationIncludingGravity
63 if (!acc) return
64
65 const now = Date.now()
66 if (now - lastCheckAt < 80) return // limit check rate to ~12 Hz
67 lastCheckAt = now
68
69 const ax = acc.x ?? 0
70 const ay = acc.y ?? 0
71 const az = acc.z ?? 0
72
73 const delta = Math.sqrt(
74 (ax - prevX) ** 2 + (ay - prevY) ** 2 + (az - prevZ) ** 2
75 )
76
77 if (delta > CONFIG.shakeAccelThreshold) {
78 callbacks.onShake(delta)
79 vibrateShake()
80 }
81
82 prevX = ax
83 prevY = ay
84 prevZ = az
85 }
86
87 function onOrientation(event: DeviceOrientationEvent): void {
88 orientationCount++
89 if (orientationCount === 1) dbg('first deviceorientation event')
90 if (event.beta === null || event.gamma === null) return
91
92 // beta = front/back tilt, 0 = flat, 90 = vertical facing up
93 // gamma = left/right tilt, -90…90
94 const clamp = (v: number, min: number, max: number) =>
95 Math.max(min, Math.min(max, v))
96
97 const beta = clamp(event.beta, -CONFIG.orientationMaxTilt, CONFIG.orientationMaxTilt)
98 const gamma = clamp(event.gamma, -90, 90)
99
100 // Map to gravity vector components. Normalise so magnitude ≤ 1.
101 const gx = Math.sin((gamma * Math.PI) / 180)
102 const gy = Math.sin((beta * Math.PI) / 180)
103
104 callbacks.onOrientation(gx, gy)
105 }
106
107 window.addEventListener('devicemotion', onMotion)
108 window.addEventListener('deviceorientation', onOrientation)
109
110 return () => {
111 window.removeEventListener('devicemotion', onMotion)
112 window.removeEventListener('deviceorientation', onOrientation)
113 }
114}