@adriansteffan/reactive 0.2.6 → 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.
Files changed (156) hide show
  1. package/README.md +796 -229
  2. package/bin/add.js +56 -0
  3. package/bin/deploy.js +48 -0
  4. package/bin/download.js +28 -0
  5. package/bin/ghsetup.js +21 -0
  6. package/bin/native.js +81 -0
  7. package/bin/setup.js +11 -17
  8. package/bin/study-deploy.js +60 -0
  9. package/bin/undeploy.js +15 -0
  10. package/extras/transcription/compose.yaml +32 -0
  11. package/{template → extras}/transcription/transcribe.py +4 -9
  12. package/package.json +62 -64
  13. package/src/bun-env.d.ts +1 -0
  14. package/src/bun-plugin.ts +22 -0
  15. package/src/components/canvasblock.tsx +209 -537
  16. package/src/components/checkdevice.tsx +64 -84
  17. package/src/components/fullscreenblock.tsx +130 -0
  18. package/src/components/icons.tsx +50 -0
  19. package/src/components/index.ts +9 -11
  20. package/src/components/microphonecheck.tsx +76 -38
  21. package/src/components/plaininput.tsx +48 -41
  22. package/src/components/prolificending.tsx +64 -28
  23. package/src/components/quest.tsx +89 -87
  24. package/src/components/{randomdotkinetogram.tsx → randomdotkinematogram.tsx} +205 -267
  25. package/src/components/{voicerecorder.tsx → recorder.tsx} +81 -106
  26. package/src/components/requestfilepermission.tsx +63 -0
  27. package/src/components/stimulus.tsx +373 -0
  28. package/src/components/storeui.tsx +94 -148
  29. package/src/components/text.tsx +61 -59
  30. package/src/components/tutorial.tsx +45 -47
  31. package/src/components/upload.tsx +133 -309
  32. package/src/components/voicerecording.tsx +90 -94
  33. package/src/core/backend.ts +20 -0
  34. package/src/core/bytecode.ts +178 -0
  35. package/src/core/columns.ts +50 -0
  36. package/src/core/component.ts +238 -0
  37. package/src/core/development.ts +32 -0
  38. package/src/core/experiment.ts +263 -0
  39. package/src/core/files.ts +291 -0
  40. package/src/core/params.ts +166 -0
  41. package/src/core/platform.ts +29 -0
  42. package/src/core/rows.ts +106 -0
  43. package/src/core/simulation.ts +158 -0
  44. package/src/core/slides.ts +178 -0
  45. package/src/core/store.ts +22 -0
  46. package/src/core/timeline.ts +399 -0
  47. package/src/fonts/AtkinsonHyperlegible-Bold.woff2 +0 -0
  48. package/src/fonts/AtkinsonHyperlegible-BoldItalic.woff2 +0 -0
  49. package/src/fonts/AtkinsonHyperlegible-Italic.woff2 +0 -0
  50. package/src/fonts/AtkinsonHyperlegible-Regular.woff2 +0 -0
  51. package/src/index.css +5 -7
  52. package/src/mod.tsx +31 -17
  53. package/src/native.ts +127 -0
  54. package/src/quest.ts +2 -0
  55. package/src/runner/contexts.ts +35 -0
  56. package/src/runner/devpanel.tsx +68 -0
  57. package/src/runner/experimentrunner.tsx +210 -0
  58. package/src/runner/fullscreenguard.tsx +93 -0
  59. package/src/runner/paraminput.tsx +86 -0
  60. package/src/runner/progressbar.tsx +20 -0
  61. package/src/runner/settingsscreen.tsx +517 -0
  62. package/src/{utils → runner}/theme.ts +9 -8
  63. package/src/server.ts +93 -0
  64. package/src/tutorial.ts +3 -0
  65. package/src/utils/array.ts +30 -62
  66. package/src/utils/canvas.ts +66 -0
  67. package/src/utils/ddm.ts +47 -70
  68. package/src/utils/distributions.ts +352 -61
  69. package/src/utils/fullscreen.ts +38 -0
  70. package/src/utils/ids.ts +11 -0
  71. package/src/utils/keys.ts +46 -0
  72. package/src/utils/llm.ts +15 -15
  73. package/src/utils/time.ts +12 -0
  74. package/src/utils/tts.ts +24 -24
  75. package/template/.dockerignore +3 -1
  76. package/template/.env.example +5 -0
  77. package/template/.github/workflows/deploy.yml +25 -0
  78. package/template/.gitignore +14 -0
  79. package/template/Dockerfile +9 -14
  80. package/template/README.md +74 -214
  81. package/template/biome.json +34 -0
  82. package/template/build.ts +20 -0
  83. package/template/bunfig.toml +3 -0
  84. package/template/docker-compose.yaml +4 -33
  85. package/template/index.html +2 -2
  86. package/template/package.json +16 -89
  87. package/template/public/.gitkeep +0 -0
  88. package/template/server.ts +32 -0
  89. package/template/simulate.ts +4 -44
  90. package/template/src/Experiment.tsx +76 -128
  91. package/template/src/bun-env.d.ts +1 -0
  92. package/template/src/index.css +1 -9
  93. package/template/src/main.tsx +25 -10
  94. package/template/tsconfig.json +4 -6
  95. package/.claude/settings.local.json +0 -61
  96. package/.eslintrc.cjs +0 -18
  97. package/.playwright-mcp/console-2026-04-07T14-22-59-060Z.log +0 -1
  98. package/.prettierrc +0 -5
  99. package/Dockerfile +0 -20
  100. package/dist/mod-HDegGPrf.js +0 -87434
  101. package/dist/mod.d.ts +0 -946
  102. package/dist/reactive.es.js +0 -87
  103. package/dist/reactive.umd.js +0 -10255
  104. package/dist/style.css +0 -5
  105. package/dist/web-7BbR1Ad7.js +0 -435
  106. package/dist/web-CATfZO1Q.js +0 -12
  107. package/planned.md +0 -103
  108. package/postcss.config.js +0 -6
  109. package/raw-loader-hooks.mjs +0 -25
  110. package/raw-loader.mjs +0 -5
  111. package/rdk_doc.md +0 -341
  112. package/src/components/enterfullscreen.tsx +0 -230
  113. package/src/components/exitfullscreen.tsx +0 -113
  114. package/src/components/experimentprovider.tsx +0 -69
  115. package/src/components/experimentrunner.tsx +0 -497
  116. package/src/components/mobilefilepermission.tsx +0 -68
  117. package/src/components/settingsscreen.tsx +0 -770
  118. package/src/types/array.d.ts +0 -6
  119. package/src/utils/audiodevice.ts +0 -4
  120. package/src/utils/bytecode.ts +0 -261
  121. package/src/utils/common.ts +0 -291
  122. package/src/utils/ddm.test.ts +0 -233
  123. package/src/utils/distributions.test.ts +0 -209
  124. package/src/utils/nodecompat.ts +0 -11
  125. package/src/utils/overlays.ts +0 -19
  126. package/src/utils/request.ts +0 -25
  127. package/src/utils/simulation.ts +0 -299
  128. package/src/utils/upload.ts +0 -275
  129. package/src/vite-env.d.ts +0 -1
  130. package/template/.env.template +0 -2
  131. package/template/.eslintrc.cjs +0 -18
  132. package/template/.prettierrc +0 -5
  133. package/template/backend/package-lock.json +0 -2544
  134. package/template/backend/package.json +0 -31
  135. package/template/backend/src/backend.ts +0 -131
  136. package/template/backend/tsconfig.json +0 -110
  137. package/template/capacitor.config.ts +0 -15
  138. package/template/electron/main.js +0 -131
  139. package/template/electron/preload.js +0 -9
  140. package/template/electron.vite.config.js +0 -45
  141. package/template/package-lock.json +0 -12467
  142. package/template/postcss.config.js +0 -5
  143. package/template/public/Atkinson_Hyperlegible/AtkinsonHyperlegible-Bold.ttf +0 -0
  144. package/template/public/Atkinson_Hyperlegible/AtkinsonHyperlegible-BoldItalic.ttf +0 -0
  145. package/template/public/Atkinson_Hyperlegible/AtkinsonHyperlegible-Italic.ttf +0 -0
  146. package/template/public/Atkinson_Hyperlegible/AtkinsonHyperlegible-Regular.ttf +0 -0
  147. package/template/shared.vite.config.js +0 -39
  148. package/template/src/vite-env.d.ts +0 -2
  149. package/template/tsconfig.node.json +0 -12
  150. package/template/vite.config.js +0 -11
  151. package/tsconfig.json +0 -30
  152. package/tsconfig.node.json +0 -12
  153. package/vite.config.ts +0 -39
  154. /package/{template → extras}/transcription/Dockerfile.cpu +0 -0
  155. /package/{template → extras}/transcription/Dockerfile.gpu +0 -0
  156. /package/{template/public/Atkinson_Hyperlegible → src/fonts}/OFL.txt +0 -0
package/README.md CHANGED
@@ -1,19 +1,19 @@
1
1
  # reactive
2
2
 
3
- A framework for quickly building interactive online experiments using Typescript, React, and TailwindCSS. Comes with a template project that has all batteries included (build tools, docker deployment setup, node server for upload etc.)
3
+ A framework for quickly building interactive online experiments using Typescript, React, and TailwindCSS. Comes with a template project that has all batteries included (build tools, docker deployment setup, Bun server for upload etc.)
4
4
  The project is very early stage, so many of the abstractions are still very leaky and the documentation is largely unfinished.
5
5
 
6
6
 
7
7
  ## Prerequisites
8
8
 
