@adriansteffan/reactive 0.2.7 → 0.5.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/README.md +796 -229
- package/bin/add.js +56 -0
- package/bin/deploy.js +48 -0
- package/bin/download.js +28 -0
- package/bin/ghsetup.js +21 -0
- package/bin/native.js +81 -0
- package/bin/setup.js +11 -17
- package/bin/study-deploy.js +60 -0
- package/bin/undeploy.js +15 -0
- package/extras/transcription/compose.yaml +32 -0
- package/{template → extras}/transcription/transcribe.py +4 -9
- package/package.json +62 -64
- package/src/bun-env.d.ts +1 -0
- package/src/bun-plugin.ts +22 -0
- package/src/components/canvasblock.tsx +209 -537
- package/src/components/checkdevice.tsx +64 -84
- package/src/components/fullscreenblock.tsx +130 -0
- package/src/components/icons.tsx +50 -0
- package/src/components/index.ts +9 -11
- package/src/components/microphonecheck.tsx +76 -38
- package/src/components/plaininput.tsx +45 -40
- package/src/components/prolificending.tsx +64 -28
- package/src/components/quest.tsx +89 -87
- package/src/components/{randomdotkinetogram.tsx → randomdotkinematogram.tsx} +205 -267
- package/src/components/{voicerecorder.tsx → recorder.tsx} +81 -106
- package/src/components/requestfilepermission.tsx +63 -0
- package/src/components/stimulus.tsx +373 -0
- package/src/components/storeui.tsx +94 -148
- package/src/components/text.tsx +61 -59
- package/src/components/tutorial.tsx +45 -47
- package/src/components/upload.tsx +133 -309
- package/src/components/voicerecording.tsx +90 -94
- package/src/core/backend.ts +20 -0
- package/src/core/bytecode.ts +178 -0
- package/src/core/columns.ts +50 -0
- package/src/core/component.ts +238 -0
- package/src/core/development.ts +32 -0
- package/src/core/experiment.ts +263 -0
- package/src/core/files.ts +291 -0
- package/src/core/params.ts +166 -0
- package/src/core/platform.ts +29 -0
- package/src/core/rows.ts +106 -0
- package/src/core/simulation.ts +158 -0
- package/src/core/slides.ts +178 -0
- package/src/core/store.ts +22 -0
- package/src/core/timeline.ts +399 -0
- package/src/fonts/AtkinsonHyperlegible-Bold.woff2 +0 -0
- package/src/fonts/AtkinsonHyperlegible-BoldItalic.woff2 +0 -0
- package/src/fonts/AtkinsonHyperlegible-Italic.woff2 +0 -0
- package/src/fonts/AtkinsonHyperlegible-Regular.woff2 +0 -0
- package/src/index.css +5 -7
- package/src/mod.tsx +31 -17
- package/src/native.ts +127 -0
- package/src/quest.ts +2 -0
- package/src/runner/contexts.ts +35 -0
- package/src/runner/devpanel.tsx +68 -0
- package/src/runner/experimentrunner.tsx +210 -0
- package/src/runner/fullscreenguard.tsx +93 -0
- package/src/runner/paraminput.tsx +86 -0
- package/src/runner/progressbar.tsx +20 -0
- package/src/runner/settingsscreen.tsx +517 -0
- package/src/{utils → runner}/theme.ts +9 -8
- package/src/server.ts +93 -0
- package/src/tutorial.ts +3 -0
- package/src/utils/array.ts +30 -62
- package/src/utils/canvas.ts +66 -0
- package/src/utils/ddm.ts +47 -70
- package/src/utils/distributions.ts +352 -61
- package/src/utils/fullscreen.ts +38 -0
- package/src/utils/ids.ts +11 -0
- package/src/utils/keys.ts +46 -0
- package/src/utils/llm.ts +15 -15
- package/src/utils/time.ts +12 -0
- package/src/utils/tts.ts +24 -24
- package/template/.dockerignore +3 -1
- package/template/.env.example +5 -0
- package/template/.github/workflows/deploy.yml +25 -0
- package/template/.gitignore +14 -0
- package/template/Dockerfile +9 -14
- package/template/README.md +74 -214
- package/template/biome.json +34 -0
- package/template/build.ts +20 -0
- package/template/bunfig.toml +3 -0
- package/template/docker-compose.yaml +4 -33
- package/template/index.html +2 -2
- package/template/package.json +16 -89
- package/template/public/.gitkeep +0 -0
- package/template/server.ts +32 -0
- package/template/simulate.ts +4 -44
- package/template/src/Experiment.tsx +76 -128
- package/template/src/bun-env.d.ts +1 -0
- package/template/src/index.css +1 -9
- package/template/src/main.tsx +25 -10
- package/template/tsconfig.json +4 -6
- package/.claude/settings.local.json +0 -61
- package/.eslintrc.cjs +0 -18
- package/.playwright-mcp/console-2026-04-07T14-22-59-060Z.log +0 -1
- package/.playwright-mcp/console-2026-09-20T12-17-32-043Z.log +0 -1
- package/.playwright-mcp/page-2026-09-20T12-17-32-084Z.yml +0 -10
- package/.prettierrc +0 -5
- package/Dockerfile +0 -20
- package/dist/mod-BTpABl23.js +0 -87435
- package/dist/mod.d.ts +0 -947
- package/dist/reactive.es.js +0 -87
- package/dist/reactive.umd.js +0 -10255
- package/dist/style.css +0 -5
- package/dist/web-DV4cj_8Q.js +0 -435
- package/dist/web-DprbPn6i.js +0 -12
- package/planned.md +0 -103
- package/postcss.config.js +0 -6
- package/raw-loader-hooks.mjs +0 -25
- package/raw-loader.mjs +0 -5
- package/rdk_doc.md +0 -341
- package/src/components/enterfullscreen.tsx +0 -230
- package/src/components/exitfullscreen.tsx +0 -113
- package/src/components/experimentprovider.tsx +0 -69
- package/src/components/experimentrunner.tsx +0 -497
- package/src/components/mobilefilepermission.tsx +0 -68
- package/src/components/settingsscreen.tsx +0 -770
- package/src/types/array.d.ts +0 -6
- package/src/utils/audiodevice.ts +0 -4
- package/src/utils/bytecode.ts +0 -261
- package/src/utils/common.ts +0 -291
- package/src/utils/ddm.test.ts +0 -233
- package/src/utils/distributions.test.ts +0 -209
- package/src/utils/nodecompat.ts +0 -11
- package/src/utils/overlays.ts +0 -19
- package/src/utils/request.ts +0 -25
- package/src/utils/simulation.ts +0 -299
- package/src/utils/upload.ts +0 -275
- package/src/vite-env.d.ts +0 -1
- package/template/.env.template +0 -2
- package/template/.eslintrc.cjs +0 -18
- package/template/.prettierrc +0 -5
- package/template/backend/package-lock.json +0 -2544
- package/template/backend/package.json +0 -31
- package/template/backend/src/backend.ts +0 -131
- package/template/backend/tsconfig.json +0 -110
- package/template/capacitor.config.ts +0 -15
- package/template/electron/main.js +0 -131
- package/template/electron/preload.js +0 -9
- package/template/electron.vite.config.js +0 -45
- package/template/package-lock.json +0 -12467
- package/template/postcss.config.js +0 -5
- package/template/public/Atkinson_Hyperlegible/AtkinsonHyperlegible-Bold.ttf +0 -0
- package/template/public/Atkinson_Hyperlegible/AtkinsonHyperlegible-BoldItalic.ttf +0 -0
- package/template/public/Atkinson_Hyperlegible/AtkinsonHyperlegible-Italic.ttf +0 -0
- package/template/public/Atkinson_Hyperlegible/AtkinsonHyperlegible-Regular.ttf +0 -0
- package/template/shared.vite.config.js +0 -39
- package/template/src/vite-env.d.ts +0 -2
- package/template/tsconfig.node.json +0 -12
- package/template/vite.config.js +0 -11
- package/tsconfig.json +0 -30
- package/tsconfig.node.json +0 -12
- package/vite.config.ts +0 -39
- /package/{template → extras}/transcription/Dockerfile.cpu +0 -0
- /package/{template → extras}/transcription/Dockerfile.gpu +0 -0
- /package/{template/public/Atkinson_Hyperlegible → src/fonts}/OFL.txt +0 -0
|
@@ -1,58 +1,16 @@
|
|
|
1
1
|
import React, { useState, useRef } from 'react';
|
|
2
|
-
import { BaseComponentProps } from '../
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import { useTheme, t } from '../
|
|
7
|
-
import {
|
|
2
|
+
import { BaseComponentProps } from '../core/component';
|
|
3
|
+
import { Recorder, RecorderHandle } from './recorder';
|
|
4
|
+
import { defineComponent } from '../core/component';
|
|
5
|
+
import { audioFilename, markRecordingUploaded } from '../core/files';
|
|
6
|
+
import { useTheme, t } from '../runner/theme';
|
|
7
|
+
import { ExclamationTriangleIcon } from './icons';
|
|
8
8
|
import { textToWebmBase64, probeAudioDurationMs } from '../utils/tts';
|
|
9
|
-
import { post } from '../
|
|
9
|
+
import { post } from '../core/backend';
|
|
10
10
|
|
|
11
11
|
// 0.5s 440Hz sine tone, Opus codec; fallback when system TTS/ffmpeg unavailable
|
|
12
12
|
const DUMMY_AUDIO_BASE64 = 'GkXfo59ChoEBQveBAULygQRC84EIQoKEd2VibUKHgQRChYECGFOAZwEAAAAAAARQEU2bdLpNu4tTq4QVSalmU6yBoU27i1OrhBZUrmtTrIHYTbuMU6uEElTDZ1OsggE/TbuMU6uEHFO7a1OsggQ67AEAAAAAAABZAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVSalmsirXsYMPQkBNgI1MYXZmNTguNzYuMTAwV0GNTGF2ZjU4Ljc2LjEwMESJiEB/wAAAAAAAFlSua+KuAQAAAAAAAFnXgQFzxYhRMt5OPJYVP5yBACK1nIN1bmSGhkFfT1BVU1aqg2MuoFa7hATEtACDgQLhkZ+BAbWIQOdwAAAAAABiZIEQY6KTT3B1c0hlYWQBATgBgLsAAAAAABJUw2dAm3NzAQAAAAAAACdjwIBnyAEAAAAAAAAaRaOHRU5DT0RFUkSHjUxhdmY1OC43Ni4xMDBzcwEAAAAAAABgY8CLY8WIUTLeTjyWFT9nyAEAAAAAAAAjRaOHRU5DT0RFUkSHlkxhdmM1OC4xMzQuMTAwIGxpYm9wdXNnyKJFo4hEVVJBVElPTkSHlDAwOjAwOjAwLjUwODAwMDAwMAAAH0O2dUJU54EAo5GBAACACINtgtAc/epJ/gE/wKOZgQAVgAinGl2KmC5fWspQj0PpJrkNsG40QKOVgQApgAihLxDkXfvcBBqwyPJFmpFgo5OBAD2ACKE40Hcyqlc9/1ttqV84o5SBAFGACKE40Hcyql5YIeRahOZfwKOXgQBlgAihTMA96uabsR453W080Xeb9h6jkYEAeYAIoTjQdzKqXDNU2kjGo5aBAI2ACKDZbPIJxX8xM7SEPNZetOMco5OBAKGACKE40Hcyqla9XawRHUWoo5OBALWACKE40Hcyqmb1XKO++uAQo5SBAMmACKEvEORd+8XekK1/rf/rrKOVgQDdgAihONB3MqpWRgIfsDV4YBUIo5OBAPGACKE40Hcyql5SyE1S2QFAo5SBAQWACKE40Hcyqla+8h2o+iaxgKOVgQEZgAihONB3MqpeqdUAtSaZmdKAo5OBAS2ACKFIA0bVUn3Jmsi7ollwo5OBAUGACKE40Hcyql6pt6b1uh3oo5WBAVWACKEvEORd+9/La7aeTKZnv/CjlYEBaYAIoTjO/AZGOE9OIX9kO96+gKOTgQF9gAihONB3MqpekAQ00UpCUKOTgQGRgAihSANG1VJz2oSiMZRZKqOQgQGlgAihONB3MqpeqbeK3KORgQG5gAihLxDkXfvfy2sJCQyjmoEBzYAIosXU/J/RyZHEovOUhd6Ypj7UPC8Bo5uBAeGACKRIuuxKsgM4Wle7xUaBZDTNWofASYGgAQAAAAAAABuhkoEB9QAIBkQ+QjevBKpbiF1qJHWihADN/mAcU7trkbuPs4EAt4r3gQHxggHg8IED';
|
|
13
13
|
|
|
14
|
-
export { DUMMY_AUDIO_BASE64 };
|
|
15
|
-
|
|
16
|
-
registerFlattener('VoiceRecording', 'session');
|
|
17
|
-
registerSimulation('VoiceRecording', async (_trialProps, _experimentState, simulators, participant) => {
|
|
18
|
-
const respond = simulators.respondTTS ?? simulators.respondBase64;
|
|
19
|
-
const result = await respond(_trialProps, participant);
|
|
20
|
-
const { participantState } = result;
|
|
21
|
-
|
|
22
|
-
let data64: string;
|
|
23
|
-
if (simulators.respondTTS) {
|
|
24
|
-
const text = result.value as string;
|
|
25
|
-
const ttsResult = await textToWebmBase64(text);
|
|
26
|
-
if (!ttsResult) throw new Error('TTS failed. Ensure say/espeak and ffmpeg are installed.');
|
|
27
|
-
data64 = ttsResult;
|
|
28
|
-
} else {
|
|
29
|
-
data64 = result.value as string;
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
// Exact duration via ffprobe, fall back to estimate from file size
|
|
33
|
-
const recordingDuration = (await probeAudioDurationMs(data64)) ?? Math.round(data64.length / 4);
|
|
34
|
-
return {
|
|
35
|
-
responseData: {
|
|
36
|
-
type: 'audiorecording',
|
|
37
|
-
data64,
|
|
38
|
-
timestamp: new Date().toISOString(),
|
|
39
|
-
recordingDuration,
|
|
40
|
-
},
|
|
41
|
-
participantState,
|
|
42
|
-
duration: recordingDuration,
|
|
43
|
-
};
|
|
44
|
-
}, {
|
|
45
|
-
/** Returns text to be spoken via platform TTS. Default: generic test sentence. */
|
|
46
|
-
respondTTS: (_input: any, participant: any) => ({
|
|
47
|
-
value: 'This is a simulated voice recording for testing purposes.',
|
|
48
|
-
participantState: participant,
|
|
49
|
-
}),
|
|
50
|
-
/** Returns raw base64-encoded WebM audio directly. Default: dummy 0.5s sine tone. */
|
|
51
|
-
respondBase64: (_input: any, participant: any) => ({
|
|
52
|
-
value: DUMMY_AUDIO_BASE64,
|
|
53
|
-
participantState: participant,
|
|
54
|
-
}),
|
|
55
|
-
});
|
|
56
14
|
|
|
57
15
|
function VoiceRecording({
|
|
58
16
|
content,
|
|
@@ -61,68 +19,68 @@ function VoiceRecording({
|
|
|
61
19
|
className = '',
|
|
62
20
|
containerClass,
|
|
63
21
|
next,
|
|
22
|
+
data,
|
|
64
23
|
store,
|
|
65
|
-
|
|
66
|
-
|
|
24
|
+
minDurationMs,
|
|
25
|
+
shortRecordingContent,
|
|
67
26
|
showVisualizer = true,
|
|
68
27
|
eagerUpload = true,
|
|
69
28
|
animate = false,
|
|
70
29
|
name,
|
|
71
|
-
|
|
72
|
-
|
|
30
|
+
silenceWarningMs,
|
|
31
|
+
silenceWarningContent,
|
|
73
32
|
}: BaseComponentProps & {
|
|
74
33
|
content?: React.ReactNode;
|
|
75
34
|
buttonText?: string;
|
|
76
|
-
/** Button text when recording is shorter than
|
|
35
|
+
/** Button text when the recording is shorter than minDurationMs. */
|
|
77
36
|
shortButtonText?: string;
|
|
78
37
|
className?: string;
|
|
79
38
|
containerClass?: string;
|
|
80
|
-
/** Minimum recording duration
|
|
81
|
-
|
|
82
|
-
/**
|
|
83
|
-
|
|
39
|
+
/** Minimum recording duration. If shorter, a warning is shown when paused. */
|
|
40
|
+
minDurationMs?: number;
|
|
41
|
+
/** Shown when the recording is shorter than minDurationMs. */
|
|
42
|
+
shortRecordingContent?: React.ReactNode;
|
|
84
43
|
/** Show the volume level meter during recording. Default true. */
|
|
85
44
|
showVisualizer?: boolean;
|
|
86
45
|
/** Upload audio immediately after recording to reduce final upload size. Default true. */
|
|
87
46
|
eagerUpload?: boolean;
|
|
88
47
|
animate?: boolean;
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
silenceWarningText?: string;
|
|
48
|
+
/** Milliseconds of continuous silence before a "speak up" banner appears. Disabled when undefined. */
|
|
49
|
+
silenceWarningMs?: number;
|
|
50
|
+
/** Shown in the silence banner. */
|
|
51
|
+
silenceWarningContent?: React.ReactNode;
|
|
94
52
|
}) {
|
|
95
53
|
const th = t(useTheme());
|
|
96
|
-
const resolvedButtonText = buttonText ?? (
|
|
97
|
-
const recorderRef = useRef<
|
|
54
|
+
const resolvedButtonText = buttonText ?? (minDurationMs != null ? 'Save & Continue' : 'Continue');
|
|
55
|
+
const recorderRef = useRef<RecorderHandle>(null);
|
|
98
56
|
const pendingContinueRef = useRef(false);
|
|
99
57
|
|
|
100
58
|
const [recordingData, setRecordingData] = useState<object | null>(null);
|
|
101
59
|
const [paused, setPaused] = useState(false);
|
|
102
60
|
const [pausedDuration, setPausedDuration] = useState(0);
|
|
103
61
|
|
|
104
|
-
const isTooShort =
|
|
62
|
+
const isTooShort = minDurationMs != null && pausedDuration < minDurationMs;
|
|
105
63
|
|
|
106
|
-
const handleSave = (
|
|
107
|
-
//
|
|
108
|
-
|
|
109
|
-
//
|
|
110
|
-
if (eagerUpload &&
|
|
111
|
-
const filename = generateAudioFilename(name ?? 'recording');
|
|
64
|
+
const handleSave = (recording: any) => {
|
|
65
|
+
// Named after the trial number this trial's row will get, which makes the name unique in the session
|
|
66
|
+
const saved = { ...recording, audioFile: audioFilename(name ?? 'VoiceRecording', data.trials.length + 1) };
|
|
67
|
+
// Uploads the recording now, so the final upload is smaller; if this fails, the final upload sends it
|
|
68
|
+
if (eagerUpload && saved.data64 && store.__uploadId) {
|
|
112
69
|
post('/data', {
|
|
113
|
-
sessionId: store.
|
|
114
|
-
files: [{ filename, content:
|
|
115
|
-
})
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
70
|
+
sessionId: store.__uploadId,
|
|
71
|
+
files: [{ filename: saved.audioFile, content: saved.data64, encoding: 'base64' }],
|
|
72
|
+
})
|
|
73
|
+
.then((response) => {
|
|
74
|
+
if (response.ok) markRecordingUploaded(saved.audioFile, saved.data64);
|
|
75
|
+
})
|
|
76
|
+
.catch(() => {});
|
|
119
77
|
}
|
|
120
78
|
|
|
121
|
-
setRecordingData(
|
|
79
|
+
setRecordingData(saved);
|
|
122
80
|
setPaused(false);
|
|
123
81
|
if (pendingContinueRef.current) {
|
|
124
82
|
pendingContinueRef.current = false;
|
|
125
|
-
next(
|
|
83
|
+
next(saved);
|
|
126
84
|
}
|
|
127
85
|
};
|
|
128
86
|
|
|
@@ -145,22 +103,22 @@ function VoiceRecording({
|
|
|
145
103
|
<div className={`max-w-prose mx-auto ${className} pt-20 pb-20 px-4 ${animate ? 'animate-fade-in opacity-0' : ''}`}>
|
|
146
104
|
{content && (
|
|
147
105
|
<article
|
|
148
|
-
className={
|
|
106
|
+
className={th.article}
|
|
149
107
|
>
|
|
150
108
|
{content}
|
|
151
109
|
</article>
|
|
152
110
|
)}
|
|
153
111
|
|
|
154
112
|
<div className='pt-6'>
|
|
155
|
-
<
|
|
113
|
+
<Recorder
|
|
156
114
|
ref={recorderRef}
|
|
157
115
|
handleSaveVoiceData={handleSave}
|
|
158
116
|
handleDiscardVoiceData={() => { setRecordingData(null); setPaused(false); }}
|
|
159
|
-
showStop={
|
|
160
|
-
showDiscard={
|
|
117
|
+
showStop={minDurationMs == null}
|
|
118
|
+
showDiscard={minDurationMs != null}
|
|
161
119
|
showVisualizer={showVisualizer}
|
|
162
|
-
|
|
163
|
-
|
|
120
|
+
silenceWarningMs={silenceWarningMs}
|
|
121
|
+
silenceWarningContent={silenceWarningContent}
|
|
164
122
|
onPause={handlePause}
|
|
165
123
|
onResume={handleResume}
|
|
166
124
|
/>
|
|
@@ -168,31 +126,31 @@ function VoiceRecording({
|
|
|
168
126
|
|
|
169
127
|
{paused && isTooShort && (
|
|
170
128
|
<div className={`mt-8 flex items-start space-x-3 p-4 border-2 ${th.buttonBorder} ${th.text} ${animate ? 'animate-fade-in opacity-0' : ''}`}>
|
|
171
|
-
<
|
|
129
|
+
<ExclamationTriangleIcon className='w-6 h-6 text-yellow-500 flex-shrink-0 mt-0.5' />
|
|
172
130
|
<p className='text-sm'>
|
|
173
|
-
{
|
|
131
|
+
{shortRecordingContent ?? 'Your recording seems quite short. Please consider adding more detail to your description.'}
|
|
174
132
|
</p>
|
|
175
133
|
</div>
|
|
176
134
|
)}
|
|
177
135
|
|
|
178
|
-
{/* Continue button (visible when paused,
|
|
179
|
-
{paused &&
|
|
136
|
+
{/* Continue button (visible when paused, minDurationMs mode only) */}
|
|
137
|
+
{paused && minDurationMs != null && (
|
|
180
138
|
<div className={`mt-8 flex justify-center ${animate ? 'animate-fade-in opacity-0' : ''}`}>
|
|
181
139
|
<button
|
|
182
140
|
onClick={finalize}
|
|
183
|
-
className={
|
|
141
|
+
className={th.button}
|
|
184
142
|
>
|
|
185
143
|
{isTooShort ? shortButtonText : resolvedButtonText}
|
|
186
144
|
</button>
|
|
187
145
|
</div>
|
|
188
146
|
)}
|
|
189
147
|
|
|
190
|
-
{/* Continue button after recording is stopped (non-
|
|
148
|
+
{/* Continue button after recording is stopped (non-minDurationMs mode) */}
|
|
191
149
|
{recordingData && !paused && (
|
|
192
150
|
<div className={`mt-16 flex justify-center ${animate ? 'animate-fade-in opacity-0' : ''}`}>
|
|
193
151
|
<button
|
|
194
152
|
onClick={() => next(recordingData)}
|
|
195
|
-
className={
|
|
153
|
+
className={th.button}
|
|
196
154
|
>
|
|
197
155
|
{resolvedButtonText}
|
|
198
156
|
</button>
|
|
@@ -203,4 +161,42 @@ function VoiceRecording({
|
|
|
203
161
|
);
|
|
204
162
|
}
|
|
205
163
|
|
|
206
|
-
export default
|
|
164
|
+
export default defineComponent({
|
|
165
|
+
name: 'VoiceRecording',
|
|
166
|
+
component: VoiceRecording,
|
|
167
|
+
session: true,
|
|
168
|
+
simulate: async ({ props, simulators, participant }) => {
|
|
169
|
+
// A trial can set respondTTS to undefined to use the base64 simulator instead
|
|
170
|
+
const { respondTTS } = simulators as Partial<typeof simulators>;
|
|
171
|
+
const result = await (respondTTS ?? simulators.respondBase64)({ props, participant });
|
|
172
|
+
|
|
173
|
+
let data64: string;
|
|
174
|
+
if (respondTTS) {
|
|
175
|
+
const text = result.value as string;
|
|
176
|
+
const ttsResult = await textToWebmBase64(text);
|
|
177
|
+
if (!ttsResult) throw new Error('TTS failed. Ensure say/espeak and ffmpeg are installed.');
|
|
178
|
+
data64 = ttsResult;
|
|
179
|
+
} else {
|
|
180
|
+
data64 = result.value as string;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
// Exact duration via ffprobe, fall back to estimate from file size
|
|
184
|
+
const recordingDurationMs = (await probeAudioDurationMs(data64)) ?? Math.round(data64.length / 4);
|
|
185
|
+
return {
|
|
186
|
+
recorded: {
|
|
187
|
+
type: 'audiorecording',
|
|
188
|
+
data64,
|
|
189
|
+
timestamp: new Date().toISOString(),
|
|
190
|
+
recordingDurationMs,
|
|
191
|
+
},
|
|
192
|
+
participant: result.participant,
|
|
193
|
+
durationMs: recordingDurationMs,
|
|
194
|
+
};
|
|
195
|
+
},
|
|
196
|
+
defaultSimulators: {
|
|
197
|
+
/** Returns text to be spoken via platform TTS. Default: generic test sentence. */
|
|
198
|
+
respondTTS: () => ({ value: 'This is a simulated voice recording for testing purposes.' }),
|
|
199
|
+
/** Returns raw base64-encoded WebM audio directly. Default: dummy 0.5s sine tone. */
|
|
200
|
+
respondBase64: () => ({ value: DUMMY_AUDIO_BASE64 }),
|
|
201
|
+
},
|
|
202
|
+
});
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
// The experiment's server: its routes on the page's own origin, or the simulation's server while simulating
|
|
2
|
+
let backendUrl = '/backend';
|
|
3
|
+
|
|
4
|
+
/** The address of the experiment's server, for components that talk to its routes. */
|
|
5
|
+
export function getBackendUrl() {
|
|
6
|
+
return backendUrl;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export function setBackendUrl(url: string) {
|
|
10
|
+
backendUrl = url;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** Sends JSON to one of the server's routes. */
|
|
14
|
+
export function post(endpoint: string, body: object) {
|
|
15
|
+
return fetch(`${backendUrl}${endpoint}`, {
|
|
16
|
+
method: 'POST',
|
|
17
|
+
headers: { 'Content-Type': 'application/json' },
|
|
18
|
+
body: JSON.stringify(body),
|
|
19
|
+
});
|
|
20
|
+
}
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
import { freezeInDevelopment } from './development';
|
|
2
|
+
import type { Store } from './store';
|
|
3
|
+
import type { TimelineContext } from './timeline';
|
|
4
|
+
|
|
5
|
+
export const BLOCK: unique symbol = Symbol('reactive.block');
|
|
6
|
+
|
|
7
|
+
type Condition = (context: TimelineContext) => boolean;
|
|
8
|
+
|
|
9
|
+
/** A block of control flow. */
|
|
10
|
+
export type BlockSpec =
|
|
11
|
+
| { kind: 'if'; cond: Condition; items: readonly unknown[]; else?: readonly unknown[] }
|
|
12
|
+
| { kind: 'while'; cond: Condition; body: readonly unknown[] }
|
|
13
|
+
| { kind: 'updateStore'; update: (context: TimelineContext) => Record<string, any> }
|
|
14
|
+
| { kind: 'marker'; id: string }
|
|
15
|
+
| { kind: 'ifGoto'; cond: Condition; marker: string }
|
|
16
|
+
| { kind: 'fullscreen'; items: readonly unknown[] };
|
|
17
|
+
|
|
18
|
+
export function isBlock(item: unknown): item is { [BLOCK]: BlockSpec } {
|
|
19
|
+
return typeof item === 'object' && item !== null && BLOCK in item;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// IfGoto jumps when its condition holds, UnlessGoto when it does not
|
|
23
|
+
type Instruction<Content> =
|
|
24
|
+
| { type: 'ExecuteContent'; content: Content }
|
|
25
|
+
| { type: 'Goto'; marker: string }
|
|
26
|
+
| { type: 'IfGoto'; cond: Condition; marker: string }
|
|
27
|
+
| { type: 'UnlessGoto'; cond: Condition; marker: string }
|
|
28
|
+
| { type: 'UpdateStore'; update: (context: TimelineContext) => Record<string, any> };
|
|
29
|
+
|
|
30
|
+
/** A compiled timeline: instructions over content of type `Content`. */
|
|
31
|
+
export interface Bytecode<Content> {
|
|
32
|
+
instructions: Instruction<Content>[];
|
|
33
|
+
markers: Record<string, number>;
|
|
34
|
+
/** The spans of instructions that run in fullscreen, each from its first to just after its last. */
|
|
35
|
+
fullscreen: [number, number][];
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// The if-branches an item sits in, from the outside in
|
|
39
|
+
export type BranchPath = readonly { block: number; arm: 'then' | 'else' }[];
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Lowers a timeline to bytecode. Nested lists are flattened and `false`, `null` and `undefined`
|
|
43
|
+
* are skipped; everything that is not a block becomes content through `toContent`.
|
|
44
|
+
*/
|
|
45
|
+
export function compileTimeline<Content>(
|
|
46
|
+
timeline: readonly unknown[],
|
|
47
|
+
toContent: (item: unknown, branch: BranchPath) => Content,
|
|
48
|
+
): Bytecode<Content> {
|
|
49
|
+
const instructions: Instruction<Content>[] = [];
|
|
50
|
+
const markers: Record<string, number> = {};
|
|
51
|
+
const fullscreen: [number, number][] = [];
|
|
52
|
+
const gotoTargets: string[] = [];
|
|
53
|
+
let blockCount = 0;
|
|
54
|
+
|
|
55
|
+
function emit(items: readonly unknown[], branch: BranchPath) {
|
|
56
|
+
for (const item of items) {
|
|
57
|
+
if (item === false || item === null || item === undefined) continue;
|
|
58
|
+
if (Array.isArray(item)) {
|
|
59
|
+
emit(item, branch);
|
|
60
|
+
continue;
|
|
61
|
+
}
|
|
62
|
+
if (!isBlock(item)) {
|
|
63
|
+
instructions.push({ type: 'ExecuteContent', content: toContent(item, branch) });
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const block = item[BLOCK];
|
|
68
|
+
const id = blockCount++;
|
|
69
|
+
switch (block.kind) {
|
|
70
|
+
case 'marker':
|
|
71
|
+
if (`user_${block.id}` in markers) {
|
|
72
|
+
throw new Error(`The marker '${block.id}' is in the timeline twice, so ifGoto could not tell which one to jump to.`);
|
|
73
|
+
}
|
|
74
|
+
markers[`user_${block.id}`] = instructions.length;
|
|
75
|
+
break;
|
|
76
|
+
case 'ifGoto':
|
|
77
|
+
instructions.push({ type: 'IfGoto', cond: block.cond, marker: `user_${block.marker}` });
|
|
78
|
+
gotoTargets.push(block.marker);
|
|
79
|
+
break;
|
|
80
|
+
case 'updateStore':
|
|
81
|
+
instructions.push({ type: 'UpdateStore', update: block.update });
|
|
82
|
+
break;
|
|
83
|
+
case 'if': {
|
|
84
|
+
const end = `if_end_${id}`;
|
|
85
|
+
const elseStart = `if_else_${id}`;
|
|
86
|
+
instructions.push({ type: 'UnlessGoto', cond: block.cond, marker: block.else ? elseStart : end });
|
|
87
|
+
emit(block.items, [...branch, { block: id, arm: 'then' }]);
|
|
88
|
+
if (block.else) {
|
|
89
|
+
instructions.push({ type: 'Goto', marker: end });
|
|
90
|
+
markers[elseStart] = instructions.length;
|
|
91
|
+
emit(block.else, [...branch, { block: id, arm: 'else' }]);
|
|
92
|
+
}
|
|
93
|
+
markers[end] = instructions.length;
|
|
94
|
+
break;
|
|
95
|
+
}
|
|
96
|
+
case 'fullscreen': {
|
|
97
|
+
const start = instructions.length;
|
|
98
|
+
emit(block.items, branch);
|
|
99
|
+
fullscreen.push([start, instructions.length]);
|
|
100
|
+
break;
|
|
101
|
+
}
|
|
102
|
+
case 'while': {
|
|
103
|
+
const start = `while_start_${id}`;
|
|
104
|
+
const end = `while_end_${id}`;
|
|
105
|
+
markers[start] = instructions.length;
|
|
106
|
+
instructions.push({ type: 'UnlessGoto', cond: block.cond, marker: end });
|
|
107
|
+
emit(block.body, branch);
|
|
108
|
+
instructions.push({ type: 'Goto', marker: start });
|
|
109
|
+
markers[end] = instructions.length;
|
|
110
|
+
break;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
emit(timeline, []);
|
|
117
|
+
|
|
118
|
+
for (const target of gotoTargets) {
|
|
119
|
+
if (!(`user_${target}` in markers)) {
|
|
120
|
+
throw new Error(`ifGoto jumps to the marker '${target}', which is not in the timeline.`);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
return { instructions, markers, fullscreen };
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// No timeline runs this many steps of control flow between two trials or slides unless it loops forever
|
|
128
|
+
const MAX_CONTROL_STEPS = 100_000;
|
|
129
|
+
|
|
130
|
+
// What a jump back to the marker repeats, as the timeline was written
|
|
131
|
+
const repeated = (marker: string) =>
|
|
132
|
+
marker.startsWith('user_') ? `the ifGoto back to the marker '${marker.slice('user_'.length)}'` : 'a whileBlock';
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Runs control flow from `fromPointer` on. Returns the pointer of the next content instruction,
|
|
136
|
+
* or the length of the bytecode once the timeline is finished, and the store as the store
|
|
137
|
+
* updates on the way left it.
|
|
138
|
+
*/
|
|
139
|
+
export function advanceToNextContent<Content>(
|
|
140
|
+
bytecode: Bytecode<Content>,
|
|
141
|
+
fromPointer: number,
|
|
142
|
+
fromStore: Store,
|
|
143
|
+
contextFor: (store: Store) => TimelineContext,
|
|
144
|
+
): { pointer: number; store: Store } {
|
|
145
|
+
let pointer = fromPointer;
|
|
146
|
+
let store = fromStore;
|
|
147
|
+
let steps = 0;
|
|
148
|
+
let loop = '';
|
|
149
|
+
while (pointer < bytecode.instructions.length) {
|
|
150
|
+
const instruction = bytecode.instructions[pointer];
|
|
151
|
+
if (instruction.type === 'ExecuteContent') break;
|
|
152
|
+
// It always throws, since a timeline that never reaches its next trial cannot go on
|
|
153
|
+
if (++steps > MAX_CONTROL_STEPS) {
|
|
154
|
+
throw new Error(
|
|
155
|
+
`The timeline repeats ${loop} without reaching anything to show, so it would never end. Its condition has to change, or a trial or slide has to run inside it.`,
|
|
156
|
+
);
|
|
157
|
+
}
|
|
158
|
+
const from = pointer;
|
|
159
|
+
|
|
160
|
+
if (instruction.type === 'Goto') {
|
|
161
|
+
pointer = bytecode.markers[instruction.marker];
|
|
162
|
+
} else if (instruction.type === 'IfGoto') {
|
|
163
|
+
pointer = instruction.cond(contextFor(store)) ? bytecode.markers[instruction.marker] : pointer + 1;
|
|
164
|
+
} else if (instruction.type === 'UnlessGoto') {
|
|
165
|
+
pointer = instruction.cond(contextFor(store)) ? pointer + 1 : bytecode.markers[instruction.marker];
|
|
166
|
+
} else {
|
|
167
|
+
const updates = instruction.update(contextFor(store));
|
|
168
|
+
if (typeof updates === 'object' && updates !== null) {
|
|
169
|
+
store = freezeInDevelopment({ ...store, ...updates });
|
|
170
|
+
} else {
|
|
171
|
+
console.warn('A store update did not return an object, so the store is unchanged.');
|
|
172
|
+
}
|
|
173
|
+
pointer++;
|
|
174
|
+
}
|
|
175
|
+
if (pointer <= from && 'marker' in instruction) loop = repeated(instruction.marker);
|
|
176
|
+
}
|
|
177
|
+
return { pointer, store };
|
|
178
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The prefixes of the CSV columns the library writes: a trial's own fields, its metadata, response
|
|
3
|
+
* fields that would otherwise start with one of these, URL params that nothing declares, the
|
|
4
|
+
* Upload's `sessionData`, and a CanvasBlock's metadata next to that of its slides.
|
|
5
|
+
*/
|
|
6
|
+
export const columnPrefixes = {
|
|
7
|
+
trial: 'trial_',
|
|
8
|
+
meta: 'meta_',
|
|
9
|
+
response: 'response_',
|
|
10
|
+
url: 'url_',
|
|
11
|
+
session: 'session_',
|
|
12
|
+
slideblockMeta: 'slideblock_meta_',
|
|
13
|
+
} as const;
|
|
14
|
+
|
|
15
|
+
/** The session CSV's columns that hold the session itself, before its params and trials. */
|
|
16
|
+
export const sessionColumns = ['sessionId', 'userAgent', 'buildSeed'] as const;
|
|
17
|
+
|
|
18
|
+
const reserved: readonly string[] = Object.values(columnPrefixes);
|
|
19
|
+
|
|
20
|
+
/** The prefixes of the session CSV's columns that are neither params nor trials. */
|
|
21
|
+
export const sessionPrefixes = [columnPrefixes.url, columnPrefixes.session] as const;
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* The CSV column for a field of a response. A field whose name starts with one of the prefixes gets
|
|
25
|
+
* `response_` in front, so that it can never take the place of a column the library writes.
|
|
26
|
+
*/
|
|
27
|
+
export function responseColumn(field: string): string {
|
|
28
|
+
return reserved.some((prefix) => field.startsWith(prefix)) ? columnPrefixes.response + field : field;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Whether a param, which is a session CSV column of its own name, would take a column the library writes. */
|
|
32
|
+
export function isReservedParamName(name: string): boolean {
|
|
33
|
+
return (
|
|
34
|
+
(sessionColumns as readonly string[]).includes(name) ||
|
|
35
|
+
sessionPrefixes.some((prefix) => name.startsWith(prefix))
|
|
36
|
+
);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Whether a trial, whose session CSV columns are `<name>_<field>`, would take columns the library writes. */
|
|
40
|
+
export function isReservedTrialName(name: string): boolean {
|
|
41
|
+
return sessionPrefixes.some((prefix) => `${name}_`.startsWith(prefix));
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
type SessionPrefix = (typeof sessionPrefixes)[number];
|
|
45
|
+
|
|
46
|
+
/** The param names `isReservedParamName` rejects, for the types. */
|
|
47
|
+
export type ReservedParamName = (typeof sessionColumns)[number] | `${SessionPrefix}${string}`;
|
|
48
|
+
|
|
49
|
+
/** The trial names `isReservedTrialName` rejects, for the types: a prefix with or without its `_`, and names that start with one. */
|
|
50
|
+
export type ReservedTrialName = `${SessionPrefix}${string}` | (SessionPrefix extends `${infer Base}_` ? Base : never);
|