@adriansteffan/reactive 0.1.36 → 0.2.1

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.
Files changed (41) hide show
  1. package/.claude/settings.local.json +7 -1
  2. package/README.md +108 -5
  3. package/dist/{mod-urua6TFn.js → mod-CWKvMS7s.js} +11570 -11218
  4. package/dist/mod.d.ts +110 -6
  5. package/dist/reactive.es.js +74 -63
  6. package/dist/reactive.umd.js +626 -654
  7. package/dist/style.css +1 -1
  8. package/dist/{web-D9yqAhIx.js → web-DDyOXSFH.js} +1 -1
  9. package/dist/{web-BtWqed4E.js → web-DR-HR3ib.js} +1 -1
  10. package/package.json +4 -2
  11. package/raw-loader-hooks.mjs +25 -0
  12. package/raw-loader.mjs +5 -0
  13. package/src/components/experimentrunner.tsx +56 -2
  14. package/src/components/index.ts +1 -0
  15. package/src/components/microphonecheck.tsx +70 -84
  16. package/src/components/text.tsx +1 -1
  17. package/src/components/upload.tsx +4 -1
  18. package/src/components/voicerecorder.tsx +184 -162
  19. package/src/components/voicerecording.tsx +198 -0
  20. package/src/index.css +6 -0
  21. package/src/mod.tsx +8 -3
  22. package/src/utils/array.ts +61 -11
  23. package/src/utils/audiodevice.ts +4 -0
  24. package/src/utils/common.ts +3 -3
  25. package/src/utils/distributions.ts +28 -5
  26. package/src/utils/llm.ts +101 -0
  27. package/src/utils/nodecompat.ts +11 -0
  28. package/src/utils/simulation.ts +2 -2
  29. package/src/utils/theme.ts +1 -0
  30. package/src/utils/tts.ts +82 -0
  31. package/src/utils/upload.ts +54 -1
  32. package/template/README.md +26 -0
  33. package/template/backend/src/backend.ts +32 -1
  34. package/template/docker-compose.yaml +32 -0
  35. package/template/package.json +5 -2
  36. package/template/simulate.ts +13 -3
  37. package/template/src/Experiment.tsx +10 -12
  38. package/template/transcription/Dockerfile.cpu +8 -0
  39. package/template/transcription/Dockerfile.gpu +8 -0
  40. package/template/transcription/transcribe.py +161 -0
  41. package/vite.config.ts +1 -1
@@ -1,9 +1,7 @@
1
- import React, { useState, useRef, useEffect } from 'react';
2
- import { HiMicrophone, HiStop, HiTrash } from 'react-icons/hi2';
3
-
4
- interface AudioVisualizerProps {
5
- stream: MediaStream;
6
- }
1
+ import React, { useState, useRef, useEffect, forwardRef, useImperativeHandle } from 'react';
2
+ import { HiMicrophone, HiStop, HiTrash, HiPause } from 'react-icons/hi2';
3
+ import { useTheme, t } from '../utils/theme';
4
+ import { useAudioDeviceId } from '../utils/audiodevice';
7
5
 