9
- You will need a current version of [node.js](https://nodejs.org/en/download/) installed on your system.
9
+ You will need a current version of [Bun](https://bun.sh/) installed on your system. Projects run entirely on Bun: the dev server, the production build, the upload backend and simulations.
10
10
 
11
11
  ## Using the package
12
12
 
13
13
  ### Create a template project
14
14
 
15
15
  ```
16
- npx @adriansteffan/reactive
16
+ bunx @adriansteffan/reactive
17
17
  ```
18
18
 
19
19
  Then follow the instructions shown there and in the created `README.md`
@@ -21,28 +21,432 @@ Then follow the instructions shown there and in the created `README.md`
21
21
 
22
22
  ### Usage
23
23
 
24
- For now, refer to the `Experiment.tsx` in the template project to find out how to define an experiment, and add custom trials and questions!
24
+ An experiment is defined in `src/Experiment.tsx` of the template project, which exports `defineExperiment(...)`:
25
+
26
+ ```tsx
27
+ import { defineExperiment, PlainInput, Text, Upload } from '@adriansteffan/reactive';
28
+
29
+ export default defineExperiment({
30
+ config: { showProgressBar: true },
31
+ timeline: [
32
+ Text.trial('welcome', { content: <p>Welcome!</p>, buttonText: 'Start' }),
33
+ PlainInput.trial('nickname', { content: <p>What is your nickname?</p> }),
34
+ Text.trial('thanks', ({ data }) => ({
35
+ content: <p>Thank you, {PlainInput.getLatest(data, 'nickname').recorded.value}!</p>,
36
+ })),
37
+ Upload.trial('upload'),
38
+ ],
39
+ });
40
+ ```
41
+
42
+ `config` sets `showProgressBar` and the `theme`: `'light'` (the default), `'dark'`, or `'dark-plain'`, a dark theme without the background pattern. The other fields of `defineExperiment` are `params` (below) and `simulation` (see [Simulation](#simulation)).
25
43
 
26
44
  Premade components available so far:
27
45
 
28
46
  * Text: A simple display of Text and a Button
29
- * MicCheck: used to test the voice recording feature and choose a preferred microphone to use
30
- * CanvasBlock: TODO DOC
31
- * IF_BLOCK: TODO DOC
32
- * IF_GOTO: TODO DOC
33
- * MARKER: TODO DOC
34
- * UPDATE_STORE: TODO DOC
35
- * StoreUI: TODO DOC
36
- * DeviceCheck: TODO DOC
37
- * ProlificEnd: TODO DOC
38
- * Quest: SurveyJS questionnaires
47
+ * Stimulus: Any React or a canvas, answered by keys, buttons, or the content itself (see [Stimuli](#stimuli))
48
+ * PlainInput: A text input with a prompt
49
+ * MicrophoneCheck: used to test the voice recording feature and choose a preferred microphone to use
50
+ * CanvasBlock: A sequence of canvas slides with keyboard responses, for timed tasks (see [Timed slides](#timed-slides))
51
+ * StoreUI: A form that writes its fields to the store
52
+ * CheckDevice: Gathers information about the participant's device and can stop participants whose device does not fit
53
+ * fullscreenBlock: Runs its trials in fullscreen, after a screen that asks the participant into it (see [Fullscreen](#fullscreen))
54
+ * ProlificEnding: Shows the Prolific completion code
55
+ * Quest (extra): SurveyJS questionnaires
39
56
  * ... all questiontypes supported by SurveyJS can be used
40
57
  * voicerecorder: a custom question type that allows participants to record voice
41
- * Tutorial: A paginated slide deck with navigation, dot indicators, and optional interactive slides via `useTutorialSlide`
58
+ * your own question types, as React components passed by name to `customQuestions`
59
+ * Tutorial (extra): A paginated slide deck with navigation, dot indicators, and optional interactive slides via `useTutorialSlide`
42
60
  * RandomDotKinematogram: A random dot kinematogram (RDK) stimulus for motion perception experiments
43
61
  * VoiceRecording: A standalone voice recording trial with pause/stop controls, optional minimum duration warning, and confirmation dialog
44
- * Upload: Uploads the collected data on a button press by the participant
62
+ * Upload: Uploads the collected data on a button press by the participant
63
+
64
+ Quest and Tutorial are extras: they need packages of their own, so a new project leaves them out. Add them in the project's root directory with
65
+
66
+ ```
67
+ bunx @adriansteffan/reactive add quest tutorial
68
+ ```
69
+
70
+ and import them from their own entry points:
71
+
72
+ ```tsx
73
+ import { Quest } from '@adriansteffan/reactive/quest';
74
+ import { Tutorial, useTutorialSlide } from '@adriansteffan/reactive/tutorial';
75
+ ```
76
+
77
+ An experiment that does not use them neither installs them nor sends them to its participants.
78
+
79
+ ### Trials
80
+
81
+ `Component.trial(name?, props)` puts a component into the timeline. The name is optional, but it identifies the trial in the data and is needed to read its result later. Props are checked against the component; a component with required props needs them here.
82
+
83
+ Name every trial your analysis needs to find, or give it metadata that identifies it, such as a stimulus id. Rows carry no other lasting identity: their `trialNumber` is the order in which the participant saw the trials, which shifts whenever the timeline changes.
84
+
85
+ Further settings are chained. Every method returns a new trial and leaves the one it was called on unchanged. Passing `undefined` leaves a setting as it is, which keeps optional settings inline. Variants of a trial are made by a function:
86
+
87
+ ```tsx
88
+ const feedback = (name: string, content: ReactNode) => Text.trial(name, { content, buttonText: 'Continue' });
89
+
90
+ feedback('slow', <p>Take your time.</p>),
91
+ Text.trial('instructions').metadata(isPractice ? { practice: true } : undefined),
92
+ ```
93
+
94
+ | Method | Description |
95
+ |---|---|
96
+ | `.metadata(values)` | Extra values for this trial's rows, kept apart from what it recorded and merged into those set before (see [Metadata](#metadata)) |
97
+ | `.csv(files)` | Renames the CSV files of this trial's rows, or keeps them out with `null` (see [Per-trial CSV files](#per-trial-csv-files)) |
98
+ | `.session(enabled)` | Puts this trial's columns in the session CSV, or keeps them out with `false`, whatever its component does (see [Session columns](#session-columns)) |
99
+ | `.simulators(simulators)` | Replaces some of the component's simulators (see [Simulation](#simulation)) |
100
+ | `.collectRefreshRate(enabled?)` | Measures the screen's refresh rate while the trial runs, for later canvas trials |
101
+ | `.hideParams(names \| true)` | Hides the component's params from the settings page; the names must be the component's params |
102
+
103
+ Times are in milliseconds everywhere, in props as in the recorded data, and their names end in `Ms`: `durationMs`, `reactionTimeMs`, and each row's `startMs` and `endMs`.
104
+
105
+ ### Reading results
106
+
107
+ Props, metadata, conditions and store updates can be functions of the timeline context (`TimelineContext`), which they receive when the trial runs. Its `data` holds everything recorded so far, which every component reads with `getAll` and `getLatest`, typed by the component:
108
+
109
+ ```tsx
110
+ Text.trial(({ data }) => ({ content: <p>Hello {PlainInput.getLatest(data, 'nickname').recorded.value}</p> }));
111
+
112
+ // Repeat the practice until 8 of the last 10 answers are correct
113
+ whileBlock(({ data }) => Stimulus.getAll(data, 'practice').slice(-10)
114
+ .filter((row) => row.recorded.response === row.metadata?.correct).length < 8, [practice]),
115
+ ```
116
+
117
+ `getAll(data)` returns the rows of the component's trials, in the order they ran, and `getAll(data, 'practice')` those of its trial named `practice`, as often as it ran; unnamed trials, such as those made in a loop, are found by their `metadata`. `getLatest(data, 'nickname')` returns the latest row of a named trial, and `getLatest(data)` that of the component's most recent trial, such as feedback after each trial of a loop needs. Both stop if no such trial has run yet; for a trial that may have been skipped, `getAll(data, 'nickname').at(-1)` is `undefined` until it has run. A row holds the trial's `recorded`, its `metadata`, and its `trialNumber`, `startMs`, `endMs` and `durationMs`. A name that is not the component's in the timeline stops the experiment during development and simulation; for real participants it is logged instead. Both work wherever `data` is: in these callbacks, in your components' `data` prop, in simulate functions, and in the raw data a study uploads.
118
+
119
+ `data.trials` lists all rows, in the order the participant saw them, so `data.trials.at(-1)` is the last one and `data.trials.length` counts them. `data.session` holds what the session recorded when it started: every param with its value and declaration, the build seed, the user agent, and the timeline's named trials. The timeline context also holds the `store`, and inside a CanvasBlock, `slides` (see [Timed slides](#timed-slides)).
120
+
121
+ These callbacks must not change the context's `data` or `store`: they are frozen during development and simulation, so trying throws. The store changes only through `updateStore` (below) and through components.
122
+
123
+ ### Control flow
124
+
125
+ The timeline is a list of trials and blocks. Lists can be nested, and `false`, `null` and `undefined` are skipped, so pieces of a timeline can be combined like React children:
126
+
127
+ ```tsx
128
+ timeline: [
129
+ welcomeAndConsent,
130
+ group === 'vn' ? [soundCheck, visualNovel] : vignette,
131
+ group === 'vn' && credits,
132
+ upload,
133
+ ]
134
+ ```
135
+
136
+ This covers choices that are fixed before the participant starts. Choices that depend on their answers use blocks, which are decided when the participant reaches them:
137
+
138
+ ```tsx
139
+ const clickedSlowly = ({ data }: TimelineContext) => CustomTrial.getLatest(data, 'customtrial').recorded.totalTimeMs > 3000;
140
+
141
+ ifBlock(clickedSlowly, [Text.trial({ content: <p>Take your time.</p> })]).else([
142
+ Text.trial({ content: <p>That was quick!</p> }),
143
+ ]),
144
+ whileBlock(({ store }) => (store.attempts ?? 0) < 3, [practiceRound]),
145
+ updateStore(({ store }) => ({ attempts: (store.attempts ?? 0) + 1 })),
146
+ marker('retry'),
147
+ ifGoto(({ data }) => !Quiz.getLatest(data, 'quiz').recorded.passed, 'retry'),
148
+ ```
149
+
150
+ A condition written as a named function, like `clickedSlowly`, can be reused in several blocks and props without storing a flag. `updateStore` is for values that carry forward, such as a bonus.
151
+
152
+ `ifGoto` jumps to the `marker` with its id, forward or back, and also into the middle of a block: the rest of the block then runs, and a `whileBlock` checks its condition again when its items are done. Within a timeline, each marker id can be used once and every `ifGoto` needs its marker, which is checked when the experiment loads; a CanvasBlock's timeline has markers of its own. On the settings screen, markers cannot be deselected, and a deselected block leaves its markers in its place, so no jump loses its target.
153
+
154
+ A `whileBlock` or a jump back that repeats without ever reaching a trial would freeze the page, so the experiment stops with an error that names the loop instead.
155
+
156
+ #### Fullscreen
157
+
158
+ `fullscreenBlock` runs its trials in fullscreen:
159
+
160
+ ```tsx
161
+ fullscreenBlock({ keepFullscreen: true }, [instructions, task]),
162
+ ```
163
+
164
+ It starts with a screen that asks the participant into fullscreen, which browsers only allow after a click. The experiment leaves fullscreen once the run is outside the block, at its end or through a jump, so there is nothing to close.
165
+
166
+ | Option | Description |
167
+ |---|---|
168
+ | `content`, `buttonText` | The screen's text and button |
169
+ | `keepFullscreen` | Asks the participant back into fullscreen on every trial of the block: `true` for a small button, `{ buttonText }` to change its text, or `{ mode: 'overlay', content, buttonText }` for a screen over the trial |
170
+ | `stopOnFailure` | Ends the experiment on the screen when the browser cannot enter fullscreen, instead of asking again; nothing is uploaded |
171
+ | `errorContent` | Shown when the browser could not enter fullscreen |
172
+ | `delayMs` | How long after entering fullscreen the block's first trial starts |
173
+ | `className`, `containerClass`, `centered`, `animate` | The screen's look, as for Text |
174
+
175
+ On the settings screen, the block's screen is listed as an item of its own, so the trials can run without fullscreen while you test them.
176
+
177
+ Within one timeline, two different trials cannot share a name, even if their components differ, unless they sit in different branches of the same `ifBlock`. A name cannot be `url` or `session`, or start with `url_` or `session_`, since its columns in the session CSV would then take the library's (see [Output files](#output-files)); the types reject these names too. An unnamed trial that goes to the session CSV is named after its component for its columns there: the first `PlainInput` (`PlainInput_value`), the next ones `PlainInput_2`, `PlainInput_3` and so on, in the order they appear in the timeline. These names count positions, so they change when the timeline does; give a trial a name of its own when your analysis reads its columns.
178
+
179
+ ### Stimuli
180
+
181
+ `Stimulus` shows any React and takes an answer, by a key, a button, or both:
182
+
183
+ ```tsx
184
+ Stimulus.trial('face', {
185
+ content: <img src={face} />,
186
+ response: {
187
+ choices: {
188
+ happy: { key: 'f', button: 'Happy' },
189
+ sad: { key: 'j', button: 'Sad' },
190
+ },
191
+ timeLimitMs: 3000,
192
+ },
193
+ displayDurationMs: 500,
194
+ }),
195
+ ```
196
+
197
+ Its row records the `response`, the `key` that gave it, empty for a button, and the `reactionTimeMs`. Without an answer in time, all three are empty.
198
+
199
+ | `response` field | Description |
200
+ |---|---|
201
+ | `choices` | Answers recorded by their names, each given by a `key`, a `button`, or both |
202
+ | `keys` | Keys recorded as themselves, or `true` for any key |
203
+ | `buttons` | Buttons recorded as their text |
204
+ | `timeLimitMs` | How long after the stimulus appears an answer counts; the trial ends then |
205
+ | `endsTrial` | Whether the first answer ends the trial; `true` by default, and otherwise the trial ends at its time limit |
206
+ | `recordAll` | Records every answer until the time limit, not only the first, so the trial lasts until then |
207
+
208
+ `displayDurationMs` hides the content after that time, while answers count until the time limit. Without a time limit, the trial ends when the content disappears. A trial needs a way to end, an answer, a time limit or a display duration, which the types check.
209
+
210
+ With `endsTrial: false`, every trial lasts until its time limit, whenever the answer came, as fixed-duration designs need. With `recordAll`, a trial records each answer in `responses`, in order, such as a press for every target in a stream; `response`, `key` and `reactionTimeMs` still hold the first. In the stimulus CSV, such a trial has a row for each answer, or one empty row without any. Both need a time limit, and the types reject `recordAll` together with `endsTrial: true`.
211
+
212
+ Named choices record what an answer means, so a counterbalanced key mapping stays in the experiment and out of the analysis:
213
+
214
+ ```tsx
215
+ timeline: ({ group }) => [
216
+ Stimulus.trial('face', {
217
+ content: <img src={face} />,
218
+ response: {
219
+ choices: {
220
+ happy: { key: group === 'a' ? 'f' : 'j' },
221
+ sad: { key: group === 'a' ? 'j' : 'f' },
222
+ },
223
+ },
224
+ }),
225
+ ],
226
+ ```
227
+
228
+ Both groups record `happy` and `sad`, and the key next to it. Two answers that share a key or a button stop the experiment when it loads, since only one of them could be given.
229
+
230
+ The content can also answer by itself. As a function, it receives `respond`, which ends the trial with whatever it is given as the `response`; an object is written to the CSV as JSON. The function is rendered as a component, so it can use hooks. `Canvas` draws within the content, sized like a CanvasBlock, and its `onClick` gives a click's position in the drawing's coordinates:
231
+
232
+ ```tsx
233
+ Stimulus.trial('location', {
234
+ content: ({ respond }) => (
235
+ <Canvas width={600} height={400} draw={drawScene} onClick={(x, y) => respond({ x, y })} />
236
+ ),
237
+ }),
238
+ ```
239
+
240
+ The simulation cannot guess such answers, so a Stimulus whose content answers needs a simulator of its own (see [Overriding simulators on a trial](#overriding-simulators-on-a-trial)):
241
+
242
+ ```tsx
243
+ .simulators({ respond: () => ({ value: { response: { x: 300, y: 200 }, reactionTimeMs: 900 } }) })
244
+ ```
245
+
246
+ A simulated answer is recorded as the browser would record it. Its `key` says how it was given, `null` for a button or the content's `respond`; left out, it is the answer's own key, so `{ response: 'happy', reactionTimeMs: 700 }` records the F of the example above. An answer the Stimulus does not take, or a key that gives another answer, stops the simulation with an error. For a trial that records every answer, `respond` is asked again after each, with the `answers` so far, until it gives none or one after the time limit; each answer has to come after the one before:
247
+
248
+ ```tsx
249
+ // a tap every 700 ms
250
+ .simulators({ respond: ({ answers }) => ({ value: { response: ' ', reactionTimeMs: (answers.length + 1) * 700 } }) })
251
+ ```
252
+
253
+ Times work as for slides (below): a reaction time runs from the frame with which the stimulus appeared to the moment the browser timestamped the key press or click, and a key pressed before the stimulus appeared does not count. The stimulus appears once the images in its content have loaded, so their loading time is not part of a reaction time or a display duration; an image that fails to load shows as broken. Background images in CSS and videos are not waited for. Rendering a page can take varying time, though, so fast sequences, such as a fixation cross, a 50 ms stimulus and a mask, belong in a CanvasBlock.
254
+
255
+ ### Timed slides
256
+
257
+ CanvasBlock shows a sequence of slides on a canvas within one trial, for tasks that need precise timing, such as a fixation cross, a briefly shown word and a key press. It draws each slide in an animation frame, with no React rendering between slides. Its timeline holds slides, and the same blocks as the experiment's timeline. A block holds either slides or trials, and the types keep each to the timelines of its kind:
258
+
259
+ ```tsx
260
+ import { CanvasBlock, ifBlock, type Slide } from '@adriansteffan/reactive';
261
+
262
+ const fixation: Slide = {
263
+ draw: (ctx, w, h) => ctx.fillText('+', w / 2, h / 2),
264
+ displayDurationMs: 500,
265
+ ignoreData: true,
266
+ };
267
+
268
+ const stimulus = (word: string): Slide => ({
269
+ draw: (ctx, w, h) => ctx.fillText(word, w / 2, h / 2),
270
+ displayDurationMs: 200,
271
+ response: { keys: ['f', 'j'], timeLimitMs: 2000 },
272
+ metadata: { word },
273
+ });
274
+
275
+ const wrongKey: Slide = { draw: (ctx, w, h) => ctx.fillText('Wrong key', w / 2, h / 2), displayDurationMs: 500 };
276
+
277
+ CanvasBlock.trial('main', {
278
+ timeline: words.map((word) => [
279
+ fixation,
280
+ stimulus(word),
281
+ ifBlock(({ slides }) => slides.at(-1)?.key !== 'f', [wrongKey]),
282
+ ]),
283
+ }).metadata({ condition: 'hard' }),
284
+ ```
285
+
286
+ | Slide field | Description |
287
+ |---|---|
288
+ | `draw(ctx, width, height)` | Draws the slide on a canvas cleared to white, with black as the fill color |
289
+ | `displayDurationMs` | How long the drawing stays visible |
290
+ | `response.keys` | The keys that count as a response, or `true` for any key (see below) |
291
+ | `response.choices` | Responses recorded by their names, each given by its `key`, as on a Stimulus |
292
+ | `response.click` | Takes a click on the canvas as a response |
293
+ | `response.timeLimitMs` | How long after the slide appears a response counts |
294
+ | `response.endsSlide` | Whether the first response ends the slide; `true` by default |
295
+ | `response.hidesDrawing` | Clears the drawing at the first response |
296
+ | `ignoreData` | Records no row for the slide |
297
+ | `metadata` | Extra values for the slide's row |
298
+
299
+ A slide with a `response` ends at the first response, unless `endsSlide` is `false`. Otherwise it ends when the response's time limit runs out, or, without one, when its display duration does; the drawing can disappear earlier while keys still count. A slide needs one of these ways to end, which the types check; an empty list of keys or choices, which they cannot see, stops the experiment during development and simulation. TypeScript explains a slide's mistakes best where it is declared as a `Slide`, like `fixation` above, rather than written inside the timeline.
300
+
301
+ Keys are named as the browser names them in `KeyboardEvent.key`: a letter, a digit or symbol, `' '` for the space bar, or a named key such as `'Enter'` or `'ArrowLeft'`, which editors suggest. Any other name the browser gives works as well, such as `'ö'` on a German keyboard. Keys count in any case, so caps lock does not matter and `'enter'` is `'Enter'`, and the slide's row records the key as the list names it. Text's and the RandomDotKinematogram's `allowedResponseKeys` work the same way.
302
+
303
+ A slide can also be a function of the timeline context, which runs once, when the slide starts. Inside a CanvasBlock, the context's `slides` holds the rows of the block's slides so far, while `data` holds the experiment's trials, as everywhere else. `updateStore` changes the store for the rest of the block, and the block's changes reach the experiment's store when it ends.
304
+
305
+ Each slide records a row with its `slideNumber`, which counts the slides the participant saw from 1, including those that record nothing; `startMs`, `endMs` and `durationMs`; and the `key` pressed and its `reactionTimeMs`, or `null` without a response. A slide with `choices` also records the `response`, the name of the choice the key gave, so that keys counterbalanced across participants are recorded by what they mean. A slide that takes clicks records where the click landed as `x` and `y`, in the coordinates `draw` uses, and its `key` is `null`. Clicks count by the same rules as keys: from the frame with which the slide appeared, judged at the next frame. In the canvas CSV, every slide is a row: its metadata is in `meta_` columns (`meta_word`), and the block's own metadata in `slideblock_meta_` columns (`slideblock_meta_condition`).
306
+
307
+ Times are taken from the frames the browser shows. A slide appears with the first frame after the one that draws it, and `startMs` is that frame's time; `endMs` is when the next frame takes it down. A reaction time runs from `startMs` to the moment the browser timestamped the key press, so the time the page needs to handle the key is not part of it, and a held key's repeats do not count. Durations are counted in frames: a slide is taken down on the frame nearest its duration when the screen's refresh rate is known, from `.collectRefreshRate()` on an earlier trial, and otherwise on the first frame at or after it.
308
+
309
+ | CanvasBlock prop | Description |
310
+ |---|---|
311
+ | `timeline` | The slides and blocks |
312
+ | `width`, `height` | The canvas's size: pixels as a number, a share of the screen as a percentage (`'80%'`), or a ratio of width to height (`'16:9'`), which sets this side from the other, or alone makes the largest canvas of that shape that fits the screen; the largest square that fits by default |
313
+ | `styleCanvas(ctx, width, height)` | Sets colors and fonts before each slide is drawn |
314
+ | `initCanvas(ctx, width, height)` | Runs once, after the canvas is set up |
315
+
316
+ `canvasCountdown(seconds)` returns slides that count down one second each and record nothing.
317
+
318
+ ### Params
319
+
320
+ Params are the experiment's inputs. They are declared once, read from the URL, and passed to `timeline`, which then becomes a function that runs once per participant:
321
+
322
+ ```tsx
323
+ export default defineExperiment({
324
+ params: {
325
+ group: {
326
+ values: ['vn', 'scenario'],
327
+ default: () => (Math.random() < 0.5 ? 'vn' : 'scenario'),
328
+ description: 'Which version of the study the participant sees',
329
+ },
330
+ rounds: { default: 3 },
331
+ },
332
+ timeline: ({ group, rounds }) => [
333
+ group === 'vn' ? visualNovel : vignette,
334
+ Array.from({ length: rounds }, (_, i) => Round.trial(`round_${i}`)),
335
+ ],
336
+ });
337
+ ```
338
+
339
+ * A param is read from the URL by its key (`?group=scenario&rounds=5`), otherwise its default is used. A default that is a function is called once per participant.
340
+ * With `values`, the param is typed as one of them (`'vn' | 'scenario'`), and its default, or what a default function returns, must be one of them too. Without `values`, the param takes the type of its default.
341
+ * Whatever sets a param, the URL, a simulated participant or a default function, a value of another type stops the experiment with an error: one outside `values`, text for a number, or anything but `true` or `false` for a switch. Only a default function without `values` declares no type, so its values are not checked.
342
+ * The resolved values are recorded in the data. Simulated participants can set them (see [Simulation](#simulation)).
343
+ * `timeline` may use any JavaScript, such as `shuffle` or loops. Its random draws are seeded per participant, and the seed (`buildSeed`) is recorded, so the exact timeline a participant saw can be rebuilt later.
344
+ * Params exist only inside `timeline`. Parts of the timeline in other files that need one become functions that take it, and components get it as a prop.
345
+ * Each param is a column of the session CSV, so a param cannot be named `sessionId`, `userAgent` or `buildSeed`, or start with `url_` or `session_`. The types reject these names, and so does the run.
346
+
347
+ ### Typed store
348
+
349
+ The store's shape can be declared once, anywhere in the project:
350
+
351
+ ```tsx
352
+ declare module '@adriansteffan/reactive' {
353
+ interface ExperimentStore {
354
+ bonus: number;
355
+ }
356
+ }
357
+ ```
358
+
359
+ The timeline context's `store`, the `updateStore` block, and the `store` and `updateStore` that components receive are then checked against it. Without a declaration, the store is untyped.
360
+
361
+ ### Custom components
362
+
363
+ `defineComponent` turns a React component into one that can be used in the timeline:
364
+
365
+ ```tsx
366
+ function ReactionView({ next, target }: BaseComponentProps<{ reactionTimeMs: number }> & { target: string }) {
367
+ ...
368
+ next({ reactionTimeMs });
369
+ }
370
+
371
+ export default defineComponent({
372
+ name: 'Reaction',
373
+ component: ReactionView,
374
+ csv: 'reactions', // optional, see Data Saving
375
+ simulate: ({ props, simulators, participant }) => { ... }, // optional, see Simulation
376
+ defaultSimulators: { ... }, // optional
377
+ });
378
+ ```
379
+
380
+ `BaseComponentProps<R>` gives the component `next`, which records what the trial measured, of type `R`, and moves on (only a type that allows `undefined` can be left out), along with `data`, `store`, `updateStore` and `name`, the trial's name. Only `name` and `component` are required. The name identifies the component in the data, since function names do not survive minification. A defined component is still an ordinary React component.
381
+
382
+ Write the component as a named function, as above, rather than inline in `defineComponent`: hot reloading then keeps the state of a trial that is on screen when its file changes.
383
+
384
+ A component that measures times takes them with `now()`, the clock of the rows' `startMs` and `endMs`. To match the built-in screens, `useTheme()` returns the experiment's theme, and `t(theme)` its Tailwind classes, such as `t(useTheme()).button` for a button that ends a screen and `.article` for a screen's text.
385
+
386
+ A component can declare params of its own, in the same format as the experiment's. The settings page lists them whenever the component is in the timeline, the URL can set them, and the component reads their values with `useParams(params)`, typed like the experiment's. Upload's `upload` and `download` switches work this way:
387
+
388
+ ```tsx
389
+ const params = {
390
+ showFeedback: { default: true, description: 'Show feedback after each response' },
391
+ } as const;
392
+
393
+ function ReactionView(...) {
394
+ const { showFeedback } = useParams(params); // boolean
395
+ ...
396
+ }
397
+
398
+ defineComponent({ name: 'Reaction', component: ReactionView, params });
399
+ ```
400
+
401
+ `as const` keeps the `values` of a param as a union of them, as `defineExperiment` does. A param that `useParams` reads but `defineComponent` does not declare would have no value, so it stops the experiment during development and simulation.
402
+
403
+ A component can check each of its trials when the experiment loads, with `check`. It gets the trial's `props` (`undefined` when they are computed during the run), the run's `params`, every trial of the timeline as `trials` with this one's `index`, and `production`, which is true in a production build. It returns what is wrong, if anything. Any message keeps the run from starting, and the settings screen shows it while you build a link. A check for something only the real link provides, such as a URL param, can leave development and simulation alone by returning nothing unless `production` is set:
404
+
405
+ ```tsx
406
+ defineComponent({
407
+ name: 'ProlificEnding',
408
+ …,
409
+ check: ({ props, params, trials, index, production }) => {
410
+ if (!trials.slice(0, index).some((trial) => trial.type === 'Upload')) {
411
+ return 'ProlificEnding ends the experiment, so an Upload has to come before it, or the data is never saved.';
412
+ }
413
+ if (production && props !== undefined && !props.prolificCode && !params.cc) {
414
+ return 'ProlificEnding has no completion code to show: set its prolificCode, or the cc param in the link.';
415
+ }
416
+ },
417
+ });
418
+ ```
419
+
420
+ This is ProlificEnding's own check. A ProlificEnding without an Upload before it stops the run everywhere, and in production, so does one without a completion code. The checks see the trials the run will show, so deselecting the Upload on the settings screen while keeping the ProlificEnding stops the run as well.
421
+
422
+ A component that talks to the experiment's server, such as a multiplayer game or a streamed API response, reaches the routes in `server.ts` at `getBackendUrl()`. That is `/backend` in the browser and the simulation's own server while simulating, so the component and its `simulate` can use the same call:
423
+
424
+ ```tsx
425
+ const response = await fetch(`${getBackendUrl()}/match`, { method: 'POST', body: JSON.stringify({ id }) });
426
+ ```
427
+
428
+ Simulated participants run at the same time against that one server, so they can also interact through it.
429
+
430
+ ### Hot reloading
431
+
432
+ Edits to the experiment or to its components keep the participant where they are: the timeline is rebuilt with the same params and seed, the trial on screen stays mounted with its state, and it receives its new props. An edit that removes the trial on screen falls back to the same position.
433
+
434
+ ### Settings page
435
+
436
+ `/settings` builds a link for a run. It lists the experiment's params, then the settings: the general ones (`dev`) and those of the components in the selected trials, by component. Below them come the trials, which follow the params entered above. The trials inside an `ifBlock` or `whileBlock` are listed under it, and unchecking a block unchecks all of them. The checked trials run, as does any trial that other param values add; the link lists the unchecked ones in `?excludeSubset=`, each by its name, or without one by its position (`4.2` for the second item of the fourth entry). A block whose items are all unchecked is left out with them. The settings follow which trials are checked, as they would in the run, so unchecking a trial drops the settings of components that only it uses. Custom params are recorded as text, in `url_` columns.
437
+
438
+ ### Dev panel
439
+
440
+ `?dev=true` adds a panel that shows the current trial's props, the store and all data recorded so far.
45
441
 
442
+ ### Turning features off
443
+
444
+ The settings page and the dev panel are available wherever the experiment runs, including a deployed study, which is often run through the settings page. A study that should not offer one of them can turn it off in the project's `.env.production`:
445
+
446
+ ```
447
+ PUBLIC_DISABLE_SETTINGS=TRUE
448
+ PUBLIC_DISABLE_DEV=TRUE
449
+ ```
46
450
 
47
451
 
48
452
  ## Simulation
@@ -51,35 +455,44 @@ Reactive includes a simulation system that lets you run experiments headlessly,
51
455
 
52
456
  ### Quick start
53
457
 
54
- Define your participant generator in `Experiment.tsx`:
458
+ Define your participant generator in `defineExperiment`:
55
459
 
56
460
  ```tsx
57
- export const simulationConfig = {
58
- seed: 42, // optional: makes simulations fully reproducible
59
- participants: () => sampleParticipants('sobol', 10, {
60
- needForCognition: { distribution: 'normal', mean: 3.5, sd: 0.8 },
61
- }),
62
- };
461
+ export default defineExperiment({
462
+ simulation: {
463
+ seed: 42, // optional: makes simulations fully reproducible
464
+ createParticipants: () => sampleParticipants('sobol', 10, {
465
+ needForCognition: { distribution: 'normal', mean: 3.5, sd: 0.8 },
466
+ }),
467
+ },
468
+ timeline: [ ... ],
469
+ });
63
470
  ```
64
471
 
65
- ### Simulating URL params (e.g. Prolific IDs)
472
+ ### Setting params and URL params
66
473
 
67
- To produce simulated runs whose session CSV matches real Prolific runs (so payout/analysis scripts work on both), attach a `urlParams` object to each simulated participant. These flow into the metadata trial as unregistered params and land in the CSV with a `url_` prefix.
474
+ A simulated participant's `params` set the experiment's params, for example to split participants evenly between groups:
475
+
476
+ ```tsx
477
+ createParticipants: () => sampleParticipants('sobol', 10, { ... }).map((p, i) => ({
478
+ ...p,
479
+ params: { group: i % 2 ? 'vn' : 'scenario' },
480
+ })),
481
+ ```
482
+
483
+ To produce simulated runs whose session CSV matches real Prolific runs (so payout/analysis scripts work on both), attach a `urlParams` object to each simulated participant. These are recorded like URL params the experiment does not declare, and land in the CSV with a `url_` prefix.
68
484
 
69
485
  ```tsx
70
486
  import { sampleParticipants, prolificId } from '@adriansteffan/reactive';
71
487
 
72
- export const simulationConfig = {
73
- seed: 42,
74
- participants: () => sampleParticipants('sobol', 10, {
75
- needForCognition: { distribution: 'normal', mean: 3.5, sd: 0.8 },
76
- }).map((p) => ({
77
- ...p,
78
- urlParams: {
79
- PROLIFIC_PID: prolificId(),
80
- },
81
- })),
82
- };
488
+ createParticipants: () => sampleParticipants('sobol', 10, {
489
+ needForCognition: { distribution: 'normal', mean: 3.5, sd: 0.8 },
490
+ }).map((p) => ({
491
+ ...p,
492
+ urlParams: {
493
+ PROLIFIC_PID: prolificId(),
494
+ },
495
+ })),
83
496
  ```
84
497
 
85
498
  Available generators: `prolificId()` (24-char alphanumeric), `alphanumericId(length)` for custom lengths.
@@ -87,98 +500,101 @@ Available generators: `prolificId()` (24-char alphanumeric), `alphanumericId(len
87
500
  Run the simulation:
88
501
 
89
502
  ```
90
- npm run simulate
503
+ bun run simulate
91
504
  ```
92
505
 
93
- This starts the backend, simulates all participants through the experiment, uploads data via the real backend (just like real participants would), and shuts down.
506
+ This starts the backend on a free port, simulates all participants through the experiment, uploads data via the real backend (just like real participants would), and shuts down.
94
507
 
95
508
  ### How it works
96
509
 
97
- Each built-in component (Text, Quest, CanvasBlock, Upload, etc.) registers a **simulate function** and **default simulators**. The simulate function contains the trial logic. The simulators are replaceable decision functions that model participant behavior at each interaction point.
510
+ Each built-in component (Text, Quest, CanvasBlock, Upload, etc.) has a **simulate function** and **default simulators**. The simulate function contains the trial logic. The simulators are replaceable decision functions that model participant behavior at each interaction point.
98
511
 
99
512
  For example, Quest's simulate function iterates through questions and calls `simulators.answerQuestion()` for each one. The default `answerQuestion` picks random valid answers. You can override it to model specific participant behavior.
100
513
 
514
+ Simulators and simulate functions take a single object, so each one names only what it uses. A simulator receives `props` and `participant`, plus whatever the simulate function passes along (`question`, for `answerQuestion`). It returns `{ value, participant }`: its decision as `value`, and the new `participant` if the participant changed; without one, the participant stays as it was.
515
+
101
516
  ### Overriding simulators on a trial
102
517
 
103
- Add a `simulators` property to any timeline item to override specific decision functions:
518
+ `.simulators()` replaces specific decision functions for one trial:
104
519
 
105
520
  ```tsx
106
- {
107
- type: 'PlainInput',
108
- props: { content: <p>What is your name?</p> },
109
- simulators: {
110
- respond: (_trialProps, participant) => ({
111
- value: participant.nickname,
112
- participantState: participant,
113
- }),
521
+ PlainInput.trial('name', { content: <p>What is your name?</p> }).simulators({
522
+ respond: ({ participant }) => ({ value: participant.nickname }),
523
+ }),
524
+ ```
525
+
526
+ The override is merged with the component's defaults — you only need to specify the decision functions you want to change. A replacement returns what the function it replaces returns, which the types check, and may leave out `participant` to keep the participant as it was. A CanvasBlock's `respondToSlide` also receives the `slide`, so one replacement can decide each slide's response.
527
+
528
+ A replacement also receives the component's default simulator, to build on what it decides. It runs the default with the input passed to it:
529
+
530
+ ```tsx
531
+ Text.trial('intro').simulators({
532
+ // The default response, only twice as slow
533
+ respond: (input, defaultSimulator) => {
534
+ const result = defaultSimulator(input);
535
+ return { ...result, value: { ...result.value, reactionTimeMs: result.value.reactionTimeMs * 2 } };
114
536
  },
115
- }
537
+ }),
116
538
  ```
117
539
 
118
- The override is merged with the registered defaults — you only need to specify the decision functions you want to change.
540
+ Spreading `result` keeps the participant the default returned. To run the default for a different participant, pass it one: `defaultSimulator({ ...input, participant: changed })`.
119
541
 
120
542
  ### Custom components
121
543
 
122
- Register a simulation for your custom components using `registerSimulation`:
544
+ Give your custom components a simulation in `defineComponent`:
123
545
 
124
546
  ```tsx
125
- registerSimulation('MyTrial',
547
+ export default defineComponent({
548
+ name: 'MyTrial',
549
+ component: MyTrialView,
126
550
  // Simulate function: uses shared trial logic + decision functions
127
- (trialProps, experimentState, simulators, participant) => {
128
- const choice = simulators.decide(trialProps, participant);
129
- return { responseData: { choice: choice.value }, participantState: choice.participantState };
551
+ simulate: ({ props, simulators, participant }) => {
552
+ const result = simulators.decide({ props, participant });
553
+ return { recorded: { choice: result.value }, participant: result.participant };
130
554
  },
131
555
  // Default simulators: one per decision point
132
- {
133
- decide: (_trialProps, participant) => ({
134
- value: 'default_choice',
135
- participantState: participant,
136
- }),
556
+ defaultSimulators: {
557
+ decide: () => ({ value: 'default_choice' }),
137
558
  },
138
- );
559
+ });
139
560
  ```
140
561
 
141
- The simulate function orchestrates the trial logic. The decision functions are the parts where a human would interact — these are what users override to model different participant behaviors.
142
-
143
- ### Hybrid mode
144
-
145
- During development, you can auto-advance simulated trials while manually interacting with others. Add `?hybridSimulation=true` to the URL during development:
562
+ A simulate function receives the trial's `props`, the `participant` and the `simulators`, along with the timeline context (`data` and `store`), so a simulation can depend on earlier answers, read with `getAll` and `getLatest`. When it calls several simulators in a row, it passes each one the participant the previous one returned (`participant = result.participant ?? participant`), and returns the last one as its `participant`.
146
563
 
147
- ```
148
- http://localhost:5173?hybridSimulation=true
149
- ```
150
-
151
- Trials with `simulators` or `simulate: true` defined on them will auto-advance. Trials without them render normally for human interaction.
564
+ A component that records nothing, such as a screen of instructions, can use `simulate: noopSimulate`, which moves on at once.
152
565
 
153
- Hybrid mode is enabled by default during development. For production, set `VITE_DISABLE_HYBRID_SIMULATION=true` to disable it regardless of URL parameters.
566
+ The simulate function orchestrates the trial logic. The decision functions are the parts where a human would interact — these are what users override to model different participant behaviors. What it returns as `recorded` is checked against the type the component records with `next`. A component without `simulate` works normally, but a simulation stops at its trials with an error.
154
567
 
155
568
  ### Reproducible simulations
156
569
 
157
570
  Add `seed` to your simulation config to make runs fully reproducible:
158
571
 
159
572
  ```tsx
160
- export const simulationConfig = {
573
+ simulation: {
161
574
  seed: 42,
162
- participants: () => sampleParticipants('sobol', 100, {
575
+ createParticipants: () => sampleParticipants('sobol', 100, {
163
576
  needForCognition: { distribution: 'normal', mean: 3.5, sd: 0.8 },
164
577
  agreeableness: { distribution: 'normal', mean: 3.0, sd: 1.0 },
165
578
  age: { distribution: 'uniform', min: 18, max: 65 },
166
579
  }),
167
- };
580
+ },
168
581
  ```
169
582
 
170
- Each simulated participant runs in its own subprocess. The `seed` controls two separate phases:
583
+ Participants are simulated in one process, several at a time (`concurrency`, by default the number of CPU cores). The `seed` controls two separate phases:
171
584
 
172
- - **Participant generation**: The `participants` factory function is called with the base `seed` (same for all workers), so every worker generates the same participant list.
173
- - **Simulation behavior**: Module-level randomness (group assignment, trial order) and simulator callbacks are seeded with `seed + participantIndex`, so each participant gets a unique but reproducible random stream.
585
+ - **Participant generation**: `createParticipants` is called with the base `seed` when the simulation starts, so the list is the same in every run, and stays the same while you edit the experiment.
586
+ - **Simulation behavior**: Each participant draws from its own random stream, seeded with the `seed` and the participant's index. The streams of the participant list and of every participant never overlap, also between runs with different seeds, so many seeded runs give independent datasets. The stream covers params' defaults, the timeline's own random draws (trial order) and simulator callbacks. The stream follows the participant across waits, so participants simulated at the same time draw exactly as if each ran alone.
174
587
 
175
- Without `seed`, simulations use random entropy and will vary between runs. When seeded, `Math.random()` is also patched to use the seeded PRNG, so existing code and third-party libraries are automatically reproducible.
588
+ Without `seed`, simulations use random entropy and will vary between runs. `Math.random()` is also routed through these streams, so existing code and third-party libraries are automatically reproducible.
176
589
 
177
- **Note:** Do not close over module-level random values into the factory function — module-level code runs with a per-worker seed, so captured values would differ between workers. Keep all participant generation logic inside the factory.
590
+ `createParticipants` produces the participants when the simulation starts. That way anything drawn at random in it is drawn from the seed, and a fixed list works the same way:
178
591
 
179
592
  ```tsx
180
- // Good: all randomness is inside the factory
181
- participants: () => {
593
+ // Fixed
594
+ createParticipants: () => [{ id: 1, speed: 2 }, { id: 2, speed: 0.5 }],
595
+
596
+ // Drawn
597
+ createParticipants: () => {
182
598
  const base = sampleParticipants('random', 100, {
183
599
  openness: { distribution: 'normal', mean: 3.5, sd: 0.8 },
184
600
  });
@@ -188,16 +604,14 @@ participants: () => {
188
604
  id: i,
189
605
  }));
190
606
  },
191
-
192
- // Bad: module-level value captured into factory
193
- const noise = normal(0, 1); // different per worker!
194
- participants: () => [{ trait: noise }],
195
607
  ```
196
608
 
609
+ **Note:** Random numbers drawn at the top of a file, outside params' defaults and the timeline function, are drawn once and shared by every simulated participant, while real participants each get their own. The simulation warns when the experiment draws random numbers while it loads.
610
+
197
611
  To model distinct populations, combine them inside the factory:
198
612
 
199
613
  ```tsx
200
- participants: () => {
614
+ createParticipants: () => {
201
615
  const smokers = sampleParticipants('sobol', 50, {
202
616
  alertness: { distribution: 'normal', mean: 2.8, sd: 0.7 },
203
617
  }).map((p) => ({ ...p, smoker: true }));
@@ -212,157 +626,176 @@ participants: () => {
212
626
 
213
627
  ### Built-in simulator decision functions
214
628
 
215
- | Component | Decision functions | Default behavior |
216
- |---|---|---|
217
- | Text | `respond` | Click button, random reaction time |
218
- | PlainInput | `respond` | Returns `'simulated_input'` |
219
- | Quest | `answerQuestion` | Random valid answer per question type |
220
- | CanvasBlock | `respondToSlide` | Random key from `allowedKeys`, random RT |
221
- | Tutorial | `respondToSlide` | Advances through slides, no interaction data |
222
- | RandomDotKinematogram | `respond` | Random key from `validKeys`, random RT (may timeout) |
223
- | Upload | *(none)* | Builds CSVs and POSTs to backend |
224
- | StoreUI | *(none)* | Uses field default values |
225
- | CheckDevice | *(none)* | Returns simulated device info |
226
- | VoiceRecording | `respondTTS`, `respondBase64` | Platform TTS with default text; falls back to dummy sine tone |
227
- | EnterFullscreen, ExitFullscreen, MicrophoneCheck, ProlificEnding, RequestFilePermission | *(none)* | No-op, advances immediately |
629
+ | Component | Decision functions | Its `value` | Default behavior |
630
+ |---|---|---|---|
631
+ | Text | `respond` | `{ key, reactionTimeMs }` | Click button, random reaction time |
632
+ | Stimulus | `respond`, also given the `answers` so far | `{ response, reactionTimeMs }`, and optionally the `key` that gave it | One random answer from `choices`, `keys` and `buttons`, random RT; a Stimulus whose content answers needs its own |
633
+ | PlainInput | `respond` | the text entered | Returns `'simulated_input'` |
634
+ | Quest | `answerQuestion`, also given `question` | `{ answer, durationMs }` | Random valid answer per question type |
635
+ | CanvasBlock | `respondToSlide`, also given `slide` | `{ key, reactionTimeMs }`, or `{ x, y, reactionTimeMs }` for a click | Random key from the slide's `keys` and `choices`, or a random point on a slide that takes clicks, random RT; it counts under the same rules as a real response |
636
+ | Tutorial | `respondToSlide`, also given `slideIndex` | `{ data, durationMs }` | Advances through slides, no interaction data |
637
+ | RandomDotKinematogram | `respond` | `{ key, reactionTimeMs }` | Random key from `allowedResponseKeys`, random RT (may timeout) |
638
+ | Upload | *(none)* | | Builds CSVs and POSTs to backend |
639
+ | StoreUI | *(none)* | | Uses field default values |
640
+ | CheckDevice | *(none)* | | Returns simulated device info |
641
+ | VoiceRecording | `respondTTS`, `respondBase64` | the text to speak, or the audio as base64 | Platform TTS with default text; falls back to dummy sine tone |
642
+ | fullscreenBlock's screen, MicrophoneCheck, ProlificEnding, RequestFilePermission | *(none)* | | No-op, advances immediately |
228
643
 
229
644
 
230
645
  ## Data Saving
231
646
 
232
- Reactive automatically builds CSV files from experiment data using a registry-based system. Each component type registers a default CSV target, and the Upload component discovers these at the end of the experiment.
647
+ Reactive automatically builds CSV files from experiment data: the session CSV, with one row per participant, and files with rows per trial. The Upload component builds the files at the end of the experiment.
233
648
 
234
649
  ### How it works
235
650
 
236
- Each component type registers where its data should go via `registerFlattener`:
651
+ Each component declares where its data should go, with the `csv` and `session` options of `defineComponent`:
237
652
 
238
653
  ```tsx
239
- registerFlattener('PlainInput', 'session'); // merge into session CSV
240
- registerFlattener('CanvasBlock', 'canvas', flattenFn); // own CSV with custom flattener
241
- registerFlattener('ProlificEnding', null); // no CSV output
654
+ defineComponent({ name: 'PlainInput', component: PlainInput, session: true }); // columns in the session CSV
655
+ defineComponent({ name: 'CanvasBlock', component: CanvasBlock, csv: { canvas: flatten } }); // own CSV with custom flattener
656
+ defineComponent({ name: 'ProlificEnding', component: ProlificEnding, csv: null }); // no CSV output
242
657
  ```
243
658
 
244
- Built-in components come pre-registered. The Upload component produces CSVs automatically with no props needed:
659
+ Without `csv`, a component's rows go to a CSV named after the component in lowercase, unless it sets `session`. Built-in components come configured. The Upload component produces CSVs automatically with no props needed:
245
660
 
246
661
  ```tsx
247
- { name: 'upload', type: 'Upload' }
662
+ Upload.trial('upload')
248
663
  ```
249
664
 
250
665
  ### Built-in defaults
251
666
 
252
667
  | Component | Default CSV | Notes |
253
668
  |---|---|---|
254
- | PlainInput, Quest, CheckDevice, EnterFullscreen, ExitFullscreen, MicrophoneCheck | `session` | Merged into single session row, namespaced by trial name |
669
+ | PlainInput, Quest, CheckDevice, VoiceRecording | session | Columns in the single session row, namespaced by trial name |
255
670
  | Text | `text` | One row per Text component |
671
+ | Stimulus | `stimulus` | One row per Stimulus |
256
672
  | CanvasBlock | `canvas` | One row per slide, with built-in flattener |
257
673
  | StoreUI | `storeui` | One row per StoreUI occurrence |
258
- | Tutorial | `session` | Merged into session row |
259
674
  | RandomDotKinematogram | `rdk` | One row per RDK trial |
260
- | ProlificEnding, Upload, RequestFilePermission | *(none)* | No CSV output |
675
+ | fullscreenBlock's screen, MicrophoneCheck, ProlificEnding, Upload, RequestFilePermission, Tutorial | *(none)* | No CSV output |
261
676
 
262
677
  ### Output files
263
678
 
264
679
  For a session `abc123`, the Upload component produces:
265
- - `abc123.raw.json` — full raw data
266
- - `session.abc123.{timestamp}.csv` — one row with params, userAgent, and all session-level trial data namespaced by trial name (e.g. `nickname_value`, `devicecheck_browser`)
680
+ - `abc123.raw.json` — all the data, as `{ "session": …, "trials": [ … ] }`, with recordings replaced by the names of their files
681
+ - `session.abc123.{timestamp}.csv` — one row with `sessionId`, `userAgent`, `buildSeed`, the params, URL params that nothing declares (`url_…`), the Upload's `sessionData` (`session_…`), and all session-level trial data namespaced by trial name (e.g. `nickname_value`, `devicecheck_browser`)
267
682
  - `canvas.abc123.{timestamp}.csv` — multi-row CSV from CanvasBlock trials
268
683
  - One CSV per additional group (text, storeui, or any custom group)
269
684
 
270
- ### Per-item CSV override
685
+ ### Per-trial CSV files
271
686
 
272
- Override the default target on any timeline item:
687
+ A trial can rename its component's CSV file:
273
688
 
274
689
  ```tsx
275
- { name: 'practice', type: 'CanvasBlock', csv: 'practice', ... } // separate from main canvas
276
- { name: 'main', type: 'CanvasBlock', ... } // uses default 'canvas'
690
+ CanvasBlock.trial('practice', { timeline: practiceSlides }).csv('practice'), // separate from main canvas
691
+ CanvasBlock.trial('main', { timeline: mainSlides }), // uses default 'canvas'
277
692
  ```
278
693
 
279
- Route a trial to multiple CSVs with an array:
694
+ The file keeps its flattener under the new name, so the practice CSV also has one row per slide. Flatteners belong to the component, and a trial never needs one of its own.
695
+
696
+ A component that only fills the session row has no file to rename, so a name gives its trial one, next to its session columns:
280
697
 
281
698
  ```tsx
282
- { name: 'survey', type: 'Quest', csv: ['session', 'survey'], ... } // both session row and own file
699
+ Quest.trial('survey', { surveyJson }).csv('survey'), // both session row and own file
283
700
  ```
284
701
 
285
- ### Adding session-level data
286
-
287
- Use `sessionData` on Upload to inject extra fields into the session CSV:
702
+ For a component with several files (see [Multi-CSV components](#multi-csv-components)), the trial names the files it renames, and the others stay as they are; `null` leaves one out:
288
703
 
289
704
  ```tsx
290
- // Static
291
- {
292
- type: 'Upload',
293
- props: {
294
- sessionData: { group: 'control', experimentVersion: 2 },
295
- },
296
- }
297
-
298
- // Dynamic (computed from store/data)
299
- {
300
- type: 'Upload',
301
- props: (data, store) => ({
302
- sessionData: { group: store.assignedGroup, condition: store.condition },
303
- }),
304
- }
705
+ SportsGame.trial('practice').csv({ sports_actions: 'practice_actions', sports_matches: null }),
305
706
  ```
306
707
 
307
- ### Custom flatteners
708
+ A name of a file the component does not write, or a plain name for a component with several files, stops the experiment when it loads. So does the name `session`, which belongs to the session CSV; `.session(true)` puts a trial's columns there.
308
709
 
309
- Register a flattener for custom components to control how `responseData` becomes CSV rows:
710
+ ### Session columns
711
+
712
+ The session CSV holds a single row per participant. A component with `session: true` gives each of its trials columns there, one per field of the response, prefixed with the trial's name (`nickname_value`). A function picks the columns instead, and returns them as one object:
310
713
 
311
714
  ```tsx
312
- registerFlattener('MyGame', 'games', (item) => {
313
- return item.responseData.moves.map((move) => ({
314
- moveType: move.type,
315
- score: move.score,
316
- }));
715
+ defineComponent({
716
+ name: 'SportsGame',
717
+ component: SportsGame,
718
+ session: (item) => ({ finalScore: item.recorded.score }), // game_finalScore for a trial named 'game'
719
+ csv: { sports_actions: (item) => flattenActions(item.recorded) },
317
720
  });
318
721
  ```
319
722
 
320
- Each row automatically gets standard trial fields prefixed with `trial_` (`trial_index`, `trial_name`, `trial_start`, etc.) plus any metadata from the timeline item. The flattener output overwrites these if keys collide.
723
+ A trial's `.session(true)` puts its columns in the session CSV although its component does not, and `.session(false)` keeps them out. Something recorded as a list has no fields to spread into columns, so it needs a function: the types reject `true` for it, and a list that reaches the session CSV from a component that does not declare its response stops the experiment during development and simulation.
321
724
 
322
- ### Array flattener
725
+ ### Adding session-level data
323
726
 
324
- For components whose `responseData` is an array of objects (like CanvasBlock), use the built-in `arrayFlattener` instead of writing your own. Each array element becomes a CSV row with a `block` column set to the trial name:
727
+ Use `sessionData` on Upload to inject extra fields into the session CSV. Their columns are prefixed with `session_` (`session_experimentVersion`), so they never take the place of a param:
325
728
 
326
729
  ```tsx
327
- import { registerFlattener, arrayFlattener } from '@adriansteffan/reactive';
730
+ // Static
731
+ Upload.trial('upload', { sessionData: { experimentVersion: 2 } }),
732
+
733
+ // Dynamic (computed from the store or earlier results)
734
+ Upload.trial('upload', ({ store, data }) => ({
735
+ sessionData: { bonus: store.bonus, choice: Story.getLatest(data, 'story').recorded.choice },
736
+ })),
737
+ ```
738
+
739
+ ### Custom flatteners
328
740
 
329
- registerFlattener('MyBlockTrial', 'blocks', arrayFlattener);
741
+ Without a flattener, each trial is one row, with the fields it recorded as columns, and a trial that recorded a list is one row per item, like CanvasBlock's slides. To give a trial rows of another shape, map the file to a function that returns its row, or a list of rows. The function reads the trial's row with the component's response, so TypeScript checks what it reads:
742
+
743
+ ```tsx
744
+ defineComponent({
745
+ name: 'MyGame',
746
+ component: MyGame,
747
+ csv: {
748
+ games: (item) =>
749
+ item.recorded.moves.map((move) => ({
750
+ moveType: move.type,
751
+ score: move.score,
752
+ })),
753
+ },
754
+ });
330
755
  ```
331
756
 
757
+ Each row automatically gets standard trial fields prefixed with `trial_` (`trial_name`, `trial_trialNumber`, `trial_startMs`, etc.) plus the trial's metadata prefixed with `meta_`.
758
+
759
+ Column names starting with `trial_`, `meta_`, `response_`, `url_`, `session_` or `slideblock_meta_` belong to the library. A field of a response or of a flattener's output whose name starts with one of them gets `response_` in front (`meta_score` becomes `response_meta_score`), so it can never take the place of a column the library writes.
760
+
332
761
  ### Multi-CSV components
333
762
 
334
- Call `registerFlattener` multiple times for one component to produce multiple CSV files:
763
+ Map several files to their flatteners to produce multiple CSV files from one component, and a file to `true` for one row per trial:
335
764
 
336
765
  ```tsx
337
- registerFlattener('SportsGame', 'sports_actions', (item) => flattenActions(item.responseData));
338
- registerFlattener('SportsGame', 'sports_players', (item) => flattenPlayers(item.responseData));
339
- registerFlattener('SportsGame', 'sports_matches', (item) => flattenMatches(item.responseData));
766
+ defineComponent({
767
+ name: 'SportsGame',
768
+ component: SportsGame,
769
+ csv: {
770
+ sports_actions: (item) => flattenActions(item.recorded),
771
+ sports_players: (item) => flattenPlayers(item.recorded),
772
+ sports_matches: (item) => flattenMatches(item.recorded),
773
+ },
774
+ });
340
775
  ```
341
776
 
342
777
  ### Upload props
343
778
 
344
779
  | Prop | Type | Default | Description |
345
780
  |---|---|---|---|
346
- | `sessionID` | `string` | random UUID | Custom session identifier used in filenames and folder names |
347
- | `sessionData` | `Record<string, any>` | — | Extra key-value pairs added to the session CSV row |
348
- | `generateFiles` | `(sessionID, data, store) => FileUpload[]` | — | Produce custom files alongside auto-generated CSVs |
349
- | `uploadRaw` | `boolean` | `true` | Include raw JSON dump of all trial data |
350
- | `autoUpload` | `boolean` | `false` | Upload immediately on mount instead of showing a submit button |
781
+ | `sessionId` | `string` | random UUID | Custom session identifier used in filenames and folder names |
782
+ | `sessionData` | `Record<string, any>` | — | Extra key-value pairs added to the session CSV row, as `session_` columns |
783
+ | `generateFiles` | `({ sessionId, data, store }) => FileUpload[]` | — | Produce custom files alongside auto-generated CSVs |
784
+ | `uploadRaw` | `boolean` | `true` | Include the raw JSON of all the data |
785
+ | `autoUpload` | `boolean` | `true` | Upload as soon as the screen appears; `false` shows a submit button first |
786
+ | `buttonText` | `string` | `'Submit Data'` | The submit button, with `autoUpload: false` |
787
+ | `retryButtonText` | `string` | `'Try Again'` | The button shown after a failed upload |
788
+ | `parentFolder` | `string` | — | A folder for the session's folder to go into, on the server (`data/<parentFolder>/<sessionId>`) and in the apps |
351
789
 
352
790
  ### Metadata
353
791
 
354
- Add `metadata` to timeline items to include extra columns in every CSV row that trial produces:
792
+ Add metadata to a trial to include extra columns in every CSV row it produces:
355
793
 
356
794
  ```tsx
357
- {
358
- name: 'block1',
359
- type: 'CanvasBlock',
360
- metadata: { difficulty: 'hard', block: 2 },
361
- props: { ... },
362
- }
795
+ RandomDotKinematogram.trial('rdk1', { coherence: 0.5 }).metadata({ difficulty: 'hard', block: 2 }),
363
796
  ```
364
797
 
365
- For session-level items, metadata is namespaced by trial name (e.g. `block1_difficulty`). For non-session items, metadata columns appear unprefixed.
798
+ In the data, metadata sits under the row's `metadata`, apart from the trial's own fields and what it `recorded`, so their names can never collide. In the CSVs, its columns are prefixed with `meta_` (`meta_difficulty`), and for session-level trials also with the trial name (`rdk1_meta_difficulty`). A CanvasBlock's metadata is in `slideblock_meta_` columns instead, next to its slides' `meta_` columns (see [Timed slides](#timed-slides)). An object value becomes a single column holding its JSON. Metadata can also be a function of the timeline context.
366
799
 
367
800
 
368
801
  ## Utilities
@@ -370,34 +803,32 @@ For session-level items, metadata is namespaced by trial name (e.g. `block1_diff
370
803
  Reactive exports helper functions for common experiment-building tasks.
371
804
 
372
805
  ```tsx
373
- import { shuffle, sample, chunk, pipe, normal, uniform, poisson, seedDistributions, sobol, halton, sampleParticipants } from '@adriansteffan/reactive';
806
+ import { shuffle, sample, chunk, normal, uniform, poisson, sobol, halton, sampleParticipants } from '@adriansteffan/reactive';
374
807
  ```
375
808
 
376
809
  ### Array functions
377
810
 
378
- These are available both as standalone functions and as Array prototype extensions (after calling `registerArrayExtensions()`).
811
+ These are available both as standalone functions and as methods of every array.
379
812
 
380
813
  | Function | Signature | Description |
381
814
  |---|---|---|
382
815
  | `shuffle` | `shuffle(arr)` | Returns a new array with elements randomly reordered (Fisher-Yates) |
383
816
  | `sample` | `sample(arr, n?)` | Returns `n` random elements from the array (default 1, with replacement) |
384
- | `chunk` | `chunk(arr, n)` | Splits the array into `n` roughly equal chunks |
385
- | `pipe` | `pipe(arr, fn)` | Passes the array to `fn` and returns the result |
817
+ | `chunk` | `chunk(arr, n)` | Splits the array into chunks of `n` items; the last chunk holds what is left |
818
+ | `mean` | `mean(arr)` | The mean of an array of numbers, or 0 for an empty one |
819
+ | `sum` | `sum(arr)` | The sum of an array of numbers |
820
+ | `.pipe` | `arr.pipe(fn)` | Passes the array to `fn` and returns the result (method only) |
386
821
 
387
- As prototype methods:
822
+ As methods, they chain:
388
823
 
389
824
  ```tsx
390
- import { registerArrayExtensions } from '@adriansteffan/reactive';
391
- registerArrayExtensions();
392
-
393
- const trials = [1, 2, 3, 4, 5].shuffle();
394
- const picked = trials.sample(2);
395
- const blocks = trials.chunk(3);
825
+ const blocks = [1, 2, 3, 4, 5, 6].shuffle().chunk(3); // two blocks of three, in random order
826
+ const practice = blocks.pipe(([first]) => first.sample(2));
396
827
  ```
397
828
 
398
829
  ### Distributions
399
830
 
400
- Random number generators backed by [@stdlib](https://github.com/stdlib-js/stdlib), useful for writing realistic simulations.
831
+ Random number generators, useful for writing realistic simulations.
401
832
 
402
833
  | Function | Signature | Description |
403
834
  |---|---|---|
@@ -405,20 +836,7 @@ Random number generators backed by [@stdlib](https://github.com/stdlib-js/stdlib
405
836
  | `normal` | `normal(mu, sigma)` | Sample from a normal (Gaussian) distribution with mean `mu` and standard deviation `sigma` |
406
837
  | `poisson` | `poisson(lambda)` | Sample from a Poisson distribution with rate `lambda` |
407
838
 
408
- All built-in simulation functions use these distributions internally.
409
-
410
- #### Global seeding
411
-
412
- Call `seedDistributions` to seed all three generators from a single seed, making simulation runs fully reproducible:
413
-
414
- ```tsx
415
- import { seedDistributions } from '@adriansteffan/reactive';
416
-
417
- seedDistributions(42);
418
- // All subsequent calls to normal(), uniform(), poisson() produce the same sequence
419
- ```
420
-
421
- Without seeding, the generators use random entropy (non-reproducible, same as `Math.random()`).
839
+ All built-in simulation functions use these distributions internally. During a simulation they draw from the participant's seeded stream (see [Reproducible simulations](#reproducible-simulations)).
422
840
 
423
841
  ### Quasi-Monte Carlo sequences
424
842
 
@@ -441,7 +859,7 @@ Each dimension spec is one of:
441
859
  | Integer | `{ distribution: 'integer', min, max }` | Uniform integer in `[min, max]` inclusive |
442
860
  | Discrete | `{ distribution: 'discrete', outcomes }` | Weighted categorical — `outcomes: [{ value, weight }, ...]` |
443
861
 
444
- For a single dimension, both return a flat `number[]`. For multiple dimensions, they return `number[][]`.
862
+ Both return one array of values per point, `number[][]`, also for a single dimension (`sobol(5, [spec]).map(([rt]) => rt)`).
445
863
 
446
864
  ```tsx
447
865
  import { sobol, halton } from '@adriansteffan/reactive';
@@ -481,9 +899,21 @@ const participants = sampleParticipants('sobol', 100, {
481
899
 
482
900
  The first argument is the sampling method: `'sobol'`, `'halton'`, or `'random'`.
483
901
 
902
+ A trait can correlate with the others, which it names in its `correlations`:
903
+
904
+ ```tsx
905
+ sampleParticipants('sobol', 100, {
906
+ needForCognition: { distribution: 'normal', mean: 3.5, sd: 0.8 },
907
+ openness: { distribution: 'normal', mean: 3.0, sd: 1.0, correlations: { needForCognition: 0.4 } },
908
+ age: { distribution: 'integer', min: 18, max: 65, correlations: { openness: -0.2 } },
909
+ });
910
+ ```
911
+
912
+ Each pair is given at one of its two traits, and pairs left out are uncorrelated. Normal traits get the correlation as given. Other distributions get a somewhat weaker one, since it applies to the normal scores they are made from: 0.5 between two uniform traits comes out at about 0.48, and coarse discrete traits lose more. Correlations that contradict each other, such as a and b at 0.9 and b and c at 0.9 but a and c at -0.9, stop with an error. Correlated samples stay as evenly spread as the Sobol and Halton sequences make them.
913
+
484
914
  ### Drift Diffusion Model (DDM)
485
915
 
486
- `simulateDDMTrial` simulates a single 2AFC trial. Parameters can be fixed numbers or distributions (`{ type: 'normal', mean, sd }` / `{ type: 'uniform', min, max }`) for inter-trial variability.
916
+ `simulateDDMTrial` simulates a single 2AFC trial. Parameters can be fixed numbers or distributions (`{ distribution: 'normal', mean, sd }` / `{ distribution: 'uniform', min, max }`) for inter-trial variability.
487
917
 
488
918
  ```tsx
489
919
  import { simulateDDMTrial, mapDDMChoice } from '@adriansteffan/reactive';
@@ -493,13 +923,13 @@ const result = simulateDDMTrial({
493
923
  boundaries: 0.1, // symmetric: +0.1 / -0.1
494
924
  startingPoint: 0,
495
925
  noiseLevel: 0.003,
496
- sensoryDelay: { type: 'uniform', min: 100, max: 200 },
497
- motorDelay: { type: 'uniform', min: 50, max: 100 },
498
- timeLimit: 2000,
499
- stimOffset: 1000,
926
+ sensoryDelayMs: { distribution: 'uniform', min: 100, max: 200 },
927
+ motorDelayMs: { distribution: 'uniform', min: 50, max: 100 },
928
+ timeLimitMs: 2000,
929
+ stimOffsetMs: 1000,
500
930
  postStimStrategy: { type: 'continue' },
501
931
  });
502
- // → { choice: 0 | 1 | null, rt, finalEvidence, isContaminated }
932
+ // → { choice: 0 | 1 | null, reactionTimeMs, finalEvidence, isContaminated }
503
933
 
504
934
  // Map DDM choice to a key press (null-safe)
505
935
  mapDDMChoice(result.choice, ['f', 'j'], 'f');
@@ -507,12 +937,12 @@ mapDDMChoice(result.choice, ['f', 'j'], 'f');
507
937
 
508
938
  `boundaries` can also be a `[lower, upper]` tuple for asymmetric boundaries. `choice` is `null` on timeout.
509
939
 
510
- After the stimulus disappears (`stimOffset`), the `postStimStrategy` takes over:
940
+ After the stimulus disappears (`stimOffsetMs`), the `postStimStrategy` takes over:
511
941
  - `{ type: 'continue' }` — keep accumulating (optional `residualDrift`, `noiseMultiplier`)
512
942
  - `{ type: 'snapshot' }` — forced choice by boundary proximity
513
- - `{ type: 'collapse', collapseDef: { rate, delay? } }` — boundaries shrink, drift drops to 0
943
+ - `{ type: 'collapse', collapseDef: { rate, delayMs? } }` — boundaries shrink, drift drops to 0
514
944
 
515
- Boundaries can also collapse during viewing via `stimulusCollapse: { rate, delay? }`.
945
+ Boundaries can also collapse during viewing via `stimulusCollapse: { rate, delayMs? }`.
516
946
 
517
947
  The RDK component uses this as its default simulator with parameters from Ratcliff & McKoon (2008), converted to ms time steps.
518
948
 
@@ -524,50 +954,47 @@ The RDK component uses this as its default simulator with parameters from Ratcli
524
954
  Place early in your timeline to let participants select and test their microphone:
525
955
 
526
956
  ```tsx
527
- { type: 'MicrophoneCheck' }
957
+ MicrophoneCheck.trial()
528
958
  ```
529
959
 
530
- The selected device ID is stored automatically and used by all subsequent recording components.
960
+ The selected device ID is stored automatically and used by all subsequent recording components. A recording component of your own reads it with `useAudioDeviceId()`.
531
961
 
532
962
  ### VoiceRecording
533
963
 
534
964
  A standalone trial where participants record their voice. The "Continue" button only appears after a recording is made.
535
965
 
536
966
  ```tsx
537
- {
538
- type: 'VoiceRecording',
539
- props: {
540
- content: <p>Please describe what you saw.</p>,
541
- },
542
- }
967
+ VoiceRecording.trial('description', {
968
+ content: <p>Please describe what you saw.</p>,
969
+ })
543
970
  ```
544
971
 
545
972
  With minimum duration enforcement; shows a warning when paused if the recording is too short:
546
973
 
547
974
  ```tsx
548
- {
549
- type: 'VoiceRecording',
550
- props: {
551
- content: <p>Please describe your decision in detail.</p>,
552
- minDuration: 15000,
553
- },
554
- }
975
+ VoiceRecording.trial('decision', {
976
+ content: <p>Please describe your decision in detail.</p>,
977
+ minDurationMs: 15000,
978
+ })
555
979
  ```
556
980
 
557
- When `minDuration` is set, only pause and discard buttons are shown. When not set, pause, stop, and discard buttons appear with playback after stopping.
981
+ When `minDurationMs` is set, only pause and discard buttons are shown. When not set, pause, stop, and discard buttons appear with playback after stopping.
558
982
 
559
983
  | Prop | Default | Description |
560
984
  |---|---|---|
561
985
  | `content` | — | Prompt text/JSX |
562
- | `buttonText` | `'Continue'` / `'Save & Continue'` (with minDuration) | Button text |
986
+ | `buttonText` | `'Continue'` / `'Save & Continue'` (with minDurationMs) | Button text |
563
987
  | `shortButtonText` | `'Continue without improving'` | Button text when recording is too short |
564
- | `shortRecordingWarning` | Generic message | Warning text for short recordings |
565
- | `minDuration` | — | Minimum recording duration in ms |
988
+ | `shortRecordingContent` | Generic message | Shown when the recording is shorter than `minDurationMs` |
989
+ | `minDurationMs` | — | Minimum recording duration |
990
+ | `silenceWarningMs`, `silenceWarningContent` | — | After this many milliseconds of silence, a banner with this content asks the participant to speak up |
566
991
  | `showVisualizer` | `true` | Show volume level meter |
567
992
  | `eagerUpload` | `true` | Upload audio immediately after recording |
568
993
  | `animate` | `false` | Fade-in animation |
569
994
 
570
- Audio recordings are automatically extracted as separate `.webm` files during upload and eagerly uploaded to reduce final upload size. The trial `name` is used in the filename.
995
+ Audio recordings are automatically extracted as separate `.webm` files during upload and eagerly uploaded to reduce final upload size. Each file is named after its trial's name and number (`audio_story_4.webm`), and the trial's row records the name as `audioFile`.
996
+
997
+ To transcribe the recordings with Whisper in Docker, add the transcription setup to the project with `bunx @adriansteffan/reactive add transcription`; the project's README explains how to run it.
571
998
 
572
999
 
573
1000
  ## LLM Integration
@@ -613,40 +1040,180 @@ const parsed = JSON.parse(result);
613
1040
  | `apiKey` | `string` | API key |
614
1041
  | `baseUrl` | `string?` | Override the API endpoint |
615
1042
 
616
- Requires `import 'dotenv/config'` at the top of `simulate.ts` to load `.env` files. Add `.reactive-cache/` to your `.gitignore`.
1043
+ Keep API keys in `.env.development`, which Bun loads automatically on your computer and the project's `.gitignore` excludes. Add `.reactive-cache/` to your `.gitignore`.
1044
+
1045
+
1046
+ ## Android and iOS apps
1047
+
1048
+ Experiments can be packaged as Android or iOS apps with [Capacitor](https://capacitorjs.com/). The apps store data on the device instead of uploading it. To add this to a project, run in its root directory:
1049
+
1050
+ ```
1051
+ bunx @adriansteffan/reactive native
1052
+ ```
1053
+
1054
+ This installs the Capacitor packages, creates `capacitor.config.ts` and imports `@adriansteffan/reactive/native` in `src/main.tsx`. It makes sense to develop with the web version and only switch to the device emulators for device-specific features and testing before packaging. `getPlatform()` returns `'native'` in the apps and `'web'` in the browser.
1055
+
1056
+ ### Android
1057
+
1058
+ #### Setup
1059
+
1060
+ To build and test an Android app containing your experiment, you will need an installation of
1061
+ [Android Studio](https://developer.android.com/studio) and [Java 21 or later](https://www.oracle.com/de/java/technologies/downloads/)
1062
+
1063
+ To set up the android project, run this command in the root directory:
1064
+ ```
1065
+ bunx cap add android
1066
+ ```
1067
+
1068
+ Next, find the [path to your local android sdk](https://stackoverflow.com/questions/25176594/android-sdk-location) and create a `local.properties` file in the `android` folder with the following content:
1069
+
1070
+ ```
1071
+ sdk.dir=SDK_PATH_HERE
1072
+ ```
1073
+
1074
+ If you want to enable file saving for Android versions <= 10, add these lines to the `android/app/main/AndroidManifest.xml`:
1075
+
1076
+ ```
1077
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android"> // this line is already there
1078
+
1079
+ <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
1080
+ <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
1081
+
1082
+ <!-- For Android 10+ (API 29+) -->
1083
+ <uses-permission android:name="android.permission.READ_MEDIA_IMAGES" />
1084
+ <uses-permission android:name="android.permission.READ_MEDIA_VIDEO" />
1085
+ <uses-permission android:name="android.permission.READ_MEDIA_AUDIO" />
1086
+
1087
+ <application
1088
+ android:requestLegacyExternalStorage="true" // add this to the application tag
1089
+ ```
1090
+
1091
+ For more information, refer to the [Capacitor documentation on Android](https://capacitorjs.com/docs/android)
1092
+
1093
+
1094
+ #### Running
1095
+
1096
+ Whenever you have made changes to the code and want to run it on the Android emulator, run:
1097
+ ```
1098
+ bun run build
1099
+ bunx cap sync
1100
+ bunx cap run android
1101
+ ```
1102
+
1103
+ #### Packaging
1104
+
1105
+ From the root directory, build the app with the settings in `.env.production` and open it:
1106
+
1107
+ ```
1108
+ bun run build:production
1109
+ bunx cap sync
1110
+ bunx cap open android
1111
+ ```
1112
+
1113
+ . Wait for Android Studio to install the project dependencies and then run Build > Generate APKs and Bundles > Generate APKs. Once your build is finished, there will be a popup guiding you to the location of the bundle's app that you can transfer to your Android device.
1114
+
1115
+ #### Where is my data stored?
1116
+
1117
+ In the "Internal Storage" section of the file browser, you will find a "Documents" folder that will contain subfolders with your data as soon as the first participant has finished the experiment.
1118
+
1119
+ ### iOS
1120
+
1121
+ #### Setup
1122
+
1123
+ To build an iOS app containing your experiment, you will need a machine running MacOS and an installation of [XCode](https://apps.apple.com/us/app/xcode/id497799835). Furthermore, you will need to install [CocoaPods](https://cocoapods.org/), which is most easily installed with [Homebrew](https://brew.sh/).
1124
+
1125
+ To set up the iOS project, run
1126
+
1127
+ ```
1128
+ bunx cap add ios
1129
+ ```
1130
+
1131
+ Then, go to `ios > App > App > Info.plist`
1132
+
1133
+ And add these lines next to the other keys:
1134
+
1135
+ ```
1136
+ <key>UIFileSharingEnabled</key>
1137
+ <string>YES</string>
1138
+ <key>LSSupportsOpeningDocumentsInPlace</key>
1139
+ <string>YES</string>
1140
+ ```
1141
+
1142
+ For more information, refer to the [Capacitor documentation on iOS](https://capacitorjs.com/docs/ios)
1143
+
1144
+ #### Running
1145
+
1146
+ Whenever you have made changes to the code and want to run it on the iOS emulator, run:
1147
+
1148
+ ```
1149
+ bun run build
1150
+ bunx cap sync
1151
+ bunx cap run ios
1152
+ ```
1153
+
1154
+ #### Packaging
1155
+
1156
+ Packaging iOS apps is quite an undertaking, which is why the process is not overly streamlined/documented yet. The best way to get your experiment on an iOS device right now is to build it with the settings in `.env.production` and run
1157
+
1158
+ ```
1159
+ bun run build:production
1160
+ bunx cap sync
1161
+ bunx cap run ios
1162
+ ```
1163
+
1164
+ which will open the finished project in XCode. From there, follow a guide on how to sign, bundle and install your app/experiment.
1165
+
1166
+ #### Where is my data stored?
1167
+
1168
+ After the first participant is run, a folder with the name of your app will appear under "My iPhone/iPad" in the files app, which contains your data.
617
1169
 
618
1170
 
619
1171
  ## Development
620
1172
 
1173
+ The package is published as TypeScript source, so there is no build step. `sideEffects` in `package.json` lists the files that do something when they are imported: the CSS, the array methods and the native integration. A project's production build leaves out every other file it does not use, so a new file that has to run on import belongs on that list.
621
1174
 
622
- Run this to in the root of the repo to build the project locally (also needs to be run after every change):
1175
+ Check it with
623
1176
 
624
1177
  ```
625
- npm run build
1178
+ bun test
1179
+ bun run typecheck
1180
+ bun run lint
626
1181
  ```
627
1182
 
628
- Then create a global link (only needs to run once during setup);
1183
+ To try changes in a project, create a global link once:
629
1184
  ```
630
- npm link
1185
+ bun link
631
1186
  ```
632
1187
 
633
1188
  Then set up a local testing project (run from the parent directory so it's created as a sibling):
634
1189
 
635
1190
  ```
636
1191
  cd ..
637
- node reactive/bin/setup.js
1192
+ bun reactive/bin/setup.js
638
1193
  cd <project-name>
639
1194
  npm pkg set dependencies.@adriansteffan/reactive="*"
640
- npm i && npm i --prefix backend
641
- npm link @adriansteffan/reactive
1195
+ bun install
1196
+ bun link @adriansteffan/reactive
642
1197
  ```
643
1198
 
1199
+ The linked library would otherwise use React from its own `node_modules`, and two copies of React break hooks. So point the library's React at the project's, from the root of this repo:
1200
+
1201
+ ```
1202
+ rm -rf node_modules/react node_modules/react-dom
1203
+ ln -s ../../<project-name>/node_modules/react node_modules/react
1204
+ ln -s ../../<project-name>/node_modules/react-dom node_modules/react-dom
1205
+ ```
1206
+
1207
+ Changes to the library then show up in the project's dev server immediately. Running `bun install` in this repo replaces the links with regular copies, so repeat these three commands afterwards.
1208
+
644
1209
 
645
1210
  Manually publishing to npm (until we figure out a better ci/cd process):
646
1211
  ```
647
1212
  npm publish
648
1213
  ```
649
1214
 
1215
+ Use npm 11 or later, older versions leave `template/.gitignore` out of the package.
1216
+
650
1217
 
651
1218
  ## Authors
652
1219