@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.
- package/README.md +796 -229
- package/bin/add.js +56 -0
- package/bin/deploy.js +48 -0
- package/bin/download.js +28 -0
- package/bin/ghsetup.js +21 -0
- package/bin/native.js +81 -0
- package/bin/setup.js +11 -17
- package/bin/study-deploy.js +60 -0
- package/bin/undeploy.js +15 -0
- package/extras/transcription/compose.yaml +32 -0
- package/{template → extras}/transcription/transcribe.py +4 -9
- package/package.json +62 -64
- package/src/bun-env.d.ts +1 -0
- package/src/bun-plugin.ts +22 -0
- package/src/components/canvasblock.tsx +209 -537
- package/src/components/checkdevice.tsx +64 -84
- package/src/components/fullscreenblock.tsx +130 -0
- package/src/components/icons.tsx +50 -0
- package/src/components/index.ts +9 -11
- package/src/components/microphonecheck.tsx +76 -38
- package/src/components/plaininput.tsx +48 -41
- package/src/components/prolificending.tsx +64 -28
- package/src/components/quest.tsx +89 -87
- package/src/components/{randomdotkinetogram.tsx → randomdotkinematogram.tsx} +205 -267
- package/src/components/{voicerecorder.tsx → recorder.tsx} +81 -106
- package/src/components/requestfilepermission.tsx +63 -0
- package/src/components/stimulus.tsx +373 -0
- package/src/components/storeui.tsx +94 -148
- package/src/components/text.tsx +61 -59
- package/src/components/tutorial.tsx +45 -47
- package/src/components/upload.tsx +133 -309
- package/src/components/voicerecording.tsx +90 -94
- package/src/core/backend.ts +20 -0
- package/src/core/bytecode.ts +178 -0
- package/src/core/columns.ts +50 -0
- package/src/core/component.ts +238 -0
- package/src/core/development.ts +32 -0
- package/src/core/experiment.ts +263 -0
- package/src/core/files.ts +291 -0
- package/src/core/params.ts +166 -0
- package/src/core/platform.ts +29 -0
- package/src/core/rows.ts +106 -0
- package/src/core/simulation.ts +158 -0
- package/src/core/slides.ts +178 -0
- package/src/core/store.ts +22 -0
- package/src/core/timeline.ts +399 -0
- package/src/fonts/AtkinsonHyperlegible-Bold.woff2 +0 -0
- package/src/fonts/AtkinsonHyperlegible-BoldItalic.woff2 +0 -0
- package/src/fonts/AtkinsonHyperlegible-Italic.woff2 +0 -0
- package/src/fonts/AtkinsonHyperlegible-Regular.woff2 +0 -0
- package/src/index.css +5 -7
- package/src/mod.tsx +31 -17
- package/src/native.ts +127 -0
- package/src/quest.ts +2 -0
- package/src/runner/contexts.ts +35 -0
- package/src/runner/devpanel.tsx +68 -0
- package/src/runner/experimentrunner.tsx +210 -0
- package/src/runner/fullscreenguard.tsx +93 -0
- package/src/runner/paraminput.tsx +86 -0
- package/src/runner/progressbar.tsx +20 -0
- package/src/runner/settingsscreen.tsx +517 -0
- package/src/{utils → runner}/theme.ts +9 -8
- package/src/server.ts +93 -0
- package/src/tutorial.ts +3 -0
- package/src/utils/array.ts +30 -62
- package/src/utils/canvas.ts +66 -0
- package/src/utils/ddm.ts +47 -70
- package/src/utils/distributions.ts +352 -61
- package/src/utils/fullscreen.ts +38 -0
- package/src/utils/ids.ts +11 -0
- package/src/utils/keys.ts +46 -0
- package/src/utils/llm.ts +15 -15
- package/src/utils/time.ts +12 -0
- package/src/utils/tts.ts +24 -24
- package/template/.dockerignore +3 -1
- package/template/.env.example +5 -0
- package/template/.github/workflows/deploy.yml +25 -0
- package/template/.gitignore +14 -0
- package/template/Dockerfile +9 -14
- package/template/README.md +74 -214
- package/template/biome.json +34 -0
- package/template/build.ts +20 -0
- package/template/bunfig.toml +3 -0
- package/template/docker-compose.yaml +4 -33
- package/template/index.html +2 -2
- package/template/package.json +16 -89
- package/template/public/.gitkeep +0 -0
- package/template/server.ts +32 -0
- package/template/simulate.ts +4 -44
- package/template/src/Experiment.tsx +76 -128
- package/template/src/bun-env.d.ts +1 -0
- package/template/src/index.css +1 -9
- package/template/src/main.tsx +25 -10
- package/template/tsconfig.json +4 -6
- package/.claude/settings.local.json +0 -61
- package/.eslintrc.cjs +0 -18
- package/.playwright-mcp/console-2026-04-07T14-22-59-060Z.log +0 -1
- package/.prettierrc +0 -5
- package/Dockerfile +0 -20
- package/dist/mod-HDegGPrf.js +0 -87434
- package/dist/mod.d.ts +0 -946
- package/dist/reactive.es.js +0 -87
- package/dist/reactive.umd.js +0 -10255
- package/dist/style.css +0 -5
- package/dist/web-7BbR1Ad7.js +0 -435
- package/dist/web-CATfZO1Q.js +0 -12
- package/planned.md +0 -103
- package/postcss.config.js +0 -6
- package/raw-loader-hooks.mjs +0 -25
- package/raw-loader.mjs +0 -5
- package/rdk_doc.md +0 -341
- package/src/components/enterfullscreen.tsx +0 -230
- package/src/components/exitfullscreen.tsx +0 -113
- package/src/components/experimentprovider.tsx +0 -69
- package/src/components/experimentrunner.tsx +0 -497
- package/src/components/mobilefilepermission.tsx +0 -68
- package/src/components/settingsscreen.tsx +0 -770
- package/src/types/array.d.ts +0 -6
- package/src/utils/audiodevice.ts +0 -4
- package/src/utils/bytecode.ts +0 -261
- package/src/utils/common.ts +0 -291
- package/src/utils/ddm.test.ts +0 -233
- package/src/utils/distributions.test.ts +0 -209
- package/src/utils/nodecompat.ts +0 -11
- package/src/utils/overlays.ts +0 -19
- package/src/utils/request.ts +0 -25
- package/src/utils/simulation.ts +0 -299
- package/src/utils/upload.ts +0 -275
- package/src/vite-env.d.ts +0 -1
- package/template/.env.template +0 -2
- package/template/.eslintrc.cjs +0 -18
- package/template/.prettierrc +0 -5
- package/template/backend/package-lock.json +0 -2544
- package/template/backend/package.json +0 -31
- package/template/backend/src/backend.ts +0 -131
- package/template/backend/tsconfig.json +0 -110
- package/template/capacitor.config.ts +0 -15
- package/template/electron/main.js +0 -131
- package/template/electron/preload.js +0 -9
- package/template/electron.vite.config.js +0 -45
- package/template/package-lock.json +0 -12467
- package/template/postcss.config.js +0 -5
- package/template/public/Atkinson_Hyperlegible/AtkinsonHyperlegible-Bold.ttf +0 -0
- package/template/public/Atkinson_Hyperlegible/AtkinsonHyperlegible-BoldItalic.ttf +0 -0
- package/template/public/Atkinson_Hyperlegible/AtkinsonHyperlegible-Italic.ttf +0 -0
- package/template/public/Atkinson_Hyperlegible/AtkinsonHyperlegible-Regular.ttf +0 -0
- package/template/shared.vite.config.js +0 -39
- package/template/src/vite-env.d.ts +0 -2
- package/template/tsconfig.node.json +0 -12
- package/template/vite.config.js +0 -11
- package/tsconfig.json +0 -30
- package/tsconfig.node.json +0 -12
- package/vite.config.ts +0 -39
- /package/{template → extras}/transcription/Dockerfile.cpu +0 -0
- /package/{template → extras}/transcription/Dockerfile.gpu +0 -0
- /package/{template/public/Atkinson_Hyperlegible → src/fonts}/OFL.txt +0 -0
|
@@ -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
|
+
});
|