sensor-based-mobile-ui 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,640 +1,653 @@
1
- 'use client';
2
-
3
- import React, { useEffect, useRef, useState } from 'react';
4
- import { createScaredState, frameBrightness, readLight, scaredMotion } from '../core/scared.js';
5
- import { createMagneticState, readMagneticField, readMagneticHeading, magneticMotion } from '../core/magnetic.js';
6
- import { readRotation, tornadoMotion } from '../core/tornado.js';
7
- import { readEarthquake, earthquakeMotion } from '../core/earthquake.js';
8
- import { readLoudness } from '../core/pulse.js';
9
- import { gravityMotion } from '../core/gravity.js';
10
-
11
- export function ScaredUI({ children, className, controlsAfter, animateControls = false }) {
12
- const [status, setStatus] = useState('idle');
13
- const [session, setSession] = useState(0);
14
- const [cameraStream, setCameraStream] = useState(null);
15
- const [sensorEnabled, setSensorEnabled] = useState(false);
16
- const elements = useRef([]);
17
- const controlsRef = useRef(null);
18
- const video = useRef(null);
19
- const cameraRef = useRef(null);
20
- const cameraRequest = useRef(0);
21
- const cameraState = useRef(createScaredState());
22
-
23
- useEffect(() => () => { cameraRequest.current++; cameraRef.current?.getTracks().forEach(track => track.stop()); }, []);
24
-
25
- const stopCamera = () => {
26
- cameraRequest.current++;
27
- cameraRef.current?.getTracks().forEach(track => track.stop());
28
- cameraRef.current = null;
29
- if (video.current) video.current.srcObject = null;
30
- setCameraStream(null);
31
- setStatus('stopped');
32
- };
33
-
34
- const startCamera = async () => {
35
- const request = ++cameraRequest.current;
36
- setSensorEnabled(false);
37
- setStatus('camera-pending');
38
- if (!navigator.mediaDevices?.getUserMedia) { setStatus('camera-unavailable'); return; }
39
- let stream;
40
- try {
41
- stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: 'user' }, audio: false });
42
- if (request !== cameraRequest.current) { stream.getTracks().forEach(track => track.stop()); return; }
43
- if (document.hidden) { stream.getTracks().forEach(track => track.stop()); stopCamera(); return; }
44
- cameraRef.current = stream;
45
- video.current.srcObject = stream;
46
- await video.current.play();
47
- if (request !== cameraRequest.current) { stream.getTracks().forEach(track => track.stop()); return; }
48
- if (document.hidden) { stopCamera(); return; }
49
- cameraState.current = createScaredState();
50
- setStatus('camera-starting');
51
- setCameraStream(stream);
52
- } catch {
53
- stream?.getTracks().forEach(track => track.stop());
54
- if (request === cameraRequest.current) { cameraRef.current = null; if (video.current) video.current.srcObject = null; setStatus('camera-unavailable'); }
55
- }
56
- };
57
-
58
- useEffect(() => {
59
- if (!cameraStream) return;
60
- const canvas = document.createElement('canvas');
61
- canvas.width = 32; canvas.height = 24;
62
- const context = canvas.getContext('2d', { willReadFrequently: true });
63
- const reducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)');
64
- let frame;
65
- let lastSample = 0;
66
- const onHidden = () => { if (document.hidden) stopCamera(); };
67
- const onEnded = () => { stopCamera(); setStatus('camera-unavailable'); };
68
- document.addEventListener('visibilitychange', onHidden);
69
- cameraStream.getVideoTracks().forEach(track => track.addEventListener('ended', onEnded));
70
- const animate = () => {
71
- const now = Date.now();
72
- if (now - lastSample >= 100 && video.current?.readyState >= 2) {
73
- try {
74
- context.drawImage(video.current, 0, 0, canvas.width, canvas.height);
75
- // shortcut: camera auto-exposure can mask a shadow; use calibrated vision if brightness proves unreliable.
76
- cameraState.current = readLight(cameraState.current, frameBrightness(context.getImageData(0, 0, canvas.width, canvas.height).data), now);
77
- setStatus(cameraState.current.baseline < 1 ? 'camera-dark' : 'camera-active');
78
- lastSample = now;
79
- } catch { stopCamera(); setStatus('camera-unavailable'); return; }
80
- }
81
- [...elements.current, controlsRef.current].forEach((element, index) => {
82
- if (!element) return;
83
- const { x, y, rotate, scaleY } = reducedMotion.matches ? { x: 0, y: 0, rotate: 0, scaleY: 1 } : scaredMotion(cameraState.current, now, index);
84
- element.style.transform = `translate(${x}px, ${y}px) rotate(${rotate}deg) scaleY(${scaleY})`;
85
- });
86
- frame = requestAnimationFrame(animate);
87
- };
88
- frame = requestAnimationFrame(animate);
89
- return () => {
90
- document.removeEventListener('visibilitychange', onHidden);
91
- cameraStream.getVideoTracks().forEach(track => track.removeEventListener('ended', onEnded));
92
- cameraStream.getTracks().forEach(track => track.stop());
93
- if (cameraRef.current === cameraStream) cameraRef.current = null;
94
- if (video.current) video.current.srcObject = null;
95
- cancelAnimationFrame(frame);
96
- elements.current.forEach(element => { if (element) element.style.transform = ''; });
97
- if (controlsRef.current) controlsRef.current.style.transform = '';
98
- };
99
- }, [cameraStream]);
100
-
101
- useEffect(() => {
102
- if (!session || !sensorEnabled) return;
103
- if (!window.isSecureContext) {
104
- setStatus('insecure');
105
- return;
106
- }
107
- if (!('AmbientLightSensor' in window)) {
108
- setStatus('unsupported');
109
- return;
110
- }
111
-
112
- let sensor;
113
- let frame;
114
- let state = createScaredState();
115
- const reducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)');
116
- const reset = () => [...elements.current, controlsRef.current].forEach(element => {
117
- if (element) element.style.transform = '';
118
- });
119
- const animate = () => {
120
- [...elements.current, controlsRef.current].forEach((element, index) => {
121
- if (!element) return;
122
- const { x, y, rotate, scaleY } = reducedMotion.matches ? { x: 0, y: 0, rotate: 0, scaleY: 1 } : scaredMotion(state, Date.now(), index);
123
- element.style.transform = `translate(${x}px, ${y}px) rotate(${rotate}deg) scaleY(${scaleY})`;
124
- });
125
- frame = requestAnimationFrame(animate);
126
- };
127
- try {
128
- sensor = new window.AmbientLightSensor({ frequency: 10 });
129
- sensor.addEventListener('reading', () => {
130
- state = readLight(state, sensor.illuminance, Date.now());
131
- if (state.baseline !== null) setStatus(state.baseline < 1 ? 'dark' : 'active');
132
- });
133
- sensor.addEventListener('error', () => {
134
- sensor.stop();
135
- cancelAnimationFrame(frame);
136
- reset();
137
- setStatus('unavailable');
138
- });
139
- sensor.start();
140
- frame = requestAnimationFrame(animate);
141
- } catch {
142
- sensor?.stop();
143
- reset();
144
- setStatus('unavailable');
145
- }
146
- return () => {
147
- sensor?.stop();
148
- cancelAnimationFrame(frame);
149
- reset();
150
- };
151
- }, [session, sensorEnabled]);
152
-
153
- const controls = React.createElement(animateControls ? 'div' : React.Fragment, animateControls ? { className: 'scared-controls', ref: controlsRef, key: 'controls' } : { key: 'controls' },
154
- cameraStream
155
- ? React.createElement(React.Fragment, null,
156
- React.createElement('button', { type: 'button', onClick: () => { cameraState.current = createScaredState(); setStatus('camera-starting'); } }, 'Recalibrate scaredUI'),
157
- React.createElement('button', { type: 'button', onClick: stopCamera }, 'Stop camera'))
158
- : status === 'camera-pending'
159
- ? React.createElement('button', { type: 'button', onClick: stopCamera }, 'Cancel camera request')
160
- : React.createElement('button', { type: 'button', onClick: () => { setSensorEnabled(true); setStatus('starting'); setSession(value => value + 1); } }, status === 'active' || status === 'dark' ? 'Recalibrate scaredUI' : session ? 'Try light sensor again' : 'Enable scaredUI'),
161
- React.createElement('p', { role: 'status' }, {
162
- idle: 'Uncover the light sensor, then enable scaredUI.',
163
- starting: 'Keep the light sensor uncovered while calibrating. You can choose the camera if no reading arrives.',
164
- active: 'Cover the light sensor to make the interface shiver.',
165
- dark: 'There is not enough light to calibrate. Move somewhere brighter and recalibrate.',
166
- insecure: 'Ambient light sensing requires HTTPS or localhost.',
167
- unsupported: 'This browser does not provide ambient light sensing. You can choose the camera instead.',
168
- unavailable: 'Ambient light sensing is unavailable or permission was denied. You can choose the camera instead.',
169
- 'camera-pending': 'Waiting for camera permission. No microphone is used.',
170
- 'camera-starting': 'Keep the front camera uncovered while calibrating.',
171
- 'camera-active': 'Camera active. Move your hand over the front camera to make the interface shiver.',
172
- 'camera-dark': 'The camera view is too dark. Uncover the camera and recalibrate in brighter light.',
173
- 'camera-unavailable': 'Camera access is unavailable or permission was denied. Check your browser settings and try again.',
174
- stopped: 'Camera stopped. You can restart it whenever you are ready.'
175
- }[status]),
176
- ['starting', 'unsupported', 'unavailable', 'camera-unavailable', 'stopped'].includes(status) && React.createElement(React.Fragment, null,
177
- React.createElement('p', null, 'Use the front camera to estimate light changes. Video is processed on your device and is not saved or sent anywhere.'),
178
- React.createElement('button', { type: 'button', onClick: startCamera }, 'Use front camera')));
179
- const items = React.Children.map(children, (child, index) => React.createElement('div', {
180
- ref: element => { elements.current[index] = element; },
181
- style: { display: 'inline-block' }
182
- }, child)) || [];
183
- items.splice(controlsAfter == null ? 0 : controlsAfter + 1, 0, controls);
184
- return React.createElement('div', { className },
185
- React.createElement('video', { ref: video, autoPlay: true, muted: true, playsInline: true, 'aria-hidden': true, tabIndex: -1, style: { position: 'fixed', width: 1, height: 1, opacity: 0.01, pointerEvents: 'none', bottom: 0, left: 0 } }),
186
- items
187
- );
188
- }
189
-
190
- export function CompassUI({ children, className }) {
191
- const [status, setStatus] = useState('idle');
192
- const [session, setSession] = useState(0);
193
- const [source, setSource] = useState(null);
194
- const elements = useRef([]);
195
- const request = useRef(0);
196
-
197
- useEffect(() => () => { request.current++; }, []);
198
-
199
- const enable = async () => {
200
- const current = ++request.current;
201
- if (!window.isSecureContext) { setStatus('insecure'); return; }
202
- if ('Magnetometer' in window) {
203
- setSource('magnetometer');
204
- } else if (window.DeviceOrientationEvent) {
205
- setStatus('permission');
206
- try {
207
- if (typeof window.DeviceOrientationEvent.requestPermission === 'function' &&
208
- await window.DeviceOrientationEvent.requestPermission(true) !== 'granted') {
209
- if (current === request.current) setStatus('denied');
210
- return;
211
- }
212
- } catch {
213
- if (current === request.current) setStatus('denied');
214
- return;
215
- }
216
- if (current !== request.current) return;
217
- setSource('compass');
218
- } else {
219
- setStatus('unsupported');
220
- return;
221
- }
222
- setStatus('starting');
223
- setSession(value => value + 1);
224
- };
225
-
226
- useEffect(() => {
227
- if (!session || !source) return;
228
-
229
- let sensor;
230
- let frame;
231
- let state = createMagneticState();
232
- let timeout = setTimeout(() => setStatus('unavailable'), 8000);
233
- const reducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)');
234
- const reset = () => elements.current.forEach(element => {
235
- if (element) element.style.transform = '';
236
- });
237
- const animate = () => {
238
- const { x, y } = reducedMotion.matches ? { x: 0, y: 0 } : magneticMotion(state);
239
- elements.current.forEach(element => {
240
- if (element) element.style.transform = `translate(${x}px, ${y}px)`;
241
- });
242
- frame = requestAnimationFrame(animate);
243
- };
244
- const onOrientation = event => {
245
- state = readMagneticHeading(state, event.webkitCompassHeading);
246
- if (state.field) { clearTimeout(timeout); setStatus('compass-active'); }
247
- };
248
- try {
249
- if (source === 'compass') {
250
- window.addEventListener('deviceorientation', onOrientation);
251
- } else {
252
- sensor = new window.Magnetometer({ frequency: 10, referenceFrame: 'screen' });
253
- sensor.addEventListener('reading', () => {
254
- state = readMagneticField(state, sensor.x, sensor.y);
255
- if (state.field) { clearTimeout(timeout); setStatus('active'); }
256
- });
257
- sensor.addEventListener('error', () => {
258
- sensor.stop();
259
- clearTimeout(timeout);
260
- cancelAnimationFrame(frame);
261
- reset();
262
- setStatus('unavailable');
263
- });
264
- sensor.start();
265
- }
266
- frame = requestAnimationFrame(animate);
267
- } catch {
268
- sensor?.stop();
269
- clearTimeout(timeout);
270
- reset();
271
- setStatus('unavailable');
272
- }
273
- return () => {
274
- sensor?.stop();
275
- window.removeEventListener('deviceorientation', onOrientation);
276
- clearTimeout(timeout);
277
- cancelAnimationFrame(frame);
278
- reset();
279
- };
280
- }, [session, source]);
281
-
282
- return React.createElement('div', { className },
283
- React.createElement('button', { type: 'button', onClick: enable, disabled: status === 'permission' }, session ? 'Restart compassUI' : 'Enable compassUI'),
284
- React.createElement('p', { role: 'status' }, {
285
- idle: 'Hold your phone flat in portrait, then enable compassUI.',
286
- permission: 'Waiting for motion and orientation permission.',
287
- starting: 'Waiting for a compass reading.',
288
- active: 'Hold your phone flat and rotate it. The content shifts toward magnetic north.',
289
- 'compass-active': 'Hold your phone flat and rotate it. The content shifts toward magnetic north.',
290
- insecure: 'Magnetic sensing requires HTTPS or localhost.',
291
- unsupported: 'This browser does not provide magnetic sensing or a compass heading.',
292
- denied: 'Motion and orientation access was denied. Check your browser settings and try again.',
293
- unavailable: 'No magnetic reading was received. Check your device and browser settings, then try again.'
294
- }[status]),
295
- React.Children.map(children, (child, index) => React.createElement('div', {
296
- ref: element => { elements.current[index] = element; },
297
- style: { display: 'inline-block' }
298
- }, child))
299
- );
300
- }
301
-
302
- export { CompassUI as MagneticUI };
303
-
304
- export function TornadoUI({ children, className }) {
305
- const [status, setStatus] = useState('idle');
306
- const [session, setSession] = useState(0);
307
- const elements = useRef([]);
308
- const request = useRef(0);
309
-
310
- useEffect(() => () => { request.current++; }, []);
311
-
312
- const enable = async () => {
313
- const current = ++request.current;
314
- if (!window.isSecureContext) { setStatus('insecure'); return; }
315
- if (!window.DeviceMotionEvent) { setStatus('unsupported'); return; }
316
- setStatus('permission');
317
- try {
318
- if (typeof window.DeviceMotionEvent.requestPermission === 'function' &&
319
- await window.DeviceMotionEvent.requestPermission() !== 'granted') {
320
- if (current === request.current) setStatus('denied');
321
- return;
322
- }
323
- } catch {
324
- if (current === request.current) setStatus('denied');
325
- return;
326
- }
327
- if (current !== request.current) return;
328
- setStatus('starting');
329
- setSession(value => value + 1);
330
- };
331
-
332
- useEffect(() => {
333
- if (!session) return;
334
- let state = null;
335
- let frame;
336
- const reducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)');
337
- const timeout = setTimeout(() => setStatus('unavailable'), 8000);
338
- const onMotion = event => {
339
- const reading = readRotation(event.rotationRate, Date.now(), state);
340
- if (!reading) return;
341
- state = reading;
342
- clearTimeout(timeout);
343
- setStatus('active');
344
- };
345
- const animate = () => {
346
- const items = elements.current.filter(Boolean);
347
- const left = Math.min(...items.map(element => element.offsetLeft));
348
- const right = Math.max(...items.map(element => element.offsetLeft + element.offsetWidth));
349
- const top = Math.min(...items.map(element => element.offsetTop));
350
- const bottom = Math.max(...items.map(element => element.offsetTop + element.offsetHeight));
351
- const centerX = (left + right) / 2;
352
- const centerY = (top + bottom) / 2;
353
- items.forEach(element => {
354
- if (!element) return;
355
- const { x, y } = reducedMotion.matches ? { x: 0, y: 0 } : tornadoMotion(state, Date.now(), element.offsetLeft + element.offsetWidth / 2 - centerX, element.offsetTop + element.offsetHeight / 2 - centerY);
356
- element.style.transform = `translate(${x}px, ${y}px)`;
357
- });
358
- frame = requestAnimationFrame(animate);
359
- };
360
- window.addEventListener('devicemotion', onMotion);
361
- frame = requestAnimationFrame(animate);
362
- return () => {
363
- window.removeEventListener('devicemotion', onMotion);
364
- clearTimeout(timeout);
365
- cancelAnimationFrame(frame);
366
- elements.current.forEach(element => { if (element) element.style.transform = ''; });
367
- };
368
- }, [session]);
369
-
370
- return React.createElement('div', { className, style: { position: 'relative' } },
371
- React.createElement('button', { type: 'button', disabled: status === 'permission' || status === 'active' || status === 'starting', onClick: enable }, status === 'active' ? 'TornadoUI enabled' : session ? 'Try tornadoUI again' : 'Enable tornadoUI'),
372
- React.createElement('p', { role: 'status' }, {
373
- idle: 'Enable tornadoUI, then rotate your device quickly.',
374
- permission: 'Waiting for motion permission.',
375
- starting: 'Waiting for a motion sensor reading.',
376
- active: 'Rotate your device quickly to stir up the interface.',
377
- insecure: 'Motion sensing requires HTTPS or localhost.',
378
- unsupported: 'This browser does not provide motion sensing.',
379
- denied: 'Motion access was denied. Check your browser settings and try again.',
380
- unavailable: 'No rotation reading was received. Check your device and browser settings.'
381
- }[status]),
382
- React.Children.map(children, (child, index) => React.createElement('div', {
383
- ref: element => { elements.current[index] = element; },
384
- style: { display: 'inline-block' }
385
- }, child))
386
- );
387
- }
388
-
389
- export function EarthquakeUI({ children, className }) {
390
- const [status, setStatus] = useState('idle');
391
- const [session, setSession] = useState(0);
392
- const elements = useRef([]);
393
- const request = useRef(0);
394
-
395
- useEffect(() => () => { request.current++; }, []);
396
-
397
- const enable = async () => {
398
- const current = ++request.current;
399
- if (!window.isSecureContext) { setStatus('insecure'); return; }
400
- if (!window.DeviceMotionEvent) { setStatus('unsupported'); return; }
401
- setStatus('permission');
402
- try {
403
- if (typeof window.DeviceMotionEvent.requestPermission === 'function' &&
404
- await window.DeviceMotionEvent.requestPermission() !== 'granted') {
405
- if (current === request.current) setStatus('denied');
406
- return;
407
- }
408
- } catch {
409
- if (current === request.current) setStatus('denied');
410
- return;
411
- }
412
- if (current !== request.current) return;
413
- setStatus('starting');
414
- setSession(value => value + 1);
415
- };
416
-
417
- useEffect(() => {
418
- if (!session) return;
419
- let state = null;
420
- let frame;
421
- const reducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)');
422
- const timeout = setTimeout(() => setStatus('unavailable'), 8000);
423
- const onMotion = event => {
424
- const reading = readEarthquake(event.acceleration, Date.now(), state);
425
- if (!reading) return;
426
- state = reading;
427
- clearTimeout(timeout);
428
- setStatus('active');
429
- };
430
- const animate = () => {
431
- elements.current.forEach((element, index) => {
432
- if (!element) return;
433
- const { x, y, rotate } = reducedMotion.matches ? { x: 0, y: 0, rotate: 0 } : earthquakeMotion(state, Date.now(), index);
434
- element.style.transform = `translate(${x}px, ${y}px) rotate(${rotate}deg)`;
435
- });
436
- frame = requestAnimationFrame(animate);
437
- };
438
- window.addEventListener('devicemotion', onMotion);
439
- frame = requestAnimationFrame(animate);
440
- return () => {
441
- window.removeEventListener('devicemotion', onMotion);
442
- clearTimeout(timeout);
443
- cancelAnimationFrame(frame);
444
- elements.current.forEach(element => { if (element) element.style.transform = ''; });
445
- };
446
- }, [session]);
447
-
448
- return React.createElement('div', { className, style: { position: 'relative' } },
449
- React.createElement('button', { type: 'button', disabled: status === 'permission' || status === 'active' || status === 'starting', onClick: enable }, status === 'active' ? 'EarthquakeUI enabled' : session ? 'Try earthquakeUI again' : 'Enable earthquakeUI'),
450
- React.createElement('p', { role: 'status' }, {
451
- idle: 'Enable earthquakeUI, then shake your phone.',
452
- permission: 'Waiting for motion permission.',
453
- starting: 'Waiting for a motion sensor reading.',
454
- active: 'Shake your phone to move the elements. They will slowly return when you stop.',
455
- insecure: 'Motion sensing requires HTTPS or localhost.',
456
- unsupported: 'This browser does not provide motion sensing.',
457
- denied: 'Motion access was denied. Check your browser settings and try again.',
458
- unavailable: 'No acceleration reading was received. Check your device and browser settings.'
459
- }[status]),
460
- React.Children.map(children, (child, index) => React.createElement('div', {
461
- ref: element => { elements.current[index] = element; },
462
- style: { display: 'inline-block' }
463
- }, child))
464
- );
465
- }
466
-
467
- export function PulseUI({ children, className }) {
468
- const [status, setStatus] = useState('idle');
469
- const [stream, setStream] = useState(null);
470
- const elements = useRef([]);
471
- const request = useRef(0);
472
- const streamRef = useRef(null);
473
-
474
- const stop = () => {
475
- request.current++;
476
- streamRef.current?.getTracks().forEach(track => track.stop());
477
- streamRef.current = null;
478
- setStream(null);
479
- setStatus('stopped');
480
- };
481
-
482
- useEffect(() => {
483
- const onHidden = () => { if (document.hidden) stop(); };
484
- document.addEventListener('visibilitychange', onHidden);
485
- return () => {
486
- document.removeEventListener('visibilitychange', onHidden);
487
- request.current++;
488
- streamRef.current?.getTracks().forEach(track => track.stop());
489
- };
490
- }, []);
491
-
492
- const start = async () => {
493
- const current = ++request.current;
494
- if (!navigator.mediaDevices?.getUserMedia || !window.AudioContext) { setStatus('unavailable'); return; }
495
- setStatus('pending');
496
- try {
497
- const audio = await navigator.mediaDevices.getUserMedia({ audio: { echoCancellation: false, noiseSuppression: false, autoGainControl: false }, video: false });
498
- if (current !== request.current || document.hidden) { audio.getTracks().forEach(track => track.stop()); return; }
499
- streamRef.current = audio;
500
- setStream(audio);
501
- setStatus('active');
502
- } catch {
503
- if (current === request.current) setStatus('unavailable');
504
- }
505
- };
506
-
507
- useEffect(() => {
508
- if (!stream) return;
509
- let context;
510
- let frame;
511
- let active = true;
512
- const onEnded = () => { if (active) { stop(); setStatus('unavailable'); } };
513
- const tracks = stream.getAudioTracks();
514
- tracks.forEach(track => track.addEventListener('ended', onEnded));
515
- try {
516
- context = new window.AudioContext();
517
- const source = context.createMediaStreamSource(stream);
518
- const analyser = context.createAnalyser();
519
- analyser.fftSize = 1024;
520
- source.connect(analyser);
521
- const samples = new Float32Array(analyser.fftSize);
522
- const reducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)');
523
- let level = 0;
524
- const animate = () => {
525
- analyser.getFloatTimeDomainData(samples);
526
- level = readLoudness(samples, level);
527
- elements.current.forEach(element => {
528
- if (!element) return;
529
- element.style.transform = reducedMotion.matches ? '' : `scale(${1 + level * 0.08})`;
530
- element.style.boxShadow = `0 0 ${level * 30}px rgba(182, 245, 91, ${level * 0.7})`;
531
- });
532
- frame = requestAnimationFrame(animate);
533
- };
534
- context.resume().catch(onEnded);
535
- frame = requestAnimationFrame(animate);
536
- } catch { onEnded(); }
537
- return () => {
538
- active = false;
539
- tracks.forEach(track => track.removeEventListener('ended', onEnded));
540
- cancelAnimationFrame(frame);
541
- context?.close();
542
- stream.getTracks().forEach(track => track.stop());
543
- elements.current.forEach(element => { if (element) { element.style.transform = ''; element.style.boxShadow = ''; } });
544
- };
545
- }, [stream]);
546
-
547
- return React.createElement('div', { className },
548
- React.createElement('button', { type: 'button', onClick: stream || status === 'pending' ? stop : start },
549
- stream ? 'Stop microphone' : status === 'pending' ? 'Cancel microphone request' : 'Enable pulseUI'),
550
- React.createElement('p', { role: 'status' }, {
551
- idle: 'Enable the microphone, then play music, speak, or clap.',
552
- pending: 'Waiting for microphone permission.',
553
- active: 'Microphone active. Sound makes the cards pulse.',
554
- stopped: 'Microphone stopped.',
555
- unavailable: 'Microphone access is unavailable or denied. Check your browser settings and try again.'
556
- }[status]),
557
- React.Children.map(children, (child, index) => React.createElement('div', {
558
- ref: element => { elements.current[index] = element; },
559
- style: { display: 'inline-block', borderRadius: '10px' }
560
- }, child))
561
- );
562
- }
563
-
564
- export function GravityUI({ children, className }) {
565
- const [status, setStatus] = useState('idle');
566
- const [session, setSession] = useState(0);
567
- const elements = useRef([]);
568
- const request = useRef(0);
569
-
570
- useEffect(() => () => { request.current++; }, []);
571
-
572
- const enable = async () => {
573
- const current = ++request.current;
574
- if (!window.isSecureContext) { setStatus('insecure'); return; }
575
- if (!window.DeviceOrientationEvent) { setStatus('unsupported'); return; }
576
- setStatus('permission');
577
- try {
578
- if (typeof window.DeviceOrientationEvent.requestPermission === 'function' &&
579
- await window.DeviceOrientationEvent.requestPermission() !== 'granted') {
580
- if (current === request.current) setStatus('denied');
581
- return;
582
- }
583
- } catch {
584
- if (current === request.current) setStatus('denied');
585
- return;
586
- }
587
- if (current !== request.current) return;
588
- setStatus('starting');
589
- setSession(value => value + 1);
590
- };
591
-
592
- useEffect(() => {
593
- if (!session) return;
594
- const reducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)');
595
- const timeout = setTimeout(() => setStatus('unavailable'), 8000);
596
- const onOrientation = event => {
597
- const motion = gravityMotion(event.beta, event.gamma, window.screen.orientation?.angle ?? window.orientation ?? 0);
598
- if (!motion) return;
599
- clearTimeout(timeout);
600
- setStatus('active');
601
- elements.current.forEach(element => {
602
- if (element) element.style.transform = reducedMotion.matches ? '' : `translate(${motion.x}px, ${motion.y}px)`;
603
- });
604
- };
605
- const onReducedMotion = () => {
606
- elements.current.forEach(element => {
607
- if (!element) return;
608
- element.style.transition = reducedMotion.matches ? 'none' : 'transform 0.2s ease-out';
609
- if (reducedMotion.matches) element.style.transform = '';
610
- });
611
- };
612
- onReducedMotion();
613
- window.addEventListener('deviceorientation', onOrientation);
614
- reducedMotion.addEventListener('change', onReducedMotion);
615
- return () => {
616
- window.removeEventListener('deviceorientation', onOrientation);
617
- reducedMotion.removeEventListener('change', onReducedMotion);
618
- clearTimeout(timeout);
619
- elements.current.forEach(element => { if (element) element.style.transform = ''; });
620
- };
621
- }, [session]);
622
-
623
- return React.createElement('div', { className },
624
- React.createElement('button', { type: 'button', onClick: enable, disabled: ['permission', 'starting', 'active'].includes(status) }, status === 'active' ? 'GravityUI enabled' : session ? 'Try gravityUI again' : 'Enable gravityUI'),
625
- React.createElement('p', { role: 'status' }, {
626
- idle: 'Enable gravityUI, then tilt your phone.',
627
- permission: 'Waiting for orientation permission.',
628
- starting: 'Waiting for an orientation reading.',
629
- active: 'Tilt your phone to move the cards toward the lower edge.',
630
- insecure: 'Orientation sensing requires HTTPS or localhost.',
631
- unsupported: 'This browser does not provide device orientation.',
632
- denied: 'Orientation access was denied. Check your browser settings and try again.',
633
- unavailable: 'No orientation reading was received. Check your device and browser settings, then try again.'
634
- }[status]),
635
- React.Children.map(children, (child, index) => React.createElement('div', {
636
- ref: element => { elements.current[index] = element; },
637
- style: { display: 'inline-block', transition: 'transform 0.2s ease-out' }
638
- }, child))
639
- );
640
- }
1
+ 'use client';
2
+
3
+ import React, { useEffect, useRef, useState } from 'react';
4
+ import { createScaredState, frameBrightness, readLight, scaredMotion } from '../core/scared.js';
5
+ import { createMagneticState, readMagneticField, readMagneticHeading, magneticMotion } from '../core/magnetic.js';
6
+ import { readRotation, tornadoMotion } from '../core/tornado.js';
7
+ import { readEarthquake, earthquakeMotion } from '../core/earthquake.js';
8
+ import { readLoudness } from '../core/pulse.js';
9
+ import { gravityMotion } from '../core/gravity.js';
10
+ import { normalizeIntensity } from '../core/intensity.js';
11
+
12
+ export function ScaredUI({ children, className, controlsAfter, animateControls = false, intensity = 1 }) {
13
+ const intensityRef = useRef(1);
14
+ intensityRef.current = normalizeIntensity(intensity);
15
+ const [status, setStatus] = useState('idle');
16
+ const [session, setSession] = useState(0);
17
+ const [cameraStream, setCameraStream] = useState(null);
18
+ const [sensorEnabled, setSensorEnabled] = useState(false);
19
+ const elements = useRef([]);
20
+ const controlsRef = useRef(null);
21
+ const video = useRef(null);
22
+ const cameraRef = useRef(null);
23
+ const cameraRequest = useRef(0);
24
+ const cameraState = useRef(createScaredState());
25
+
26
+ useEffect(() => () => { cameraRequest.current++; cameraRef.current?.getTracks().forEach(track => track.stop()); }, []);
27
+
28
+ const stopCamera = () => {
29
+ cameraRequest.current++;
30
+ cameraRef.current?.getTracks().forEach(track => track.stop());
31
+ cameraRef.current = null;
32
+ if (video.current) video.current.srcObject = null;
33
+ setCameraStream(null);
34
+ setStatus('stopped');
35
+ };
36
+
37
+ const startCamera = async () => {
38
+ const request = ++cameraRequest.current;
39
+ setSensorEnabled(false);
40
+ setStatus('camera-pending');
41
+ if (!navigator.mediaDevices?.getUserMedia) { setStatus('camera-unavailable'); return; }
42
+ let stream;
43
+ try {
44
+ stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: 'user' }, audio: false });
45
+ if (request !== cameraRequest.current) { stream.getTracks().forEach(track => track.stop()); return; }
46
+ if (document.hidden) { stream.getTracks().forEach(track => track.stop()); stopCamera(); return; }
47
+ cameraRef.current = stream;
48
+ video.current.srcObject = stream;
49
+ await video.current.play();
50
+ if (request !== cameraRequest.current) { stream.getTracks().forEach(track => track.stop()); return; }
51
+ if (document.hidden) { stopCamera(); return; }
52
+ cameraState.current = createScaredState();
53
+ setStatus('camera-starting');
54
+ setCameraStream(stream);
55
+ } catch {
56
+ stream?.getTracks().forEach(track => track.stop());
57
+ if (request === cameraRequest.current) { cameraRef.current = null; if (video.current) video.current.srcObject = null; setStatus('camera-unavailable'); }
58
+ }
59
+ };
60
+
61
+ useEffect(() => {
62
+ if (!cameraStream) return;
63
+ const canvas = document.createElement('canvas');
64
+ canvas.width = 32; canvas.height = 24;
65
+ const context = canvas.getContext('2d', { willReadFrequently: true });
66
+ const reducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)');
67
+ let frame;
68
+ let lastSample = 0;
69
+ const onHidden = () => { if (document.hidden) stopCamera(); };
70
+ const onEnded = () => { stopCamera(); setStatus('camera-unavailable'); };
71
+ document.addEventListener('visibilitychange', onHidden);
72
+ cameraStream.getVideoTracks().forEach(track => track.addEventListener('ended', onEnded));
73
+ const animate = () => {
74
+ const now = Date.now();
75
+ if (now - lastSample >= 100 && video.current?.readyState >= 2) {
76
+ try {
77
+ context.drawImage(video.current, 0, 0, canvas.width, canvas.height);
78
+ // shortcut: camera auto-exposure can mask a shadow; use calibrated vision if brightness proves unreliable.
79
+ cameraState.current = readLight(cameraState.current, frameBrightness(context.getImageData(0, 0, canvas.width, canvas.height).data), now);
80
+ setStatus(cameraState.current.baseline < 1 ? 'camera-dark' : 'camera-active');
81
+ lastSample = now;
82
+ } catch { stopCamera(); setStatus('camera-unavailable'); return; }
83
+ }
84
+ [...elements.current, controlsRef.current].forEach((element, index) => {
85
+ if (!element) return;
86
+ const { x, y, rotate, scaleY } = reducedMotion.matches ? { x: 0, y: 0, rotate: 0, scaleY: 1 } : scaredMotion(cameraState.current, now, index);
87
+ element.style.transform = `translate(${x * intensityRef.current}px, ${y * intensityRef.current}px) rotate(${rotate * intensityRef.current}deg) scaleY(${1 + (scaleY - 1) * intensityRef.current})`;
88
+ });
89
+ frame = requestAnimationFrame(animate);
90
+ };
91
+ frame = requestAnimationFrame(animate);
92
+ return () => {
93
+ document.removeEventListener('visibilitychange', onHidden);
94
+ cameraStream.getVideoTracks().forEach(track => track.removeEventListener('ended', onEnded));
95
+ cameraStream.getTracks().forEach(track => track.stop());
96
+ if (cameraRef.current === cameraStream) cameraRef.current = null;
97
+ if (video.current) video.current.srcObject = null;
98
+ cancelAnimationFrame(frame);
99
+ elements.current.forEach(element => { if (element) element.style.transform = ''; });
100
+ if (controlsRef.current) controlsRef.current.style.transform = '';
101
+ };
102
+ }, [cameraStream]);
103
+
104
+ useEffect(() => {
105
+ if (!session || !sensorEnabled) return;
106
+ if (!window.isSecureContext) {
107
+ setStatus('insecure');
108
+ return;
109
+ }
110
+ if (!('AmbientLightSensor' in window)) {
111
+ setStatus('unsupported');
112
+ return;
113
+ }
114
+
115
+ let sensor;
116
+ let frame;
117
+ let state = createScaredState();
118
+ const reducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)');
119
+ const reset = () => [...elements.current, controlsRef.current].forEach(element => {
120
+ if (element) element.style.transform = '';
121
+ });
122
+ const animate = () => {
123
+ [...elements.current, controlsRef.current].forEach((element, index) => {
124
+ if (!element) return;
125
+ const { x, y, rotate, scaleY } = reducedMotion.matches ? { x: 0, y: 0, rotate: 0, scaleY: 1 } : scaredMotion(state, Date.now(), index);
126
+ element.style.transform = `translate(${x * intensityRef.current}px, ${y * intensityRef.current}px) rotate(${rotate * intensityRef.current}deg) scaleY(${1 + (scaleY - 1) * intensityRef.current})`;
127
+ });
128
+ frame = requestAnimationFrame(animate);
129
+ };
130
+ try {
131
+ sensor = new window.AmbientLightSensor({ frequency: 10 });
132
+ sensor.addEventListener('reading', () => {
133
+ state = readLight(state, sensor.illuminance, Date.now());
134
+ if (state.baseline !== null) setStatus(state.baseline < 1 ? 'dark' : 'active');
135
+ });
136
+ sensor.addEventListener('error', () => {
137
+ sensor.stop();
138
+ cancelAnimationFrame(frame);
139
+ reset();
140
+ setStatus('unavailable');
141
+ });
142
+ sensor.start();
143
+ frame = requestAnimationFrame(animate);
144
+ } catch {
145
+ sensor?.stop();
146
+ reset();
147
+ setStatus('unavailable');
148
+ }
149
+ return () => {
150
+ sensor?.stop();
151
+ cancelAnimationFrame(frame);
152
+ reset();
153
+ };
154
+ }, [session, sensorEnabled]);
155
+
156
+ const controls = React.createElement(animateControls ? 'div' : React.Fragment, animateControls ? { className: 'scared-controls', ref: controlsRef, key: 'controls' } : { key: 'controls' },
157
+ cameraStream
158
+ ? React.createElement(React.Fragment, null,
159
+ React.createElement('button', { type: 'button', onClick: () => { cameraState.current = createScaredState(); setStatus('camera-starting'); } }, 'Recalibrate scaredUI'),
160
+ React.createElement('button', { type: 'button', onClick: stopCamera }, 'Stop camera'))
161
+ : status === 'camera-pending'
162
+ ? React.createElement('button', { type: 'button', onClick: stopCamera }, 'Cancel camera request')
163
+ : React.createElement('button', { type: 'button', onClick: () => { setSensorEnabled(true); setStatus('starting'); setSession(value => value + 1); } }, status === 'active' || status === 'dark' ? 'Recalibrate scaredUI' : session ? 'Try light sensor again' : 'Enable scaredUI'),
164
+ React.createElement('p', { role: 'status' }, {
165
+ idle: 'Uncover the light sensor, then enable scaredUI.',
166
+ starting: 'Keep the light sensor uncovered while calibrating. You can choose the camera if no reading arrives.',
167
+ active: 'Cover the light sensor to make the interface shiver.',
168
+ dark: 'There is not enough light to calibrate. Move somewhere brighter and recalibrate.',
169
+ insecure: 'Ambient light sensing requires HTTPS or localhost.',
170
+ unsupported: 'This browser does not provide ambient light sensing. You can choose the camera instead.',
171
+ unavailable: 'Ambient light sensing is unavailable or permission was denied. You can choose the camera instead.',
172
+ 'camera-pending': 'Waiting for camera permission. No microphone is used.',
173
+ 'camera-starting': 'Keep the front camera uncovered while calibrating.',
174
+ 'camera-active': 'Camera active. Move your hand over the front camera to make the interface shiver.',
175
+ 'camera-dark': 'The camera view is too dark. Uncover the camera and recalibrate in brighter light.',
176
+ 'camera-unavailable': 'Camera access is unavailable or permission was denied. Check your browser settings and try again.',
177
+ stopped: 'Camera stopped. You can restart it whenever you are ready.'
178
+ }[status]),
179
+ ['starting', 'unsupported', 'unavailable', 'camera-unavailable', 'stopped'].includes(status) && React.createElement(React.Fragment, null,
180
+ React.createElement('p', null, 'Use the front camera to estimate light changes. Video is processed on your device and is not saved or sent anywhere.'),
181
+ React.createElement('button', { type: 'button', onClick: startCamera }, 'Use front camera')));
182
+ const items = React.Children.map(children, (child, index) => React.createElement('div', {
183
+ ref: element => { elements.current[index] = element; },
184
+ style: { display: 'inline-block' }
185
+ }, child)) || [];
186
+ items.splice(controlsAfter == null ? 0 : controlsAfter + 1, 0, controls);
187
+ return React.createElement('div', { className },
188
+ React.createElement('video', { ref: video, autoPlay: true, muted: true, playsInline: true, 'aria-hidden': true, tabIndex: -1, style: { position: 'fixed', width: 1, height: 1, opacity: 0.01, pointerEvents: 'none', bottom: 0, left: 0 } }),
189
+ items
190
+ );
191
+ }
192
+
193
+ export function CompassUI({ children, className, intensity = 1 }) {
194
+ const intensityRef = useRef(1);
195
+ intensityRef.current = normalizeIntensity(intensity);
196
+ const [status, setStatus] = useState('idle');
197
+ const [session, setSession] = useState(0);
198
+ const [source, setSource] = useState(null);
199
+ const elements = useRef([]);
200
+ const request = useRef(0);
201
+
202
+ useEffect(() => () => { request.current++; }, []);
203
+
204
+ const enable = async () => {
205
+ const current = ++request.current;
206
+ if (!window.isSecureContext) { setStatus('insecure'); return; }
207
+ if ('Magnetometer' in window) {
208
+ setSource('magnetometer');
209
+ } else if (window.DeviceOrientationEvent) {
210
+ setStatus('permission');
211
+ try {
212
+ if (typeof window.DeviceOrientationEvent.requestPermission === 'function' &&
213
+ await window.DeviceOrientationEvent.requestPermission(true) !== 'granted') {
214
+ if (current === request.current) setStatus('denied');
215
+ return;
216
+ }
217
+ } catch {
218
+ if (current === request.current) setStatus('denied');
219
+ return;
220
+ }
221
+ if (current !== request.current) return;
222
+ setSource('compass');
223
+ } else {
224
+ setStatus('unsupported');
225
+ return;
226
+ }
227
+ setStatus('starting');
228
+ setSession(value => value + 1);
229
+ };
230
+
231
+ useEffect(() => {
232
+ if (!session || !source) return;
233
+
234
+ let sensor;
235
+ let frame;
236
+ let state = createMagneticState();
237
+ let timeout = setTimeout(() => setStatus('unavailable'), 8000);
238
+ const reducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)');
239
+ const reset = () => elements.current.forEach(element => {
240
+ if (element) element.style.transform = '';
241
+ });
242
+ const animate = () => {
243
+ const { x, y } = reducedMotion.matches ? { x: 0, y: 0 } : magneticMotion(state);
244
+ elements.current.forEach(element => {
245
+ if (element) element.style.transform = `translate(${x * intensityRef.current}px, ${y * intensityRef.current}px)`;
246
+ });
247
+ frame = requestAnimationFrame(animate);
248
+ };
249
+ const onOrientation = event => {
250
+ state = readMagneticHeading(state, event.webkitCompassHeading);
251
+ if (state.field) { clearTimeout(timeout); setStatus('compass-active'); }
252
+ };
253
+ try {
254
+ if (source === 'compass') {
255
+ window.addEventListener('deviceorientation', onOrientation);
256
+ } else {
257
+ sensor = new window.Magnetometer({ frequency: 10, referenceFrame: 'screen' });
258
+ sensor.addEventListener('reading', () => {
259
+ state = readMagneticField(state, sensor.x, sensor.y);
260
+ if (state.field) { clearTimeout(timeout); setStatus('active'); }
261
+ });
262
+ sensor.addEventListener('error', () => {
263
+ sensor.stop();
264
+ clearTimeout(timeout);
265
+ cancelAnimationFrame(frame);
266
+ reset();
267
+ setStatus('unavailable');
268
+ });
269
+ sensor.start();
270
+ }
271
+ frame = requestAnimationFrame(animate);
272
+ } catch {
273
+ sensor?.stop();
274
+ clearTimeout(timeout);
275
+ reset();
276
+ setStatus('unavailable');
277
+ }
278
+ return () => {
279
+ sensor?.stop();
280
+ window.removeEventListener('deviceorientation', onOrientation);
281
+ clearTimeout(timeout);
282
+ cancelAnimationFrame(frame);
283
+ reset();
284
+ };
285
+ }, [session, source]);
286
+
287
+ return React.createElement('div', { className },
288
+ React.createElement('button', { type: 'button', onClick: enable, disabled: status === 'permission' }, session ? 'Restart compassUI' : 'Enable compassUI'),
289
+ React.createElement('p', { role: 'status' }, {
290
+ idle: 'Hold your phone flat in portrait, then enable compassUI.',
291
+ permission: 'Waiting for motion and orientation permission.',
292
+ starting: 'Waiting for a compass reading.',
293
+ active: 'Hold your phone flat and rotate it. The content shifts toward magnetic north.',
294
+ 'compass-active': 'Hold your phone flat and rotate it. The content shifts toward magnetic north.',
295
+ insecure: 'Magnetic sensing requires HTTPS or localhost.',
296
+ unsupported: 'This browser does not provide magnetic sensing or a compass heading.',
297
+ denied: 'Motion and orientation access was denied. Check your browser settings and try again.',
298
+ unavailable: 'No magnetic reading was received. Check your device and browser settings, then try again.'
299
+ }[status]),
300
+ React.Children.map(children, (child, index) => React.createElement('div', {
301
+ ref: element => { elements.current[index] = element; },
302
+ style: { display: 'inline-block' }
303
+ }, child))
304
+ );
305
+ }
306
+
307
+ export { CompassUI as MagneticUI };
308
+
309
+ export function TornadoUI({ children, className, intensity = 1 }) {
310
+ const intensityRef = useRef(1);
311
+ intensityRef.current = normalizeIntensity(intensity);
312
+ const [status, setStatus] = useState('idle');
313
+ const [session, setSession] = useState(0);
314
+ const elements = useRef([]);
315
+ const request = useRef(0);
316
+
317
+ useEffect(() => () => { request.current++; }, []);
318
+
319
+ const enable = async () => {
320
+ const current = ++request.current;
321
+ if (!window.isSecureContext) { setStatus('insecure'); return; }
322
+ if (!window.DeviceMotionEvent) { setStatus('unsupported'); return; }
323
+ setStatus('permission');
324
+ try {
325
+ if (typeof window.DeviceMotionEvent.requestPermission === 'function' &&
326
+ await window.DeviceMotionEvent.requestPermission() !== 'granted') {
327
+ if (current === request.current) setStatus('denied');
328
+ return;
329
+ }
330
+ } catch {
331
+ if (current === request.current) setStatus('denied');
332
+ return;
333
+ }
334
+ if (current !== request.current) return;
335
+ setStatus('starting');
336
+ setSession(value => value + 1);
337
+ };
338
+
339
+ useEffect(() => {
340
+ if (!session) return;
341
+ let state = null;
342
+ let frame;
343
+ const reducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)');
344
+ const timeout = setTimeout(() => setStatus('unavailable'), 8000);
345
+ const onMotion = event => {
346
+ const reading = readRotation(event.rotationRate, Date.now(), state);
347
+ if (!reading) return;
348
+ state = reading;
349
+ clearTimeout(timeout);
350
+ setStatus('active');
351
+ };
352
+ const animate = () => {
353
+ const items = elements.current.filter(Boolean);
354
+ const left = Math.min(...items.map(element => element.offsetLeft));
355
+ const right = Math.max(...items.map(element => element.offsetLeft + element.offsetWidth));
356
+ const top = Math.min(...items.map(element => element.offsetTop));
357
+ const bottom = Math.max(...items.map(element => element.offsetTop + element.offsetHeight));
358
+ const centerX = (left + right) / 2;
359
+ const centerY = (top + bottom) / 2;
360
+ items.forEach(element => {
361
+ if (!element) return;
362
+ const { x, y } = reducedMotion.matches ? { x: 0, y: 0 } : tornadoMotion(state, Date.now(), element.offsetLeft + element.offsetWidth / 2 - centerX, element.offsetTop + element.offsetHeight / 2 - centerY);
363
+ element.style.transform = `translate(${x * intensityRef.current}px, ${y * intensityRef.current}px)`;
364
+ });
365
+ frame = requestAnimationFrame(animate);
366
+ };
367
+ window.addEventListener('devicemotion', onMotion);
368
+ frame = requestAnimationFrame(animate);
369
+ return () => {
370
+ window.removeEventListener('devicemotion', onMotion);
371
+ clearTimeout(timeout);
372
+ cancelAnimationFrame(frame);
373
+ elements.current.forEach(element => { if (element) element.style.transform = ''; });
374
+ };
375
+ }, [session]);
376
+
377
+ return React.createElement('div', { className, style: { position: 'relative' } },
378
+ React.createElement('button', { type: 'button', disabled: status === 'permission' || status === 'active' || status === 'starting', onClick: enable }, status === 'active' ? 'TornadoUI enabled' : session ? 'Try tornadoUI again' : 'Enable tornadoUI'),
379
+ React.createElement('p', { role: 'status' }, {
380
+ idle: 'Enable tornadoUI, then rotate your device quickly.',
381
+ permission: 'Waiting for motion permission.',
382
+ starting: 'Waiting for a motion sensor reading.',
383
+ active: 'Rotate your device quickly to stir up the interface.',
384
+ insecure: 'Motion sensing requires HTTPS or localhost.',
385
+ unsupported: 'This browser does not provide motion sensing.',
386
+ denied: 'Motion access was denied. Check your browser settings and try again.',
387
+ unavailable: 'No rotation reading was received. Check your device and browser settings.'
388
+ }[status]),
389
+ React.Children.map(children, (child, index) => React.createElement('div', {
390
+ ref: element => { elements.current[index] = element; },
391
+ style: { display: 'inline-block' }
392
+ }, child))
393
+ );
394
+ }
395
+
396
+ export function EarthquakeUI({ children, className, intensity = 1 }) {
397
+ const intensityRef = useRef(1);
398
+ intensityRef.current = normalizeIntensity(intensity);
399
+ const [status, setStatus] = useState('idle');
400
+ const [session, setSession] = useState(0);
401
+ const elements = useRef([]);
402
+ const request = useRef(0);
403
+
404
+ useEffect(() => () => { request.current++; }, []);
405
+
406
+ const enable = async () => {
407
+ const current = ++request.current;
408
+ if (!window.isSecureContext) { setStatus('insecure'); return; }
409
+ if (!window.DeviceMotionEvent) { setStatus('unsupported'); return; }
410
+ setStatus('permission');
411
+ try {
412
+ if (typeof window.DeviceMotionEvent.requestPermission === 'function' &&
413
+ await window.DeviceMotionEvent.requestPermission() !== 'granted') {
414
+ if (current === request.current) setStatus('denied');
415
+ return;
416
+ }
417
+ } catch {
418
+ if (current === request.current) setStatus('denied');
419
+ return;
420
+ }
421
+ if (current !== request.current) return;
422
+ setStatus('starting');
423
+ setSession(value => value + 1);
424
+ };
425
+
426
+ useEffect(() => {
427
+ if (!session) return;
428
+ let state = null;
429
+ let frame;
430
+ const reducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)');
431
+ const timeout = setTimeout(() => setStatus('unavailable'), 8000);
432
+ const onMotion = event => {
433
+ const reading = readEarthquake(event.acceleration, Date.now(), state);
434
+ if (!reading) return;
435
+ state = reading;
436
+ clearTimeout(timeout);
437
+ setStatus('active');
438
+ };
439
+ const animate = () => {
440
+ elements.current.forEach((element, index) => {
441
+ if (!element) return;
442
+ const { x, y, rotate } = reducedMotion.matches ? { x: 0, y: 0, rotate: 0 } : earthquakeMotion(state, Date.now(), index);
443
+ element.style.transform = `translate(${x * intensityRef.current}px, ${y * intensityRef.current}px) rotate(${rotate * intensityRef.current}deg)`;
444
+ });
445
+ frame = requestAnimationFrame(animate);
446
+ };
447
+ window.addEventListener('devicemotion', onMotion);
448
+ frame = requestAnimationFrame(animate);
449
+ return () => {
450
+ window.removeEventListener('devicemotion', onMotion);
451
+ clearTimeout(timeout);
452
+ cancelAnimationFrame(frame);
453
+ elements.current.forEach(element => { if (element) element.style.transform = ''; });
454
+ };
455
+ }, [session]);
456
+
457
+ return React.createElement('div', { className, style: { position: 'relative' } },
458
+ React.createElement('button', { type: 'button', disabled: status === 'permission' || status === 'active' || status === 'starting', onClick: enable }, status === 'active' ? 'EarthquakeUI enabled' : session ? 'Try earthquakeUI again' : 'Enable earthquakeUI'),
459
+ React.createElement('p', { role: 'status' }, {
460
+ idle: 'Enable earthquakeUI, then shake your phone.',
461
+ permission: 'Waiting for motion permission.',
462
+ starting: 'Waiting for a motion sensor reading.',
463
+ active: 'Shake your phone to move the elements. They will slowly return when you stop.',
464
+ insecure: 'Motion sensing requires HTTPS or localhost.',
465
+ unsupported: 'This browser does not provide motion sensing.',
466
+ denied: 'Motion access was denied. Check your browser settings and try again.',
467
+ unavailable: 'No acceleration reading was received. Check your device and browser settings.'
468
+ }[status]),
469
+ React.Children.map(children, (child, index) => React.createElement('div', {
470
+ ref: element => { elements.current[index] = element; },
471
+ style: { display: 'inline-block' }
472
+ }, child))
473
+ );
474
+ }
475
+
476
+ export function PulseUI({ children, className, intensity = 1 }) {
477
+ const intensityRef = useRef(1);
478
+ intensityRef.current = normalizeIntensity(intensity);
479
+ const [status, setStatus] = useState('idle');
480
+ const [stream, setStream] = useState(null);
481
+ const elements = useRef([]);
482
+ const request = useRef(0);
483
+ const streamRef = useRef(null);
484
+
485
+ const stop = () => {
486
+ request.current++;
487
+ streamRef.current?.getTracks().forEach(track => track.stop());
488
+ streamRef.current = null;
489
+ setStream(null);
490
+ setStatus('stopped');
491
+ };
492
+
493
+ useEffect(() => {
494
+ const onHidden = () => { if (document.hidden) stop(); };
495
+ document.addEventListener('visibilitychange', onHidden);
496
+ return () => {
497
+ document.removeEventListener('visibilitychange', onHidden);
498
+ request.current++;
499
+ streamRef.current?.getTracks().forEach(track => track.stop());
500
+ };
501
+ }, []);
502
+
503
+ const start = async () => {
504
+ const current = ++request.current;
505
+ if (!navigator.mediaDevices?.getUserMedia || !window.AudioContext) { setStatus('unavailable'); return; }
506
+ setStatus('pending');
507
+ try {
508
+ const audio = await navigator.mediaDevices.getUserMedia({ audio: { echoCancellation: false, noiseSuppression: false, autoGainControl: false }, video: false });
509
+ if (current !== request.current || document.hidden) { audio.getTracks().forEach(track => track.stop()); return; }
510
+ streamRef.current = audio;
511
+ setStream(audio);
512
+ setStatus('active');
513
+ } catch {
514
+ if (current === request.current) setStatus('unavailable');
515
+ }
516
+ };
517
+
518
+ useEffect(() => {
519
+ if (!stream) return;
520
+ let context;
521
+ let frame;
522
+ let active = true;
523
+ const onEnded = () => { if (active) { stop(); setStatus('unavailable'); } };
524
+ const tracks = stream.getAudioTracks();
525
+ tracks.forEach(track => track.addEventListener('ended', onEnded));
526
+ try {
527
+ context = new window.AudioContext();
528
+ const source = context.createMediaStreamSource(stream);
529
+ const analyser = context.createAnalyser();
530
+ analyser.fftSize = 1024;
531
+ source.connect(analyser);
532
+ const samples = new Float32Array(analyser.fftSize);
533
+ const reducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)');
534
+ let level = 0;
535
+ const animate = () => {
536
+ analyser.getFloatTimeDomainData(samples);
537
+ level = readLoudness(samples, level);
538
+ elements.current.forEach(element => {
539
+ if (!element) return;
540
+ element.style.transform = reducedMotion.matches ? '' : `scale(${1 + level * 0.08 * intensityRef.current})`;
541
+ element.style.boxShadow = `0 0 ${level * 30 * intensityRef.current}px rgba(182, 245, 91, ${Math.min(1, level * 0.7 * intensityRef.current)})`;
542
+ });
543
+ frame = requestAnimationFrame(animate);
544
+ };
545
+ context.resume().catch(onEnded);
546
+ frame = requestAnimationFrame(animate);
547
+ } catch { onEnded(); }
548
+ return () => {
549
+ active = false;
550
+ tracks.forEach(track => track.removeEventListener('ended', onEnded));
551
+ cancelAnimationFrame(frame);
552
+ context?.close();
553
+ stream.getTracks().forEach(track => track.stop());
554
+ elements.current.forEach(element => { if (element) { element.style.transform = ''; element.style.boxShadow = ''; } });
555
+ };
556
+ }, [stream]);
557
+
558
+ return React.createElement('div', { className },
559
+ React.createElement('button', { type: 'button', onClick: stream || status === 'pending' ? stop : start },
560
+ stream ? 'Stop microphone' : status === 'pending' ? 'Cancel microphone request' : 'Enable pulseUI'),
561
+ React.createElement('p', { role: 'status' }, {
562
+ idle: 'Enable the microphone, then play music, speak, or clap.',
563
+ pending: 'Waiting for microphone permission.',
564
+ active: 'Microphone active. Sound makes the cards pulse.',
565
+ stopped: 'Microphone stopped.',
566
+ unavailable: 'Microphone access is unavailable or denied. Check your browser settings and try again.'
567
+ }[status]),
568
+ React.Children.map(children, (child, index) => React.createElement('div', {
569
+ ref: element => { elements.current[index] = element; },
570
+ style: { display: 'inline-block', borderRadius: '10px' }
571
+ }, child))
572
+ );
573
+ }
574
+
575
+ export function GravityUI({ children, className, intensity = 1 }) {
576
+ const intensityRef = useRef(1);
577
+ intensityRef.current = normalizeIntensity(intensity);
578
+ const [status, setStatus] = useState('idle');
579
+ const [session, setSession] = useState(0);
580
+ const elements = useRef([]);
581
+ const request = useRef(0);
582
+
583
+ useEffect(() => () => { request.current++; }, []);
584
+
585
+ const enable = async () => {
586
+ const current = ++request.current;
587
+ if (!window.isSecureContext) { setStatus('insecure'); return; }
588
+ if (!window.DeviceOrientationEvent) { setStatus('unsupported'); return; }
589
+ setStatus('permission');
590
+ try {
591
+ if (typeof window.DeviceOrientationEvent.requestPermission === 'function' &&
592
+ await window.DeviceOrientationEvent.requestPermission() !== 'granted') {
593
+ if (current === request.current) setStatus('denied');
594
+ return;
595
+ }
596
+ } catch {
597
+ if (current === request.current) setStatus('denied');
598
+ return;
599
+ }
600
+ if (current !== request.current) return;
601
+ setStatus('starting');
602
+ setSession(value => value + 1);
603
+ };
604
+
605
+ useEffect(() => {
606
+ if (!session) return;
607
+ const reducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)');
608
+ const timeout = setTimeout(() => setStatus('unavailable'), 8000);
609
+ const onOrientation = event => {
610
+ const motion = gravityMotion(event.beta, event.gamma, window.screen.orientation?.angle ?? window.orientation ?? 0);
611
+ if (!motion) return;
612
+ clearTimeout(timeout);
613
+ setStatus('active');
614
+ elements.current.forEach(element => {
615
+ if (element) element.style.transform = reducedMotion.matches ? '' : `translate(${motion.x * intensityRef.current}px, ${motion.y * intensityRef.current}px)`;
616
+ });
617
+ };
618
+ const onReducedMotion = () => {
619
+ elements.current.forEach(element => {
620
+ if (!element) return;
621
+ element.style.transition = reducedMotion.matches ? 'none' : 'transform 0.2s ease-out';
622
+ if (reducedMotion.matches) element.style.transform = '';
623
+ });
624
+ };
625
+ onReducedMotion();
626
+ window.addEventListener('deviceorientation', onOrientation);
627
+ reducedMotion.addEventListener('change', onReducedMotion);
628
+ return () => {
629
+ window.removeEventListener('deviceorientation', onOrientation);
630
+ reducedMotion.removeEventListener('change', onReducedMotion);
631
+ clearTimeout(timeout);
632
+ elements.current.forEach(element => { if (element) element.style.transform = ''; });
633
+ };
634
+ }, [session]);
635
+
636
+ return React.createElement('div', { className },
637
+ React.createElement('button', { type: 'button', onClick: enable, disabled: ['permission', 'starting', 'active'].includes(status) }, status === 'active' ? 'GravityUI enabled' : session ? 'Try gravityUI again' : 'Enable gravityUI'),
638
+ React.createElement('p', { role: 'status' }, {
639
+ idle: 'Enable gravityUI, then tilt your phone.',
640
+ permission: 'Waiting for orientation permission.',
641
+ starting: 'Waiting for an orientation reading.',
642
+ active: 'Tilt your phone to move the cards toward the lower edge.',
643
+ insecure: 'Orientation sensing requires HTTPS or localhost.',
644
+ unsupported: 'This browser does not provide device orientation.',
645
+ denied: 'Orientation access was denied. Check your browser settings and try again.',
646
+ unavailable: 'No orientation reading was received. Check your device and browser settings, then try again.'
647
+ }[status]),
648
+ React.Children.map(children, (child, index) => React.createElement('div', {
649
+ ref: element => { elements.current[index] = element; },
650
+ style: { display: 'inline-block', transition: 'transform 0.2s ease-out' }
651
+ }, child))
652
+ );
653
+ }