sensor-based-mobile-ui 0.0.0-stage → 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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 shellkore
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,184 @@
1
- # Temporary Holding Version
1
+ # Sensor-Based Mobile UI
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A UI library in development for building interfaces that respond to mobile device sensors. The goal is to offer a selection of reusable UI templates and components for React, Next.js, and React Native, so developers can choose the experience that fits their app.
4
+
5
+ [Explore the live demo](https://sensor-based-mobile-ui.vercel.app/) · [Read the documentation](https://sensor-based-mobile-ui.vercel.app/docs)
6
+
7
+ If you like this project, please [star the repository](https://github.com/shellkore/sensor-based-mobile-ui) and consider sponsoring its development.
8
+
9
+ ## Project status
10
+
11
+ `ScaredUI`, `CompassUI`, `TornadoUI`, `EarthquakeUI`, `PulseUI`, and `GravityUI` are available for React and Next.js. React Native support is planned.
12
+
13
+ In the next npm release, all components accept an `intensity` prop to control the strength of the visual effect. The default is `1`; use `0` for no effect, `0.5` for a gentler effect, or `2` for a stronger effect. Values are clamped to the range `0`–`2`; invalid values default to `1`. Changing the prop updates the effect while it is active. Sensor permissions and reduced-motion settings still apply.
14
+
15
+ ```jsx
16
+ <GravityUI intensity={0.5}><button>One</button></GravityUI>
17
+ ```
18
+
19
+ ### gravityUI
20
+
21
+ `GravityUI` slides its direct children toward the lower edge as the phone tilts. Hold the phone flat to return them to their original positions.
22
+
23
+ ```jsx
24
+ import { GravityUI } from 'sensor-based-mobile-ui';
25
+
26
+ <GravityUI><button>One</button><button>Two</button></GravityUI>
27
+ ```
28
+
29
+ Tap Enable and allow orientation access if prompted. HTTPS or localhost and a device and browser providing orientation readings are required. Unsupported or denied access leaves children usable. The effect respects reduced-motion preferences. Each direct child receives an inline-block wrapper; React 18 or newer and a client component in Next.js are required.
30
+
31
+ ### pulseUI
32
+
33
+ `PulseUI` expands and glows around its direct children in response to microphone loudness, then settles as the sound gets quieter.
34
+
35
+ ```jsx
36
+ import { PulseUI } from 'sensor-based-mobile-ui';
37
+
38
+ <PulseUI><button>One</button><button>Two</button></PulseUI>
39
+ ```
40
+
41
+ Tap Enable and allow microphone access. HTTPS or localhost, a microphone, and a compatible browser are required. Audio is processed locally and is not recorded or sent. The microphone stops when stopped, the page is hidden, or the component unmounts. Denied or unavailable access leaves children usable. Scaling respects reduced-motion preferences. Each direct child receives an inline-block wrapper; React 18 or newer and a client component in Next.js are required. Microphone sensitivity and browser audio processing affect the response.
42
+
43
+ ### earthquakeUI
44
+
45
+ `EarthquakeUI` shakes and displaces its direct children in response to phone acceleration. Stronger movement creates a larger effect; after movement stops, the children slowly return to their original positions.
46
+
47
+ ```jsx
48
+ import { EarthquakeUI } from 'sensor-based-mobile-ui';
49
+
50
+ <EarthquakeUI><button>One</button><button>Two</button></EarthquakeUI>
51
+ ```
52
+
53
+ Tap Enable and allow motion access if prompted. HTTPS or localhost and a browser and device providing acceleration readings are required. Unsupported or denied access leaves children usable. The effect respects reduced-motion preferences. Each direct child receives an inline-block wrapper; React 18 or newer and a client component in Next.js are required.
54
+
55
+ ### tornadoUI
56
+
57
+ `TornadoUI` moves its direct children in a swirling pattern when the phone rotates quickly. The effect fades when movement stops.
58
+
59
+ ```jsx
60
+ import { TornadoUI } from 'sensor-based-mobile-ui';
61
+
62
+ <TornadoUI>
63
+ <button>One</button>
64
+ <button>Two</button>
65
+ </TornadoUI>
66
+ ```
67
+
68
+ Tap Enable and allow motion access if prompted. This requires HTTPS or localhost and a browser and device that provide rotation-rate readings; access can also be blocked by browser or embedding settings. If unavailable, the children remain usable. Motion is disabled when the user prefers reduced motion. Each direct child receives an inline-block wrapper, which can change its layout. React 18 or newer is required; use a client component in Next.js.
69
+
70
+ ### scaredUI
71
+
72
+ `ScaredUI` wraps each direct child and moves it when a shadow falls on the device's ambient light sensor. When the sensor is unavailable, users can opt in to a front-camera fallback that estimates changes in brightness. The interface keeps shaking and compresses vertically while the view is darker, with a stronger effect as it gets darker; a faster drop also causes temporary displacement. The first reading after enabling or recalibrating is the baseline, so keep the sensor or camera uncovered until calibration finishes.
73
+
74
+ By default, controls appear before the children and stay still. Set `controlsAfter` to a zero-based child index to place them after that child, and set `animateControls` to make the controls move too.
75
+
76
+ ```jsx
77
+ import { ScaredUI } from 'sensor-based-mobile-ui';
78
+
79
+ export default function Example() {
80
+ return (
81
+ <ScaredUI>
82
+ <button>One</button>
83
+ <button>Two</button>
84
+ </ScaredUI>
85
+ );
86
+ }
87
+ ```
88
+
89
+ React 18 or newer is a peer dependency. For Next.js, use this component from a client component. Sensor and camera access require a secure context (HTTPS or localhost), compatible hardware, and permission. Unsupported or denied access leaves the children usable and displays a message. Neither method measures distance: lighting changes and shadows can also trigger the effect. Recalibrate when the surrounding light changes. Motion is disabled when the user prefers reduced motion.
90
+
91
+ Safari and Chrome on iPhone do not currently expose the ambient light sensor through this API, so users can choose the camera fallback. It requests the front camera without audio and processes small frames locally; video is not saved or sent anywhere. The camera stops when the user selects Stop camera, leaves the page, or switches away from the tab. Cover enough of the front camera's view to darken it. Automatic exposure and changes in the scene can affect the response. Some Chromium browsers expose the sensor only behind an experimental flag.
92
+
93
+ Each direct child gets an inline-block wrapper, so its layout may differ from an unwrapped child. Use direct children for elements that should move independently.
94
+
95
+ ### compassUI
96
+
97
+ `CompassUI` shifts its direct children toward magnetic north. Hold the phone flat with the screen facing up in portrait orientation, enable the experience, and rotate the phone: when its top points north, the children move up; when it points east, they move left. No starting direction or recalibration is needed.
98
+
99
+ ```jsx
100
+ import { CompassUI } from 'sensor-based-mobile-ui';
101
+
102
+ export default function Example() {
103
+ return (
104
+ <CompassUI>
105
+ <button>Explore</button>
106
+ <button>Discover</button>
107
+ </CompassUI>
108
+ );
109
+ }
110
+ ```
111
+
112
+ `MagneticUI` remains available as an alias for existing users. Magnetic sensing requires a secure context (HTTPS or localhost), compatible hardware, and permission. Where the browser exposes `Magnetometer`, the effect uses its x and y field readings to estimate magnetic north when the phone is flat. On iPhone, browsers can instead use the compass heading from device orientation events; tap Enable and allow motion and orientation access when prompted. Rotate the phone to see the effect. The compass fallback uses heading rather than field strength, and neither method locates a magnet. Magnetic north differs from geographic north; nearby magnets and tilted devices can affect accuracy. Support varies, and browser settings or embedding policies can block access. If access is unavailable or denied, the children remain usable and a message is displayed. Motion is limited and disabled when the user prefers reduced motion. As with `ScaredUI`, each direct child receives an inline-block wrapper. React 18 or newer is required; in Next.js, use a client component.
113
+
114
+ ## Planned structure
115
+
116
+ ```text
117
+ src/
118
+ core/ Shared, platform-independent behavior
119
+ react/ React and Next.js UI components and templates
120
+ react-native/ React Native UI components and templates
121
+ examples/
122
+ web/ React and Next.js examples
123
+ mobile/ React Native examples
124
+ demos/ Vercel-ready React app for interactive web demos
125
+ ```
126
+
127
+ Each platform can offer multiple UI options. Shared code should remain independent of browser and native APIs; platform-specific code will handle device access and presentation. Sensor selection, permissions, fallback behavior, and accessibility will be designed alongside each feature.
128
+
129
+ ## Getting started
130
+
131
+ Install the package in a React 18 or newer application:
132
+
133
+ ```bash
134
+ npm install sensor-based-mobile-ui
135
+ ```
136
+
137
+ For Next.js, import the components from a client component:
138
+
139
+ ```jsx
140
+ 'use client';
141
+
142
+ import { GravityUI } from 'sensor-based-mobile-ui';
143
+
144
+ export default function Example() {
145
+ return <GravityUI><button>Tilt your phone</button></GravityUI>;
146
+ }
147
+ ```
148
+
149
+ To work on the library locally, clone the repository:
150
+
151
+ ```bash
152
+ git clone https://github.com/shellkore/sensor-based-mobile-ui.git
153
+ cd sensor-based-mobile-ui
154
+ ```
155
+
156
+ You can also install the package from a local checkout alongside React. Run `npm test` to check the shared behavior. There is no build step.
157
+
158
+ To run or deploy the interactive demo app, see [demos/README.md](demos/README.md).
159
+
160
+ ## Contributing
161
+
162
+ Work on a feature branch and open a pull request to `main`. The Verify workflow runs the tests, builds the demo, and checks the npm package. Merge only after the checks and review pass. Configure a GitHub branch protection rule or ruleset for `main` to require a pull request and the `test` status check; the workflow alone does not prevent direct pushes or merges.
163
+
164
+ Use conventional commit messages (and a conventional pull request title when using squash merge), since semantic-release reads the commits that land on `main`:
165
+
166
+ - `fix: correct motion handling` publishes a patch release.
167
+ - `feat: add intensity control` publishes a minor release.
168
+ - A commit containing a `BREAKING CHANGE:` footer publishes a major release.
169
+ - `docs: ...`, `test: ...`, and `chore: ...` do not normally trigger a release.
170
+
171
+ After a push or merge to `main`, the Release workflow reruns the checks and, if the commits warrant it, publishes to npm and creates a GitHub release and tag. It uses GitHub Actions trusted publishing, so no npm token is needed. The repository's `package.json` version is not committed on each release; semantic-release sets the published version based on Git tags.
172
+
173
+ ### One-time release setup
174
+
175
+ 1. In [npm package settings](https://www.npmjs.com/package/sensor-based-mobile-ui/access), configure a GitHub Actions trusted publisher for owner `shellkore`, repository `sensor-based-mobile-ui`, and workflow filename `release.yml`. Allow publishing, and leave the environment name blank. The workflow must exist on GitHub before npm can validate it.
176
+ 2. Add and push a `v0.1.0` tag on the commit corresponding to the already published npm version. The initial npm package was published from a working tree with uncommitted changes, so first verify the closest appropriate baseline in the repository; do not tag the later intensity change as already released. Semantic-release uses this tag as its release baseline. The workflow refuses to release until the tag exists in main's history.
177
+ 3. The existing intensity commit is named `Add configurable effect intensity`, so it does not itself trigger semantic-release. To include it in the next release, merge a pull request with an appropriate conventional `feat:` commit or squash title after the baseline tag. This will include all changes since the baseline.
178
+ 4. Enable GitHub Actions. GitHub automatically supplies `secrets.GITHUB_TOKEN`; do not create a repository secret with that name or add a personal access token. The Release job requests the write permissions needed to create releases and tags, plus `id-token: write` for npm trusted publishing. No `NPM_TOKEN` repository secret is needed. Configure the branch rules mentioned above. Once the trusted publisher and tag are set up, rerun the Release workflow from the Actions tab if needed.
179
+
180
+ Releases are fully automatic when qualifying changes reach `main`; test changes on the pull request before merging.
181
+
182
+ ## License
183
+
184
+ This project is licensed under the [MIT License](LICENSE).
package/package.json CHANGED
@@ -1,6 +1,41 @@
1
1
  {
2
2
  "name": "sensor-based-mobile-ui",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "type": "module",
5
+ "exports": {
6
+ ".": "./src/react/index.js"
7
+ },
8
+ "files": [
9
+ "src",
10
+ "!src/**/*.test.js"
11
+ ],
12
+ "scripts": {
13
+ "test": "node --test",
14
+ "prepublishOnly": "npm test"
15
+ },
16
+ "publishConfig": {
17
+ "access": "public",
18
+ "registry": "https://registry.npmjs.org/"
19
+ },
20
+ "peerDependencies": {
21
+ "react": ">=18"
22
+ },
23
+ "description": "Sensor-responsive UI components for React and Next.js",
24
+ "homepage": "https://sensor-based-mobile-ui.vercel.app/",
25
+ "bugs": {
26
+ "url": "https://github.com/shellkore/sensor-based-mobile-ui/issues"
27
+ },
28
+ "repository": {
29
+ "type": "git",
30
+ "url": "https://github.com/shellkore/sensor-based-mobile-ui.git"
31
+ },
32
+ "keywords": [
33
+ "ui",
34
+ "mobile",
35
+ "sensors",
36
+ "react",
37
+ "nextjs",
38
+ "react-native"
39
+ ],
40
+ "license": "MIT"
41
+ }
@@ -0,0 +1,3 @@
1
+ # Shared core
2
+
3
+ The scaredUI, compassUI, tornadoUI, earthquakeUI, pulseUI, and gravityUI models convert sensor and audio readings into effects independently of browser APIs.
@@ -0,0 +1,21 @@
1
+ export function readEarthquake(acceleration, time, previous = null) {
2
+ if (!acceleration || ![acceleration.x, acceleration.y, acceleration.z].some(Number.isFinite) || !Number.isFinite(time)) return null;
3
+ const strength = Math.hypot(...[acceleration.x, acceleration.y, acceleration.z].map(value => Number.isFinite(value) ? value : 0));
4
+ const intensity = Math.min(1, Math.max(0, (strength - 1.5) / 13));
5
+ if (!intensity) return previous || { intensity: 0, time };
6
+ return { intensity, time };
7
+ }
8
+
9
+ export function earthquakeMotion(state, time, index) {
10
+ if (!state) return { x: 0, y: 0, rotate: 0 };
11
+ const elapsed = Math.max(0, time - state.time);
12
+ const returnScale = Math.max(0, 1 - Math.max(0, elapsed - 2000) / 6000);
13
+ const shake = Math.max(0, 1 - elapsed / 2000);
14
+ const direction = index % 2 ? -1 : 1;
15
+ const intensity = state.intensity * returnScale;
16
+ return {
17
+ x: intensity * direction * (65 + 35 * shake * Math.sin(time / 45 + index)),
18
+ y: intensity * (index % 3 - 1) * (40 + 25 * shake * Math.cos(time / 55 + index)),
19
+ rotate: intensity * direction * (12 + 8 * shake * Math.sin(time / 60 + index))
20
+ };
21
+ }
@@ -0,0 +1,8 @@
1
+ export function gravityMotion(beta, gamma, angle = 0) {
2
+ if (!Number.isFinite(beta) || !Number.isFinite(gamma)) return null;
3
+ const radians = Math.PI / 180;
4
+ const x = Math.sin(gamma * radians) * Math.cos(beta * radians);
5
+ const y = Math.sin(beta * radians);
6
+ const rotation = (Number.isFinite(angle) ? angle : 0) * radians;
7
+ return { x: 80 * (x * Math.cos(rotation) - y * Math.sin(rotation)), y: 80 * (x * Math.sin(rotation) + y * Math.cos(rotation)) };
8
+ }
@@ -0,0 +1,3 @@
1
+ export function normalizeIntensity(value) {
2
+ return typeof value === 'number' && Number.isFinite(value) ? Math.max(0, Math.min(2, value)) : 1;
3
+ }
@@ -0,0 +1,21 @@
1
+ export function createMagneticState() {
2
+ return { field: null };
3
+ }
4
+
5
+ export function readMagneticField(state, x, y) {
6
+ if (!Number.isFinite(x) || !Number.isFinite(y) || Math.hypot(x, y) === 0) return state;
7
+ return { field: { x, y } };
8
+ }
9
+
10
+ export function readMagneticHeading(state, heading) {
11
+ if (!Number.isFinite(heading) || heading < 0 || heading >= 360) return state;
12
+ const radians = heading * Math.PI / 180;
13
+ return readMagneticField(state, -Math.sin(radians), Math.cos(radians));
14
+ }
15
+
16
+ export function magneticMotion(state) {
17
+ if (!state.field) return { x: 0, y: 0 };
18
+ const { x, y } = state.field;
19
+ const scale = 48 / Math.hypot(x, y);
20
+ return { x: x ? x * scale : 0, y: y ? -y * scale : 0 };
21
+ }
@@ -0,0 +1,6 @@
1
+ export function readLoudness(samples, previous = 0) {
2
+ if (!samples.length) return 0;
3
+ const rms = Math.sqrt(samples.reduce((sum, sample) => sum + sample * sample, 0) / samples.length);
4
+ const target = Math.min(1, Math.max(0, (rms - 0.003) * 10));
5
+ return previous + (target - previous) * (target > previous ? 0.45 : 0.08);
6
+ }
@@ -0,0 +1,35 @@
1
+ export function createScaredState() {
2
+ return { baseline: null, light: null, time: null, impulse: 0 };
3
+ }
4
+
5
+ export function frameBrightness(pixels) {
6
+ let total = 0;
7
+ for (let i = 0; i < pixels.length; i += 4) {
8
+ total += pixels[i] * 0.2126 + pixels[i + 1] * 0.7152 + pixels[i + 2] * 0.0722;
9
+ }
10
+ return pixels.length ? total / (pixels.length / 4) : 0;
11
+ }
12
+
13
+ export function readLight(state, light, time) {
14
+ if (!Number.isFinite(light) || light < 0 || !Number.isFinite(time)) return state;
15
+ // shortcut: the first reading is the baseline; use sampled calibration if hardware readings are noisy.
16
+ if (state.baseline === null) return { baseline: light, light, time, impulse: 0 };
17
+ const elapsed = Math.max((time - state.time) / 1000, 0.05);
18
+ const drop = Math.max(0, (state.light - light) / Math.max(state.baseline, 1));
19
+ return { ...state, light, time, impulse: Math.max(state.impulse * Math.exp(-elapsed * 2), Math.min(drop / elapsed, 1)) };
20
+ }
21
+
22
+ export function scaredMotion(state, time, index) {
23
+ if (state.baseline === null || state.baseline < 1) return { x: 0, y: 0, rotate: 0, scaleY: 1 };
24
+ const elapsed = Math.max(0, (time - state.time) / 1000);
25
+ const darkness = Math.max(0, Math.min(1, (state.baseline - state.light) / state.baseline));
26
+ const impulse = state.impulse * Math.exp(-elapsed * 2);
27
+ const shake = darkness * (22 + impulse * 12);
28
+ const phase = time / 35 + index * 2.4;
29
+ return {
30
+ x: Math.sin(phase) * shake + Math.sin(index * 7) * impulse * darkness * 18,
31
+ y: Math.cos(phase * 1.3) * shake + Math.cos(index * 5) * impulse * darkness * 18,
32
+ rotate: Math.sin(phase * 0.8) * shake * 0.45 + Math.sin(index * 3) * impulse * darkness * 5,
33
+ scaleY: 1 - darkness * 0.25
34
+ };
35
+ }
@@ -0,0 +1,14 @@
1
+ export function readRotation(rate, time, previous = null) {
2
+ if (!rate || ![rate.alpha, rate.beta, rate.gamma].some(Number.isFinite) || !Number.isFinite(time)) return null;
3
+ const speed = Math.hypot(...[rate.alpha, rate.beta, rate.gamma].map(value => Number.isFinite(value) ? value : 0));
4
+ const remaining = previous ? previous.intensity * Math.exp(-Math.max(0, time - previous.time) / 700) : 0;
5
+ return { intensity: Math.max(remaining, Math.min(1, Math.max(0, (speed - 30) / 150))), time };
6
+ }
7
+
8
+ export function tornadoMotion(state, time, x, y) {
9
+ const intensity = state ? state.intensity * Math.exp(-Math.max(0, time - state.time) / 700) : 0;
10
+ const phase = time / 400;
11
+ const cos = Math.cos(phase);
12
+ const sin = Math.sin(phase);
13
+ return { x: ((x + 40) * cos - y * sin - x) * intensity, y: ((x + 40) * sin + y * cos - y) * intensity };
14
+ }
@@ -0,0 +1,3 @@
1
+ # React and Next.js
2
+
3
+ `ScaredUI`, `CompassUI`, `TornadoUI`, `EarthquakeUI`, `PulseUI`, and `GravityUI` are web components. See the root README for usage, calibration, and browser requirements. Sensor access starts only on the client after the user enables it.
@@ -0,0 +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
+ 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
+ }
@@ -0,0 +1,3 @@
1
+ # React Native
2
+
3
+ Native components and UI templates belong here. Platform-specific sensor access and permissions will be chosen with each feature.