8
6
  interface RecordingData {
9
7
  blob: Blob;
@@ -11,12 +9,9 @@ interface RecordingData {
11
9
  timestamp: string;
12
10
  }
13
11
 
14
- // I quickly AI-genned this viz so that the participants have some feedback if their audio is being picked up - probably highly inaccurate, but that should not matter at all
15
- const AudioVisualizer: React.FC<AudioVisualizerProps> = ({ stream }) => {
12
+ const AudioVisualizer: React.FC<{ stream: MediaStream; isDark: boolean }> = ({ stream, isDark }) => {
16
13
  const canvasRef = useRef<HTMLCanvasElement | null>(null);
17
14
  const animationRef = useRef<number | null>(null);
18
- const analyserRef = useRef<AnalyserNode | null>(null);
19
- const previousDataRef = useRef<number[]>([]);
20
15
 
21
16
  useEffect(() => {
22
17
  if (!stream || !canvasRef.current) return;
@@ -26,178 +21,146 @@ const AudioVisualizer: React.FC<AudioVisualizerProps> = ({ stream }) => {
26
21
  const analyser = audioContext.createAnalyser();
27
22
  const source = audioContext.createMediaStreamSource(stream);
28
23
 
29
- // Increased FFT size for smoother data
30
24
  analyser.fftSize = 2048;
31
25
  source.connect(analyser);
32
- analyserRef.current = analyser;
33
26
 
34
27
  const canvas = canvasRef.current;
35
28
  const ctx = canvas.getContext('2d', { alpha: false });
36
29
  if (!ctx) return;
37
30
 
38
- ctx.imageSmoothingEnabled = true;
39
- ctx.imageSmoothingQuality = 'high';
40
-
41
31
  const dpr = window.devicePixelRatio || 1;
42
32
  const rect = canvas.getBoundingClientRect();
43
-
44
33
  canvas.width = rect.width * dpr;
45
34
  canvas.height = rect.height * dpr;
46
35
  ctx.scale(dpr, dpr);
47
-
48
36
  canvas.style.width = `${rect.width}px`;
49
37
  canvas.style.height = `${rect.height}px`;
50
38
 
51
- const dataArray = new Uint8Array(analyser.frequencyBinCount);
52
- previousDataRef.current = Array(analyser.frequencyBinCount).fill(128);
53
-
54
- // Enhanced smoothing function with weighted average
55
- const smoothValue = (current: number, previous: number) => {
56
- const weight = 0.08; // Lower = smoother, higher = more responsive
57
- return previous + (current - previous) * weight;
58
- };
59
-
60
- // Function to compute running average for additional smoothing
61
- const averageValues = (data: number[], windowSize: number = 3) => {
62
- const result = new Array(data.length).fill(0);
63
-
64
- for (let i = 0; i < data.length; i++) {
65
- let sum = 0;
66
- let count = 0;
67
-
68
- for (
69
- let j = Math.max(0, i - windowSize);
70
- j < Math.min(data.length, i + windowSize + 1);
71
- j++
72
- ) {
73
- sum += data[j];
74
- count++;
75
- }
76
-
77
- result[i] = sum / count;
78
- }
79
-
80
- return result;
81
- };
39
+ const timeData = new Uint8Array(analyser.fftSize);
40
+ const bgColor = isDark ? '#374151' : '#ffffff';
41
+ const activeColor = isDark ? '#ffffff' : '#000000';
42
+ const dimColor = isDark ? '#4B5563' : '#E5E7EB';
43
+ const width = rect.width;
44
+ const height = rect.height;
45
+ const segmentCount = 24;
46
+ const segmentWidth = width / segmentCount;
47
+ const gap = 2;
48
+ let smoothedLevel = 0;
82
49
 
83
50
  const draw = () => {
84
- const width = rect.width;
85
- const height = rect.height;
86
- const centerY = height / 2;
87
-
88
51
  animationRef.current = requestAnimationFrame(draw);
89
- analyser.getByteTimeDomainData(dataArray);
90
-
91
- // Apply initial smoothing
92
- const smoothedData = Array.from(dataArray).map((value, i) =>
93
- smoothValue(value, previousDataRef.current[i]),
94
- );
95
-
96
- // Apply running average smoothing
97
- const averagedData = averageValues(smoothedData);
98
-
99
- // Update previous data
100
- previousDataRef.current = averagedData;
101
-
102
- ctx.fillStyle = '#ffffff';
103
- ctx.fillRect(0, 0, width * dpr, height * dpr);
104
-
105
- // Draw the center line
106
- ctx.beginPath();
107
- ctx.strokeStyle = 'rgba(0, 0, 0, 0.1)';
108
- ctx.lineWidth = 1;
109
- ctx.moveTo(0, centerY);
110
- ctx.lineTo(width, centerY);
111
- ctx.stroke();
112
-
113
- // Draw waveform
114
- ctx.beginPath();
115
- ctx.lineWidth = 2;
116
- ctx.strokeStyle = 'rgba(0, 0, 0, 0.85)';
117
-
118
- const skipPoints = 4;
119
- const points: [number, number][] = [];
120
-
121
- for (let i = 0; i < averagedData.length; i += skipPoints) {
122
- const x = (i / averagedData.length) * width;
123
- const normalizedValue = (averagedData[i] - 128) / 128;
124
- const y = centerY + normalizedValue * height * 4.0;
125
- points.push([x, y]);
126
- }
52
+ analyser.getByteTimeDomainData(timeData);
127
53
 
128
- // Draw smooth curve through points
129
- if (points.length > 0) {
130
- ctx.moveTo(points[0][0], points[0][1]);
54
+ // Compute RMS volume from time-domain samples (centered at 128)
55
+ let sumOfSquares = 0;
56
+ for (let i = 0; i < timeData.length; i++) {
57
+ const normalized = (timeData[i] - 128) / 128;
58
+ sumOfSquares += normalized * normalized;
59
+ }
60
+ const volumeLevel = Math.min(1, Math.sqrt(sumOfSquares / timeData.length) * 5);
61
+ smoothedLevel += (volumeLevel - smoothedLevel) * 0.3;
131
62
 
132
- for (let i = 1; i < points.length - 2; i++) {
133
- const xc = (points[i][0] + points[i + 1][0]) / 2;
134
- const yc = (points[i][1] + points[i + 1][1]) / 2;
135
- ctx.quadraticCurveTo(points[i][0], points[i][1], xc, yc);
136
- }
63
+ ctx.fillStyle = bgColor;
64
+ ctx.fillRect(0, 0, width, height);
137
65
 
138
- // For the last two points
139
- if (points.length > 2) {
140
- const last = points.length - 1;
141
- ctx.quadraticCurveTo(
142
- points[last - 1][0],
143
- points[last - 1][1],
144
- points[last][0],
145
- points[last][1],
146
- );
147
- }
66
+ const activeSegments = Math.round(smoothedLevel * segmentCount);
67
+ for (let i = 0; i < segmentCount; i++) {
68
+ ctx.fillStyle = i < activeSegments ? activeColor : dimColor;
69
+ ctx.fillRect(i * segmentWidth + gap / 2, gap, segmentWidth - gap, height - gap * 2);
148
70
  }
149
-
150
- ctx.stroke();
151
71
  };
152
72
 
153
73
  draw();
154
74
 
155
75
  return () => {
156
- if (animationRef.current) {
157
- cancelAnimationFrame(animationRef.current);
158
- }
76
+ if (animationRef.current) cancelAnimationFrame(animationRef.current);
159
77
  source.disconnect();
160
78
  audioContext.close();
161
79
  };
162
- }, [stream]);
80
+ }, [stream, isDark]);
163
81
 
164
82
  return (
165
83
  <canvas
166
84
  ref={canvasRef}
167
85
  width={300}
168
86
  height={60}
169
- className='mx-auto rounded-lg bg-white shadow-xs'
87
+ className={`mx-auto border-2 border-black ${isDark ? 'bg-gray-700' : 'bg-white'}`}
170
88
  />
171
89
  );
172
90
  };
173
91
 
174
- export const VoiceRecorder = ({
175
- question,
176
- handleSaveVoiceData,
177
- handleDiscardVoiceData,
178
- }: {
179
- question: {
180
- value: RecordingData | null;
181
- };
92
+ export interface VoiceRecorderHandle {
93
+ stop: () => void;
94
+ }
95
+
96
+ export interface VoiceRecorderProps {
97
+ question?: { value: RecordingData | null };
182
98
  handleSaveVoiceData: (data: object) => void;
183
99
  handleDiscardVoiceData: () => void;
184
- }) => {
100
+ deviceId?: string;
101
+ showPause?: boolean;
102
+ showStop?: boolean;
103
+ showVisualizer?: boolean;
104
+ /** Show a discard button while recording to delete and start over. */
105
+ showDiscard?: boolean;
106
+ onRecordingStart?: () => void;
107
+ onPause?: (duration: number) => void;
108
+ onResume?: () => void;
109
+ }
110
+
111
+ export const VoiceRecorder = forwardRef<VoiceRecorderHandle, VoiceRecorderProps>(({
112
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
113
+ question: _question,
114
+ handleSaveVoiceData,
115
+ handleDiscardVoiceData,
116
+ deviceId,
117
+ showPause = true,
118
+ showStop = true,
119
+ showVisualizer = true,
120
+ showDiscard = true,
121
+ onRecordingStart,
122
+ onPause,
123
+ onResume,
124
+ }, ref) => {
125
+ const theme = useTheme();
126
+ const th = t(theme);
127
+ const isDark = theme.startsWith('dark');
128
+ const contextDeviceId = useAudioDeviceId();
129
+
185
130
  const [isRecording, setIsRecording] = useState<boolean>(false);
131
+ const [isPaused, setIsPaused] = useState<boolean>(false);
186
132
  const [audioUrl, setAudioUrl] = useState<string | null>(null);
187
133
  const [audioStream, setAudioStream] = useState<MediaStream | null>(null);
188
134
  const mediaRecorderRef = useRef<MediaRecorder | null>(null);
189
135
  const chunksRef = useRef<BlobPart[]>([]);
190
136
 
137
+ // Duration tracking (ms, excludes paused time)
138
+ const durationRef = useRef(0);
139
+ const timerRef = useRef<ReturnType<typeof setInterval> | null>(null);
140
+
141
+ const clearTimer = () => { if (timerRef.current) { clearInterval(timerRef.current); timerRef.current = null; } };
142
+ const startTimer = () => { durationRef.current = 0; timerRef.current = setInterval(() => { durationRef.current += 100; }, 100); };
143
+ const resumeTimer = () => { timerRef.current = setInterval(() => { durationRef.current += 100; }, 100); };
144
+
145
+ const stopRecording = () => {
146
+ const recorder = mediaRecorderRef.current;
147
+ if (recorder && (recorder.state === 'recording' || recorder.state === 'paused')) {
148
+ recorder.stop();
149
+ recorder.stream.getTracks().forEach((track) => track.stop());
150
+ setIsRecording(false);
151
+ setIsPaused(false);
152
+ clearTimer();
153
+ }
154
+ };
155
+
156
+ useImperativeHandle(ref, () => ({ stop: stopRecording }));
157
+
191
158
  const startRecording = async () => {
192
159
  try {
193
- /*This is really hacky but it works and there is a deadline, we should find a way to pass around such values in the future */
194
- /*eslint-disable-next-line @typescript-eslint/no-explicit-any*/
195
- const deviceId = (window as any).audioInputId;
160
+ const resolvedDeviceId = deviceId ?? contextDeviceId;
196
161
  const constraints: MediaStreamConstraints = {
197
- audio: deviceId
198
- ? {
199
- deviceId: { exact: deviceId },
200
- }
162
+ audio: resolvedDeviceId
163
+ ? { deviceId: { exact: resolvedDeviceId } }
201
164
  : true,
202
165
  };
203
166
 
@@ -225,16 +188,29 @@ export const VoiceRecorder = ({
225
188
  mediaRecorderRef.current.start();
226
189
 
227
190
  setIsRecording(true);
191
+ setIsPaused(false);
192
+ startTimer();
193
+ onRecordingStart?.();
228
194
  } catch (err) {
229
195
  console.error('Error accessing microphone:', err);
230
196
  }
231
197
  };
232
198
 
233
- const stopRecording = () => {
234
- if (mediaRecorderRef.current && isRecording) {
235
- mediaRecorderRef.current.stop();
236
- mediaRecorderRef.current.stream.getTracks().forEach((track) => track.stop());
237
- setIsRecording(false);
199
+ const pauseRecording = () => {
200
+ if (mediaRecorderRef.current && mediaRecorderRef.current.state === 'recording') {
201
+ mediaRecorderRef.current.pause();
202
+ setIsPaused(true);
203
+ clearTimer();
204
+ onPause?.(durationRef.current);
205
+ }
206
+ };
207
+
208
+ const resumeRecording = () => {
209
+ if (mediaRecorderRef.current && mediaRecorderRef.current.state === 'paused') {
210
+ mediaRecorderRef.current.resume();
211
+ setIsPaused(false);
212
+ resumeTimer();
213
+ onResume?.();
238
214
  }
239
215
  };
240
216
 
@@ -243,7 +219,6 @@ export const VoiceRecorder = ({
243
219
  const base64Data = await new Promise<string>((resolve) => {
244
220
  const reader = new FileReader();
245
221
  reader.onloadend = () => {
246
- // Remove data URL prefix (e.g., "data:audio/webm;base64,")
247
222
  const base64 = reader.result?.toString().split(',')[1] || '';
248
223
  resolve(base64);
249
224
  };
@@ -252,59 +227,109 @@ export const VoiceRecorder = ({
252
227
 
253
228
  handleSaveVoiceData({
254
229
  blob: blob,
255
- // dont change this type, since the upload function depends on it while looking for audio. we might want to refactor this at some point
230
+ // dont change this type, since the upload function depends on it while looking for audio
256
231
  type: 'audiorecording',
257
232
  url: url,
258
233
  data64: base64Data,
259
234
  timestamp: new Date().toISOString(),
235
+ recordingDuration: durationRef.current,
260
236
  });
261
237
  }
262
238
  };
263
239
 
240
+ const discardWhileRecording = () => {
241
+ const recorder = mediaRecorderRef.current;
242
+ if (recorder && (recorder.state === 'recording' || recorder.state === 'paused')) {
243
+ // Prevent onstop from saving, clear chunks first
244
+ chunksRef.current = [];
245
+ recorder.onstop = null;
246
+ recorder.stop();
247
+ recorder.stream.getTracks().forEach((track) => track.stop());
248
+ }
249
+ setIsRecording(false);
250
+ setIsPaused(false);
251
+ setAudioStream(null);
252
+ clearTimer();
253
+ handleDiscardVoiceData();
254
+ };
255
+
264
256
  const discardRecording = () => {
265
257
  if (audioUrl) {
266
258
  URL.revokeObjectURL(audioUrl);
267
259
  }
268
260
  setAudioUrl(null);
269
- question.value = null;
261
+ setIsPaused(false);
270
262
  handleDiscardVoiceData();
271
263
  };
272
264
 
265
+ const btnBase = `flex items-center justify-center p-4 rounded-full border-2 ${th.buttonBorder} ${th.buttonShadow} hover:translate-x-[2px] hover:translate-y-[2px] hover:shadow-none cursor-pointer transition-colors duration-200`;
266
+
273
267
  return (
274
- <div className='flex flex-col items-center space-y-4 p-4 bg-white px-8 '>
275
- {/* Recording button */}
276
- {!audioUrl && (
268
+ <div className='flex flex-col items-center space-y-4 p-4 px-8'>
269
+ {/* Start button */}
270
+ {!audioUrl && !isRecording && (
277
271
  <button
278
- onClick={isRecording ? stopRecording : startRecording}
279
- className={`flex items-center justify-center space-x-2 p-4 rounded-full border-2 border-black shadow-[2px_2px_0px_rgba(0,0,0,1)] hover:translate-x-[2px] hover:translate-y-[2px] hover:shadow-none cursor-pointer
280
- ${isRecording ? 'bg-red-500 hover:bg-red-600' : ''}
281
- text-white transition-colors duration-200`}
282
- aria-label={isRecording ? 'Stop Recording' : 'Start Recording'}
272
+ onClick={startRecording}
273
+ className={`${btnBase} ${th.buttonBg}`}
274
+ aria-label='Start Recording'
283
275
  >
284
- {isRecording ? (
285
- <HiStop className='w-6 h-6' />
286
- ) : (
287
- <HiMicrophone className='w-6 h-6 text-black' />
288
- )}
276
+ <HiMicrophone className={`w-6 h-6 ${th.buttonText}`} />
289
277
  </button>
290
278
  )}
291
279
 
280
+ {/* Recording controls */}
281
+ {!audioUrl && isRecording && (
282
+ <div className='flex items-center space-x-4'>
283
+ {showPause && (
284
+ <button
285
+ onClick={isPaused ? resumeRecording : pauseRecording}
286
+ className={`${btnBase} ${th.buttonBg}`}
287
+ aria-label={isPaused ? 'Resume Recording' : 'Pause Recording'}
288
+ >
289
+ {isPaused ? (
290
+ <HiMicrophone className={`w-6 h-6 ${th.buttonText}`} />
291
+ ) : (
292
+ <HiPause className={`w-6 h-6 ${th.buttonText}`} />
293
+ )}
294
+ </button>
295
+ )}
296
+ {showStop && (
297
+ <button
298
+ onClick={stopRecording}
299
+ className={`${btnBase} bg-red-500 text-white`}
300
+ aria-label='Stop Recording'
301
+ >
302
+ <HiStop className='w-6 h-6' />
303
+ </button>
304
+ )}
305
+ {showDiscard && isPaused && (
306
+ <button
307
+ onClick={discardWhileRecording}
308
+ className={`${btnBase} ${th.buttonBg}`}
309
+ aria-label='Discard Recording'
310
+ >
311
+ <HiTrash className={`w-6 h-6 ${th.buttonText}`} />
312
+ </button>
313
+ )}
314
+ </div>
315
+ )}
316
+
292
317
  {/* Audio visualizer */}
293
- {isRecording && audioStream && (
318
+ {showVisualizer && isRecording && !isPaused && audioStream && (
294
319
  <div className='w-full max-w-md mx-auto'>
295
- <AudioVisualizer stream={audioStream} />
320
+ <AudioVisualizer stream={audioStream} isDark={isDark} />
296
321
  </div>
297
322
  )}
298
323
 
299
324
  {/* Recording status */}
300
325
  {isRecording && (
301
326
  <div className='flex items-center space-x-2'>
302
- <div className='w-3 h-3 bg-red-500 rounded-full animate-pulse'></div>
303
- <span className='text-sm text-black'>Recording...</span>
327
+ <div className={`w-3 h-3 rounded-full ${isPaused ? 'bg-yellow-500' : 'bg-red-500 animate-pulse'}`}></div>
328
+ <span className={`text-sm ${th.text}`}>{isPaused ? 'Paused' : 'Recording...'}</span>
304
329
  </div>
305
330
  )}
306
331
 
307
- {/* Audio player and action buttons */}
332
+ {/* Audio player and discard */}
308
333
  {audioUrl && !isRecording && (
309
334
  <div className='flex flex-col items-center space-y-4 w-full max-w-md'>
310
335
  <audio controls preload='none' className='w-full' playsInline>
@@ -316,8 +341,7 @@ export const VoiceRecorder = ({
316
341
  <div className='flex space-x-4'>
317
342
  <button
318
343
  onClick={discardRecording}
319
- className='border-2 border-black shadow-[2px_2px_0px_rgba(0,0,0,1)] hover:translate-x-[2px] hover:translate-y-[2px] hover:shadow-none cursor-pointer flex items-center space-x-2 px-4 py-2 text-black
320
- rounded-xl transition-colors duration-200'
344
+ 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`}
321
345
  >
322
346
  <HiTrash className='w-4 h-4' />
323
347
  <span>Discard</span>
@@ -327,8 +351,7 @@ export const VoiceRecorder = ({
327
351
  )}
328
352
  </div>
329
353
  );
330
- };
331
-
354
+ });
332
355
 
333
356
 
334
357
  export default function VoicerecorderQuestionComponent({
@@ -338,7 +361,6 @@ export default function VoicerecorderQuestionComponent({
338
361
  }) {
339
362
  return (
340
363
  <VoiceRecorder
341
- question={{ value: null }}
342
364
  handleSaveVoiceData={(data) => setValue(data)}
343
365
  handleDiscardVoiceData={() => setValue(null)}
344
366
  />