@adriansteffan/reactive 0.2.5 → 0.2.6

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,4 +1,4 @@
1
- import { W as P, b as x, E } from "./mod-CHZCELgX.js";
1
+ import { W as P, b as x, E } from "./mod-HDegGPrf.js";
2
2
  function m(w) {
3
3
  const e = w.split("/").filter((t) => t !== "."), r = [];
4
4
  return e.forEach((t) => {
@@ -1,4 +1,4 @@
1
- import { W as e } from "./mod-CHZCELgX.js";
1
+ import { W as e } from "./mod-HDegGPrf.js";
2
2
  class s extends e {
3
3
  async enable() {
4
4
  console.log("Immersive mode is only available on Android");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adriansteffan/reactive",
3
- "version": "0.2.5",
3
+ "version": "0.2.6",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "dev": "vite",
@@ -2,6 +2,7 @@ import React, { useState, useCallback, useRef, useEffect } from 'react';
2
2
  import { BaseComponentProps, getPlatform, isFullscreen } from '../utils/common';
3
3
  import { registerSimulation, noopSimulate } from '../utils/simulation';
4
4
  import { registerFlattener } from '../utils/upload';
5
+ import { registerOverlay, OverlayProps } from '../utils/overlays';
5
6
  import Text from '../components/text';
6
7
  import { StatusBar } from '@capacitor/status-bar';
7
8
  import { ImmersiveMode } from '@adriansteffan/immersive-mode';
@@ -11,6 +12,73 @@ import { useTheme, t } from '../utils/theme';
11
12
  registerFlattener('EnterFullscreen', 'session');
12
13
  registerSimulation('EnterFullscreen', noopSimulate, {});
13
14
 
15
+ function FullscreenGuard({ store }: OverlayProps) {
16
+ const [fs, setFs] = useState(isFullscreen());
17
+ const cfg = store?._fullscreenGuard as FullscreenGuardConfig | undefined;
18
+ const active = !!cfg;
19
+
20
+ useEffect(() => {
21
+ if (!active) return;
22
+ setFs(isFullscreen());
23
+ let interval: ReturnType<typeof setInterval> | null = null;
24
+ const timeout = setTimeout(() => {
25
+ interval = setInterval(() => setFs(isFullscreen()), 3000);
26
+ }, 5000);
27
+ return () => {
28
+ clearTimeout(timeout);
29
+ if (interval) clearInterval(interval);
30
+ };
31
+ }, [active]);
32
+ if (!cfg || fs) return null;
33
+
34
+ const reenter = async () => {
35
+ const el = document.documentElement as any;
36
+ try {
37
+ // Clear stale DOM fullscreen state first — on macOS Chrome after ESC,
38
+ // fullscreenElement may still be set even though the window is windowed,
39
+ // causing requestFullscreen to silently no-op.
40
+ if (document.fullscreenElement) {
41
+ await document.exitFullscreen().catch(() => {});
42
+ }
43
+ if (el.requestFullscreen) await el.requestFullscreen();
44
+ else if (el.webkitRequestFullscreen) await el.webkitRequestFullscreen();
45
+ else if (el.mozRequestFullScreen) await el.mozRequestFullScreen();
46
+ else if (el.msRequestFullscreen) await el.msRequestFullscreen();
47
+ } catch (err) {
48
+ console.error('[FullscreenGuard] requestFullscreen failed:', err);
49
+ }
50
+ };
51
+ const buttonText = cfg.buttonText ?? 'Return to Fullscreen';
52
+ const btnClass = 'px-6 py-3 bg-white text-black text-sm font-bold border-2 border-black rounded-xl shadow-[2px_2px_0px_rgba(0,0,0,1)] hover:translate-x-[1px] hover:translate-y-[1px] hover:shadow-none cursor-pointer';
53
+
54
+ if (cfg.mode === 'overlay') {
55
+ return (
56
+ <div className='fixed inset-0 z-50 bg-white flex flex-col items-center justify-center gap-6 p-8 text-center'>
57
+ {cfg.content ?? (
58
+ <>
59
+ <h1 className='text-3xl font-bold'>Please return to fullscreen</h1>
60
+ <p>This experiment requires fullscreen mode. Click the button below to continue.</p>
61
+ </>
62
+ )}
63
+ <button onClick={reenter} className={btnClass}>{buttonText}</button>
64
+ </div>
65
+ );
66
+ }
67
+ return (
68
+ <button onClick={reenter} className={`fixed top-6 left-6 z-50 ${btnClass}`}>
69
+ {buttonText}
70
+ </button>
71
+ );
72
+ }
73
+
74
+ interface FullscreenGuardConfig {
75
+ mode?: 'button' | 'overlay';
76
+ buttonText?: string;
77
+ content?: React.ReactNode;
78
+ }
79
+
80
+ registerOverlay(FullscreenGuard);
81
+
14
82
  export default function EnterFullscreen({
15
83
  content,
16
84
  buttonText,
@@ -22,6 +90,7 @@ export default function EnterFullscreen({
22
90
  data,
23
91
  updateStore,
24
92
  delayMs = 0,
93
+ keepFullscreen = false,
25
94
  }: {
26
95
  prolificCode?: string;
27
96
  content?: React.ReactNode;
@@ -31,6 +100,10 @@ export default function EnterFullscreen({
31
100
  centered?: boolean;
32
101
  animate?: boolean;
33
102
  delayMs?: number;
103
+ /** Show a prompt to re-enter fullscreen on every subsequent trial until ExitFullscreen runs.
104
+ * `true` renders a small top-left button with default text.
105
+ * Pass a config to customize the button text, or switch to a full-screen overlay with custom content. */
106
+ keepFullscreen?: boolean | FullscreenGuardConfig;
34
107
  } & BaseComponentProps) {
35
108
  const contentWrap = (
36
109
  <div className='flex flex-col items-center'>
@@ -62,12 +135,15 @@ export default function EnterFullscreen({
62
135
  const proceedWithDelay = useCallback(() => {
63
136
  cancelPendingTimeout();
64
137
  setIsWaiting(true);
138
+ if (keepFullscreen) {
139
+ updateStore({ _fullscreenGuard: keepFullscreen === true ? {} : keepFullscreen });
140
+ }
65
141
  timeoutId.current = setTimeout(() => {
66
142
  timeoutId.current = null;
67
143
 
68
144
  next({});
69
145
  }, delayMs);
70
- }, [next, delayMs, cancelPendingTimeout]);
146
+ }, [next, delayMs, cancelPendingTimeout, keepFullscreen, updateStore]);
71
147
 
72
148
  const handleFullscreenChangeForFallback = useCallback(() => {
73
149
  if (!listenerFallbackActive.current) return;
@@ -11,6 +11,7 @@ registerSimulation('ExitFullscreen', noopSimulate, {});
11
11
 
12
12
  export default function ExitFullscreen({
13
13
  next,
14
+ updateStore,
14
15
  delayMs = 0,
15
16
  }: {
16
17
  delayMs?: number;
@@ -62,6 +63,7 @@ export default function ExitFullscreen({
62
63
  }, [handleFullscreenChangeForFallback, removeListenersAndTimeout]);
63
64
 
64
65
  useEffect(() => {
66
+ updateStore({ _fullscreenGuard: null });
65
67
  const performExitFullscreen = async () => {
66
68
  if (!isFullscreen()) {
67
69
  next({});
@@ -19,6 +19,7 @@ import {
19
19
  import { useHybridSimulationDisabled } from './experimentprovider';
20
20
  import { ThemeContext, t } from '../utils/theme';
21
21
  import { AudioDeviceContext } from '../utils/audiodevice';
22
+ import { getOverlays } from '../utils/overlays';
22
23
  import { v4 as uuidv4 } from 'uuid';
23
24
 
24
25
  import Upload from './upload';
@@ -454,6 +455,9 @@ export default function ExperimentRunner({
454
455
  </div>
455
456
  </div>
456
457
  {componentToRender}
458
+ {getOverlays().map((O, i) => (
459
+ <O key={i} store={experimentStoreRef.current} updateStore={updateStore} data={dataRef.current} />
460
+ ))}
457
461
  {showDev && (
458
462
  <>
459
463
  <button
@@ -90,7 +90,7 @@ function MicrophoneSelect({
90
90
  );
91
91
  }
92
92
 
93
- const MicrophoneCheck = ({ next, updateStore, animate = false }: BaseComponentProps & { animate?: boolean }) => {
93
+ const MicrophoneCheck = ({ next, updateStore, animate = false, discardLabel }: BaseComponentProps & { animate?: boolean; discardLabel?: string }) => {
94
94
  const th = t(useTheme());
95
95
  const [recordingExists, setRecordingExists] = useState(false);
96
96
  const [isRecording, setIsRecording] = useState(false);
@@ -120,14 +120,17 @@ const MicrophoneCheck = ({ next, updateStore, animate = false }: BaseComponentPr
120
120
  </p>
121
121
  </article>
122
122
 
123
- <VoiceRecorder
124
- onRecordingStart={() => setIsRecording(true)}
125
- handleSaveVoiceData={() => { setRecordingExists(true); setIsRecording(false); }}
126
- handleDiscardVoiceData={() => { setRecordingExists(false); setIsRecording(false); }}
127
- deviceId={selectedDeviceId}
128
- showPause={false}
129
- showDiscard={false}
130
- />
123
+ <div className='mt-4 mb-12'>
124
+ <VoiceRecorder
125
+ onRecordingStart={() => setIsRecording(true)}
126
+ handleSaveVoiceData={() => { setRecordingExists(true); setIsRecording(false); }}
127
+ handleDiscardVoiceData={() => { setRecordingExists(false); setIsRecording(false); }}
128
+ deviceId={selectedDeviceId}
129
+ showPause={false}
130
+ showDiscard={false}
131
+ discardLabel={discardLabel}
132
+ />
133
+ </div>
131
134
 
132
135
  {recordingExists && (
133
136
  <div className='animate-fade-in opacity-0'>
@@ -103,6 +103,12 @@ export interface VoiceRecorderProps {
103
103
  showVisualizer?: boolean;
104
104
  /** Show a discard button while recording to delete and start over. */
105
105
  showDiscard?: boolean;
106
+ /** Label for the post-recording discard button. */
107
+ discardLabel?: string;
108
+ /** If set, show a "speak up" banner after this many seconds of continuous silence. Disabled when undefined. */
109
+ silenceWarningSec?: number;
110
+ /** Text shown in the silence banner. */
111
+ silenceWarningText?: string;
106
112
  onRecordingStart?: () => void;
107
113
  onPause?: (duration: number) => void;
108
114
  onResume?: () => void;
@@ -118,6 +124,9 @@ export const VoiceRecorder = forwardRef<VoiceRecorderHandle, VoiceRecorderProps>
118
124
  showStop = true,
119
125
  showVisualizer = true,
120
126
  showDiscard = true,
127
+ discardLabel = 'New Recording',
128
+ silenceWarningSec,
129
+ silenceWarningText = 'We can\'t hear you — please speak up',
121
130
  onRecordingStart,
122
131
  onPause,
123
132
  onResume,
@@ -131,6 +140,7 @@ export const VoiceRecorder = forwardRef<VoiceRecorderHandle, VoiceRecorderProps>
131
140
  const [isPaused, setIsPaused] = useState<boolean>(false);
132
141
  const [audioUrl, setAudioUrl] = useState<string | null>(null);
133
142
  const [audioStream, setAudioStream] = useState<MediaStream | null>(null);
143
+ const [showSilenceBanner, setShowSilenceBanner] = useState(false);
134
144
  const mediaRecorderRef = useRef<MediaRecorder | null>(null);
135
145
  const chunksRef = useRef<BlobPart[]>([]);
136
146
 
@@ -155,6 +165,47 @@ export const VoiceRecorder = forwardRef<VoiceRecorderHandle, VoiceRecorderProps>
155
165
 
156
166
  useImperativeHandle(ref, () => ({ stop: stopRecording }));
157
167
 
168
+ // Silence detection: analyze the mic stream every 100ms; trigger banner when
169
+ // RMS stays below threshold for silenceWarningSec seconds continuously.
170
+ useEffect(() => {
171
+ if (!audioStream || !silenceWarningSec || isPaused) {
172
+ setShowSilenceBanner(false);
173
+ return;
174
+ }
175
+ const AudioCtx = (window.AudioContext || (window as any).webkitAudioContext);
176
+ const audioCtx = new AudioCtx();
177
+ const analyser = audioCtx.createAnalyser();
178
+ analyser.fftSize = 2048;
179
+ const source = audioCtx.createMediaStreamSource(audioStream);
180
+ source.connect(analyser);
181
+ const timeData = new Uint8Array(analyser.fftSize);
182
+
183
+ let silenceMs = 0;
184
+ const tick = setInterval(() => {
185
+ analyser.getByteTimeDomainData(timeData);
186
+ let sum = 0;
187
+ for (let i = 0; i < timeData.length; i++) {
188
+ const n = (timeData[i] - 128) / 128;
189
+ sum += n * n;
190
+ }
191
+ const rms = Math.sqrt(sum / timeData.length);
192
+ if (rms < 0.02) {
193
+ silenceMs += 100;
194
+ if (silenceMs >= silenceWarningSec * 1000) setShowSilenceBanner(true);
195
+ } else {
196
+ silenceMs = 0;
197
+ setShowSilenceBanner(false);
198
+ }
199
+ }, 100);
200
+
201
+ return () => {
202
+ clearInterval(tick);
203
+ source.disconnect();
204
+ audioCtx.close();
205
+ setShowSilenceBanner(false);
206
+ };
207
+ }, [audioStream, silenceWarningSec, isPaused]);
208
+
158
209
  const startRecording = async () => {
159
210
  try {
160
211
  const resolvedDeviceId = deviceId ?? contextDeviceId;
@@ -266,6 +317,11 @@ export const VoiceRecorder = forwardRef<VoiceRecorderHandle, VoiceRecorderProps>
266
317
 
267
318
  return (
268
319
  <div className='flex flex-col items-center space-y-4 p-4 px-8'>
320
+ {showSilenceBanner && (
321
+ <div className='fixed top-0 left-0 right-0 z-40 bg-yellow-300 text-black text-center py-3 px-4 border-b-2 border-black font-semibold shadow-[0px_2px_0px_rgba(0,0,0,1)]'>
322
+ {silenceWarningText}
323
+ </div>
324
+ )}
269
325
  {/* Start button */}
270
326
  {!audioUrl && !isRecording && (
271
327
  <button
@@ -344,7 +400,7 @@ export const VoiceRecorder = forwardRef<VoiceRecorderHandle, VoiceRecorderProps>
344
400
  className={`border-2 ${th.buttonBorder} ${th.buttonShadow} hover:translate-x-[2px] hover:translate-y-[2px] hover:shadow-none cursor-pointer flex items-center space-x-2 px-4 py-2 ${th.text} rounded-xl transition-colors duration-200`}
345
401
  >
346
402
  <HiTrash className='w-4 h-4' />
347
- <span>Discard</span>
403
+ <span>{discardLabel}</span>
348
404
  </button>
349
405
  </div>
350
406
  </div>
@@ -68,6 +68,8 @@ function VoiceRecording({
68
68
  eagerUpload = true,
69
69
  animate = false,
70
70
  name,
71
+ silenceWarningSec,
72
+ silenceWarningText,
71
73
  }: BaseComponentProps & {
72
74
  content?: React.ReactNode;
73
75
  buttonText?: string;
@@ -85,6 +87,10 @@ function VoiceRecording({
85
87
  eagerUpload?: boolean;
86
88
  animate?: boolean;
87
89
  name?: string;
90
+ /** Seconds of continuous silence before a "speak up" banner appears. Disabled when undefined. */
91
+ silenceWarningSec?: number;
92
+ /** Text shown in the silence banner. */
93
+ silenceWarningText?: string;
88
94
  }) {
89
95
  const th = t(useTheme());
90
96
  const resolvedButtonText = buttonText ?? (minDuration != null ? 'Save & Continue' : 'Continue');
@@ -153,6 +159,8 @@ function VoiceRecording({
153
159
  showStop={minDuration == null}
154
160
  showDiscard={minDuration != null}
155
161
  showVisualizer={showVisualizer}
162
+ silenceWarningSec={silenceWarningSec}
163
+ silenceWarningText={silenceWarningText}
156
164
  onPause={handlePause}
157
165
  onResume={handleResume}
158
166
  />
package/src/mod.tsx CHANGED
@@ -6,6 +6,9 @@ export * from './utils/array';
6
6
  export * from './utils/common';
7
7
  export * from './utils/simulation';
8
8
  export { registerFlattener, arrayFlattener } from './utils/upload';
9
+ export { registerOverlay } from './utils/overlays';
10
+ export type { OverlayProps } from './utils/overlays';
11
+ export { prolificId, alphanumericId } from './utils/ids';
9
12
  export { normal, poisson, uniform, seedDistributions, sobol, halton, sampleParticipants, draw } from './utils/distributions';
10
13
  export { useTheme, ThemeContext, THEME, t, LIGHT_DOT_BG_CLASS, DARK_BG_CLASS, DARK_BG_PLAIN_CLASS } from './utils/theme';
11
14
  export { AudioDeviceContext, useAudioDeviceId } from './utils/audiodevice';
@@ -6,12 +6,16 @@ export function now(){
6
6
  }
7
7
 
8
8
  export function isFullscreen(): boolean {
9
- return !!(
9
+ const domFs = !!(
10
10
  document.fullscreenElement ||
11
11
  (document as any).webkitFullscreenElement ||
12
12
  (document as any).mozFullScreenElement ||
13
13
  (document as any).msFullscreenElement
14
14
  );
15
+ if (!domFs) return false;
16
+ // On macOS Chrome, `fullscreenElement` can stay set after ESC exit. When truly
17
+ // in fullscreen, no browser chrome is visible, so outerHeight === innerHeight.
18
+ return Math.abs(window.outerHeight - window.innerHeight) < 5;
15
19
  }
16
20
 
17
21
  export function isDesktop() {
@@ -0,0 +1,17 @@
1
+ import { uniform } from './distributions';
2
+
3
+ const ALPHANUMERIC = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
4
+
5
+ /** Generate a random alphanumeric string of the given length. Uses the seedable uniform PRNG so simulations are reproducible. */
6
+ export function alphanumericId(length: number): string {
7
+ let out = '';
8
+ for (let i = 0; i < length; i++) {
9
+ out += ALPHANUMERIC[Math.floor(uniform(0, 1) * ALPHANUMERIC.length)];
10
+ }
11
+ return out;
12
+ }
13
+
14
+ /** Generate a Prolific-style 24-character alphanumeric ID */
15
+ export function prolificId(): string {
16
+ return alphanumericId(24);
17
+ }
@@ -0,0 +1,19 @@
1
+ /* eslint-disable @typescript-eslint/no-explicit-any */
2
+ import { ComponentType } from 'react';
3
+ import { Store } from './common';
4
+
5
+ export interface OverlayProps {
6
+ store: Store;
7
+ updateStore: (mergeIn: Store) => void;
8
+ data: any[];
9
+ }
10
+
11
+ const registry: ComponentType<OverlayProps>[] = [];
12
+
13
+ export function registerOverlay(component: ComponentType<OverlayProps>) {
14
+ if (!registry.includes(component)) registry.push(component);
15
+ }
16
+
17
+ export function getOverlays() {
18
+ return [...registry];
19
+ }
@@ -97,15 +97,28 @@ export async function simulateParticipant(
97
97
  name: '',
98
98
  responseData: {
99
99
  userAgent: 'simulated',
100
- params: Object.fromEntries(
101
- (Param.getRegistry() || []).map((p: any) => [p.name, {
102
- value: p.value !== undefined ? p.value : p.defaultValue,
103
- registered: true,
104
- defaultValue: p.defaultValue,
105
- type: p.type,
106
- description: p.description,
107
- }]),
108
- ),
100
+ params: {
101
+ // Unregistered URL params from participant.urlParams appear in the CSV with a `url_` prefix.
102
+ ...Object.fromEntries(
103
+ Object.entries((participant as any)?.urlParams ?? {}).map(([name, value]) => [name, {
104
+ value,
105
+ registered: false,
106
+ defaultValue: undefined,
107
+ type: undefined,
108
+ description: undefined,
109
+ }]),
110
+ ),
111
+ // Registered params win on name collision.
112
+ ...Object.fromEntries(
113
+ (Param.getRegistry() || []).map((p: any) => [p.name, {
114
+ value: p.value !== undefined ? p.value : p.defaultValue,
115
+ registered: true,
116
+ defaultValue: p.defaultValue,
117
+ type: p.type,
118
+ description: p.description,
119
+ }]),
120
+ ),
121
+ },
109
122
  },
110
123
  },
111
124
  ];
@@ -74,14 +74,17 @@ export function convertArrayOfObjectsToCSV(data: DataObject[]): string {
74
74
  }
75
75
 
76
76
  // Extracts experiment parameter values (URL params / registered params) from the initial metadata trial.
77
- // Each param entry has { value, defaultValue, ... } — we pick value if set, otherwise the default.
77
+ // Each param entry has { value, defaultValue, registered, ... } — we pick value if set, otherwise the default.
78
+ // Unregistered params (raw URL params not declared via getParam) are prefixed with `url_` so they're
79
+ // visibly distinguishable from intentional study variables in the CSV.
78
80
  function extractParams(data: any[]): Record<string, any> {
79
81
  const paramsSource = data?.[0]?.responseData?.params;
80
82
  if (!paramsSource || typeof paramsSource !== 'object') return {};
81
83
  const result: Record<string, any> = {};
82
84
  for (const [name, details] of Object.entries(paramsSource) as [string, any][]) {
83
85
  if (details && typeof details === 'object') {
84
- result[name] = details.value ?? details.defaultValue;
86
+ const key = details.registered ? name : `url_${name}`;
87
+ result[key] = details.value ?? details.defaultValue;
85
88
  }
86
89
  }
87
90
  return result;