@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
@@ -0,0 +1,373 @@
1
+ import React, { createElement, useCallback, useLayoutEffect, useRef } from 'react';
2
+ import { type BaseComponentProps, defineComponent } from '../core/component';
3
+ import { t, useTheme } from '../runner/theme';
4
+ import { type CanvasSize, type Draw, prepareCanvas } from '../utils/canvas';
5
+ import { uniform } from '../utils/distributions';
6
+ import { keyAnswer, type ResponseKey, responseKey } from '../utils/keys';
7
+ import { halfFrameMs } from '../utils/time';
8
+
9
+ /** An answer the participant gives by a key, a button, or both. */
10
+ export type StimulusChoice = { key: ResponseKey; button?: string } | { key?: ResponseKey; button: string };
11
+
12
+ interface StimulusResponseFields {
13
+ /** Keys that answer, each recorded as itself, letters in either case; `true` for any key. */
14
+ keys?: readonly ResponseKey[] | true;
15
+ /** Buttons that answer, each recorded as its text. */
16
+ buttons?: readonly string[];
17
+ /** Answers recorded by their names, each given by a key, a button, or both. */
18
+ choices?: Record<string, StimulusChoice>;
19
+ /** How long after the stimulus appears an answer counts. The trial ends then, if no answer has ended it. */
20
+ timeLimitMs?: number;
21
+ /** Whether the first answer ends the trial. Defaults to `true`; otherwise the trial ends at its time limit. */
22
+ endsTrial?: boolean;
23
+ /** Records every answer until the time limit, as `responses`, so the trial lasts until then. */
24
+ recordAll?: boolean;
25
+ }
26
+
27
+ /** The answers a stimulus takes, how long they count, and whether the first ends the trial. */
28
+ // Recording every answer keeps the trial going, so it cannot also end at the first
29
+ export type StimulusResponse = StimulusResponseFields & ({ recordAll?: false } | { recordAll: true; endsTrial?: false });
30
+
31
+ /** What a content function receives: `respond` ends the trial with an answer of the content's own. */
32
+ export interface StimulusControls {
33
+ respond: (response: unknown) => void;
34
+ }
35
+
36
+ /** An answer, the key that gave it, and how long after the stimulus appeared it came. */
37
+ export type StimulusAnswer = { response: unknown; key: string | null; reactionTimeMs: number };
38
+
39
+ /**
40
+ * The first answer, the key that gave it, and how long after the stimulus appeared it came, all null
41
+ * without an answer; with `recordAll`, every answer as `responses`.
42
+ */
43
+ export type StimulusData = {
44
+ response: unknown;
45
+ key: string | null;
46
+ reactionTimeMs: number | null;
47
+ responses?: StimulusAnswer[];
48
+ };
49
+
50
+ type StimulusFields = {
51
+ /** The stimulus: React, or a function of `{ respond }` for content that answers by itself. */
52
+ content?: React.ReactNode | ((controls: StimulusControls) => React.ReactNode);
53
+ response?: StimulusResponse;
54
+ /**
55
+ * How long the content stays visible. Unless the response has a time limit, the trial ends then.
56
+ * Without one, the trial needs another way to end: a time limit, or keys, buttons, choices or
57
+ * content that respond, whose first answer ends it.
58
+ */
59
+ displayDurationMs?: number;
60
+ className?: string;
61
+ containerClass?: string;
62
+ };
63
+
64
+ // An answer ends the trial, unless endsTrial is false or the trial records every answer
65
+ type EndsAtAnswer = { endsTrial?: true; recordAll?: false };
66
+
67
+ // A trial needs a way to end: an answer, a time limit, a display duration, or content that responds.
68
+ // TypeScript explains a mismatch against the last of these, so a trial without an end reads as
69
+ // missing its displayDurationMs, whose documentation lists the other ways.
70
+ type StimulusEnd =
71
+ | { content: (controls: StimulusControls) => React.ReactNode; response?: EndsAtAnswer }
72
+ | {
73
+ response:
74
+ | { timeLimitMs: number }
75
+ | (EndsAtAnswer &
76
+ ({ keys: readonly ResponseKey[] | true } | { buttons: readonly string[] } | { choices: Record<string, StimulusChoice> }));
77
+ }
78
+ | { displayDurationMs: number };
79
+
80
+ export type StimulusProps = StimulusFields & StimulusEnd & BaseComponentProps<StimulusData>;
81
+
82
+ type Answer = { response: string; key?: ResponseKey; button?: string };
83
+
84
+ // The declared answers: the named choices, then the keys and buttons, which are recorded as themselves
85
+ function answersOf(response: StimulusResponse | undefined): Answer[] {
86
+ const keys = response?.keys === true ? [] : (response?.keys ?? []);
87
+ return [
88
+ ...Object.entries(response?.choices ?? {}).map(([name, choice]) => ({ response: name, ...choice })),
89
+ ...keys.map((key) => ({ response: key, key })),
90
+ ...(response?.buttons ?? []).map((button) => ({ response: button, button })),
91
+ ];
92
+ }
93
+
94
+ // What a trial records from its answers: the first, and with recordAll, every one
95
+ function recordOf(answers: StimulusAnswer[], recordAll: boolean): StimulusData {
96
+ const first = answers[0] ?? { response: null, key: null, reactionTimeMs: null };
97
+ return recordAll ? { ...first, responses: answers } : { ...first };
98
+ }
99
+
100
+ // A simulated answer as the browser would record it. The simulator's key says how the answer was
101
+ // given: by a key, judged as a press is, or with null, by a button or the content's respond. Left
102
+ // out, it is the declared answer's key, or with `keys: true`, the answer itself.
103
+ function recordAnswer(
104
+ props: Pick<StimulusFields, 'content' | 'response'>,
105
+ response: unknown,
106
+ given: string | null | undefined,
107
+ ): { response: unknown; key: string | null } {
108
+ const declared = answersOf(props.response).find((answer) => answer.response === response);
109
+ const anyKey = props.response?.keys === true && typeof response === 'string';
110
+ const key = given !== undefined ? given : declared ? (declared.key ?? null) : anyKey ? response : null;
111
+ if (key !== null) {
112
+ const answer = keyAnswer(props.response, key);
113
+ if (answer && typeof response === 'string' && responseKey([answer.response], response) !== undefined) return answer;
114
+ throw new Error(
115
+ `A simulated participant answered ${JSON.stringify(response)} with the key '${key}', which ${answer ? `gives '${answer.response}'` : 'does not answer the Stimulus'}.`,
116
+ );
117
+ }
118
+ if (declared?.button !== undefined || typeof props.content === 'function') return { response, key: null };
119
+ throw new Error(
120
+ declared
121
+ ? `A simulated participant gave the Stimulus's answer '${declared.response}' without its key, but it has no button.`
122
+ : `A simulated participant answered ${JSON.stringify(response)}, which the Stimulus does not take. Its answers are ${answersOf(props.response).map((answer) => `'${answer.response}'`).join(', ') || 'none'}.`,
123
+ );
124
+ }
125
+
126
+ function Stimulus({ content, response, displayDurationMs, className = '', containerClass, next, store }: StimulusProps) {
127
+ const th = t(useTheme());
128
+ // The content and its buttons, hidden until the images in the content can show
129
+ const stageRef = useRef<HTMLDivElement>(null);
130
+ const contentRef = useRef<HTMLDivElement>(null);
131
+ // Set while the trial runs; key presses, buttons and the content answer through it
132
+ const answerRef = useRef<(response: unknown, key: string | null, timeStamp: number) => void>(() => {});
133
+ const respond = useCallback((value: unknown) => answerRef.current(value, null, performance.now()), []);
134
+
135
+ const refreshRate = store.__screenRefreshRate;
136
+ // A layout effect starts the clock before the browser paints the stimulus, like a CanvasBlock's draw
137
+ useLayoutEffect(() => {
138
+ const timeoutMs = response?.timeLimitMs ?? displayDurationMs ?? Number.POSITIVE_INFINITY;
139
+ const recordAll = response?.recordAll === true;
140
+ const endsAtAnswer = response?.endsTrial !== false && !recordAll;
141
+ const answers: StimulusAnswer[] = [];
142
+ const halfFrame = halfFrameMs(refreshRate);
143
+ // The frame that paints the stimulus, and the next one, with which it appears
144
+ let paintedAt: number | undefined;
145
+ let onset: number | undefined;
146
+ let done = false;
147
+ let frameId = 0;
148
+
149
+ const end = () => {
150
+ done = true;
151
+ cancelAnimationFrame(frameId);
152
+ next(recordOf(answers, recordAll));
153
+ };
154
+ answerRef.current = (value, key, timeStamp) => {
155
+ const reactionTimeMs = Math.round(Math.max(0, timeStamp - (onset ?? timeStamp)));
156
+ // Only the first answer counts, unless the trial records every answer
157
+ if (done || reactionTimeMs >= timeoutMs || (answers.length > 0 && !recordAll)) return;
158
+ answers.push({ response: value, key, reactionTimeMs });
159
+ if (endsAtAnswer) end();
160
+ };
161
+
162
+ const frame = (timestamp: number) => {
163
+ if (paintedAt === undefined) {
164
+ // Shown in a frame callback, so this frame is the one that paints it
165
+ if (stageRef.current) stageRef.current.style.visibility = 'visible';
166
+ paintedAt = timestamp;
167
+ } else {
168
+ onset ??= timestamp;
169
+ // Half a frame more ends the trial on the frame nearest its time
170
+ const elapsed = timestamp - paintedAt + halfFrame;
171
+ if (elapsed >= timeoutMs) {
172
+ end();
173
+ return;
174
+ }
175
+ if (contentRef.current && elapsed >= (displayDurationMs ?? Number.POSITIVE_INFINITY)) {
176
+ contentRef.current.style.visibility = 'hidden';
177
+ }
178
+ }
179
+ frameId = requestAnimationFrame(frame);
180
+ };
181
+
182
+ const onKeyDown = (event: KeyboardEvent) => {
183
+ // A held key repeats, and a key pressed before the stimulus appeared does not count
184
+ if (event.repeat || onset === undefined || event.timeStamp < onset) return;
185
+ const answer = keyAnswer(response, event.key);
186
+ if (!answer) return;
187
+ event.preventDefault();
188
+ answerRef.current(answer.response, answer.key, event.timeStamp);
189
+ };
190
+
191
+ window.addEventListener('keydown', onKeyDown);
192
+ // The clock starts once every image has loaded and decoded, so their loading time is not part
193
+ // of a reaction time; an image that fails to load shows as broken instead of holding up the trial
194
+ const images = Array.from(stageRef.current?.querySelectorAll('img') ?? []);
195
+ Promise.all(images.map((image) => image.decode().catch(() => undefined))).then(() => {
196
+ if (!done) frameId = requestAnimationFrame(frame);
197
+ });
198
+ return () => {
199
+ done = true;
200
+ window.removeEventListener('keydown', onKeyDown);
201
+ cancelAnimationFrame(frameId);
202
+ };
203
+ }, [next, response, displayDurationMs, refreshRate]);
204
+
205
+ const buttons = answersOf(response).filter((answer) => answer.button !== undefined);
206
+
207
+ return (
208
+ <div className={`min-h-screen flex items-center justify-center px-4 py-20 ${th.text} ${containerClass ?? th.containerBg}`}>
209
+ <div ref={stageRef} className='flex flex-col items-center gap-12' style={{ visibility: 'hidden' }}>
210
+ <div ref={contentRef} className={className}>
211
+ {/* A function is rendered as a component, so that it can use hooks */}
212
+ {typeof content === 'function' ? createElement(content, { respond }) : content}
213
+ </div>
214
+ {buttons.length > 0 && (
215
+ <div className='flex flex-wrap justify-center gap-4'>
216
+ {buttons.map((answer) => (
217
+ <button
218
+ key={answer.response}
219
+ type='button'
220
+ tabIndex={-1}
221
+ // Keys answer through their own handler, never by pressing a focused button
222
+ onKeyDown={(event) => {
223
+ if (event.key === ' ' || event.key === 'Enter') event.preventDefault();
224
+ }}
225
+ onClick={(event) => answerRef.current(answer.response, null, event.timeStamp)}
226
+ className={th.button}
227
+ >
228
+ {answer.button}
229
+ </button>
230
+ ))}
231
+ </div>
232
+ )}
233
+ </div>
234
+ </div>
235
+ );
236
+ }
237
+
238
+ /**
239
+ * A canvas in a Stimulus's content, which `draw` paints when the stimulus appears and again whenever
240
+ * `draw` changes. Its size works as a CanvasBlock's does.
241
+ */
242
+ export function Canvas({
243
+ draw,
244
+ width,
245
+ height,
246
+ onClick,
247
+ className,
248
+ }: {
249
+ draw: Draw;
250
+ width?: CanvasSize;
251
+ height?: CanvasSize;
252
+ /** Receives where the participant clicked, in the coordinates that `draw` uses. */
253
+ onClick?: (x: number, y: number) => void;
254
+ className?: string;
255
+ }) {
256
+ const canvasRef = useRef<HTMLCanvasElement>(null);
257
+
258
+ // Drawn before the browser paints, so the drawing appears with the rest of the stimulus
259
+ useLayoutEffect(() => {
260
+ const prepared = canvasRef.current && prepareCanvas(canvasRef.current, width, height);
261
+ if (!prepared) return;
262
+ // A mistake in drawing code leaves the canvas incomplete instead of stopping the experiment
263
+ try {
264
+ draw(prepared.ctx, prepared.size.width, prepared.size.height);
265
+ } catch (error) {
266
+ console.error('Drawing on the canvas failed:', error);
267
+ }
268
+ }, [draw, width, height]);
269
+
270
+ return (
271
+ <canvas
272
+ ref={canvasRef}
273
+ className={className}
274
+ onClick={
275
+ onClick &&
276
+ ((event) => {
277
+ const bounds = event.currentTarget.getBoundingClientRect();
278
+ onClick(event.clientX - bounds.left, event.clientY - bounds.top);
279
+ })
280
+ }
281
+ />
282
+ );
283
+ }
284
+
285
+ /**
286
+ * What a Stimulus's `respond` simulator decides: the answer and its reaction time, or nulls for none.
287
+ * The key says how the answer was given, null for a button; left out, it is the answer's own.
288
+ */
289
+ type StimulusDecision = { value: { response: unknown; key?: string | null; reactionTimeMs: number | null } };
290
+
291
+ export default defineComponent({
292
+ name: 'Stimulus',
293
+ component: Stimulus,
294
+ check: ({ props }) => {
295
+ if (props === undefined) return undefined;
296
+ const answers = answersOf(props.response);
297
+ const endsAtAnswer = props.response?.endsTrial !== false && props.response?.recordAll !== true;
298
+ const ends =
299
+ (endsAtAnswer && (answers.length > 0 || props.response?.keys === true || typeof props.content === 'function')) ||
300
+ props.response?.timeLimitMs !== undefined ||
301
+ props.displayDurationMs !== undefined;
302
+ if (!ends) {
303
+ return 'A Stimulus would never end. Give it a displayDurationMs, or a response with a timeLimitMs, or with keys, buttons or choices whose first answer ends it.';
304
+ }
305
+ // Keys count in any case, so two that differ only in case are the same key
306
+ const givenBy = new Map<string, string>();
307
+ for (const answer of answers) {
308
+ for (const way of [answer.key && `key '${answer.key.toLowerCase()}'`, answer.button && `button '${answer.button}'`]) {
309
+ if (!way) continue;
310
+ const other = givenBy.get(way);
311
+ if (other !== undefined) {
312
+ return `The Stimulus's answers '${other}' and '${answer.response}' share the ${way}, so only one of them can be given.`;
313
+ }
314
+ givenBy.set(way, answer.response);
315
+ }
316
+ }
317
+ return undefined;
318
+ },
319
+ // A trial that records every answer has a CSV row for each, or one without an answer
320
+ csv: {
321
+ stimulus: (row) => {
322
+ const { responses, ...first } = row.recorded;
323
+ return responses && responses.length > 0 ? responses : first;
324
+ },
325
+ },
326
+ simulate: ({ props, simulators, participant }) => {
327
+ const timeoutMs = props.response?.timeLimitMs ?? props.displayDurationMs ?? Number.POSITIVE_INFINITY;
328
+ const recordAll = props.response?.recordAll === true;
329
+ const endsAtAnswer = props.response?.endsTrial !== false && !recordAll;
330
+ const answers: StimulusAnswer[] = [];
331
+ // One answer after another, under the browser's rules: an answer counts within the trial's
332
+ // time, and with recordAll, each after the one before
333
+ do {
334
+ const result = simulators.respond({ props, participant, answers });
335
+ participant = result.participant ?? participant;
336
+ const { response, key, reactionTimeMs } = result.value;
337
+ if (response === null || reactionTimeMs === null || reactionTimeMs >= timeoutMs) break;
338
+ const previous = answers.at(-1);
339
+ if (previous && reactionTimeMs <= previous.reactionTimeMs) {
340
+ throw new Error(
341
+ `A simulated participant answered a Stimulus at ${reactionTimeMs} ms, which is not after the answer before at ${previous.reactionTimeMs} ms.`,
342
+ );
343
+ }
344
+ answers.push({ ...recordAnswer(props, response, key), reactionTimeMs });
345
+ } while (recordAll);
346
+
347
+ const durationMs = endsAtAnswer && answers.length > 0 ? answers[0].reactionTimeMs : timeoutMs;
348
+ if (durationMs === Number.POSITIVE_INFINITY) {
349
+ throw new Error('A simulated participant gave no answer to a Stimulus that only an answer ends.');
350
+ }
351
+ return { recorded: recordOf(answers, recordAll), participant, durationMs };
352
+ },
353
+ defaultSimulators: {
354
+ // One answer: a trial that records every answer gets no second
355
+ respond: ({ props, answers: given }): StimulusDecision => {
356
+ if (given.length > 0) return { value: { response: null, reactionTimeMs: null } };
357
+ const answers = answersOf(props.response);
358
+ if (answers.length > 0) {
359
+ const answer = answers[Math.floor(uniform(0, answers.length))];
360
+ return { value: { response: answer.response, reactionTimeMs: Math.round(uniform(300, 1500)) } };
361
+ }
362
+ if (props.response?.keys === true) {
363
+ return { value: { response: ' ', reactionTimeMs: Math.round(uniform(300, 1500)) } };
364
+ }
365
+ if (typeof props.content === 'function') {
366
+ throw new Error(
367
+ "A Stimulus whose content answers through respond needs a simulator of its own, since the simulation cannot guess its answers. Give the trial one with .simulators({ respond: ({ participant }) => ({ value: { response, reactionTimeMs } }) }).",
368
+ );
369
+ }
370
+ return { value: { response: null, reactionTimeMs: null } };
371
+ },
372
+ },
373
+ });