@adriansteffan/reactive 0.2.7 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (158) 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 +45 -40
  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/.playwright-mcp/console-2026-09-20T12-17-32-043Z.log +0 -1
  99. package/.playwright-mcp/page-2026-09-20T12-17-32-084Z.yml +0 -10
  100. package/.prettierrc +0 -5
  101. package/Dockerfile +0 -20
  102. package/dist/mod-BTpABl23.js +0 -87435
  103. package/dist/mod.d.ts +0 -947
  104. package/dist/reactive.es.js +0 -87
  105. package/dist/reactive.umd.js +0 -10255
  106. package/dist/style.css +0 -5
  107. package/dist/web-DV4cj_8Q.js +0 -435
  108. package/dist/web-DprbPn6i.js +0 -12
  109. package/planned.md +0 -103
  110. package/postcss.config.js +0 -6
  111. package/raw-loader-hooks.mjs +0 -25
  112. package/raw-loader.mjs +0 -5
  113. package/rdk_doc.md +0 -341
  114. package/src/components/enterfullscreen.tsx +0 -230
  115. package/src/components/exitfullscreen.tsx +0 -113
  116. package/src/components/experimentprovider.tsx +0 -69
  117. package/src/components/experimentrunner.tsx +0 -497
  118. package/src/components/mobilefilepermission.tsx +0 -68
  119. package/src/components/settingsscreen.tsx +0 -770
  120. package/src/types/array.d.ts +0 -6
  121. package/src/utils/audiodevice.ts +0 -4
  122. package/src/utils/bytecode.ts +0 -261
  123. package/src/utils/common.ts +0 -291
  124. package/src/utils/ddm.test.ts +0 -233
  125. package/src/utils/distributions.test.ts +0 -209
  126. package/src/utils/nodecompat.ts +0 -11
  127. package/src/utils/overlays.ts +0 -19
  128. package/src/utils/request.ts +0 -25
  129. package/src/utils/simulation.ts +0 -299
  130. package/src/utils/upload.ts +0 -275
  131. package/src/vite-env.d.ts +0 -1
  132. package/template/.env.template +0 -2
  133. package/template/.eslintrc.cjs +0 -18
  134. package/template/.prettierrc +0 -5
  135. package/template/backend/package-lock.json +0 -2544
  136. package/template/backend/package.json +0 -31
  137. package/template/backend/src/backend.ts +0 -131
  138. package/template/backend/tsconfig.json +0 -110
  139. package/template/capacitor.config.ts +0 -15
  140. package/template/electron/main.js +0 -131
  141. package/template/electron/preload.js +0 -9
  142. package/template/electron.vite.config.js +0 -45
  143. package/template/package-lock.json +0 -12467
  144. package/template/postcss.config.js +0 -5
  145. package/template/public/Atkinson_Hyperlegible/AtkinsonHyperlegible-Bold.ttf +0 -0
  146. package/template/public/Atkinson_Hyperlegible/AtkinsonHyperlegible-BoldItalic.ttf +0 -0
  147. package/template/public/Atkinson_Hyperlegible/AtkinsonHyperlegible-Italic.ttf +0 -0
  148. package/template/public/Atkinson_Hyperlegible/AtkinsonHyperlegible-Regular.ttf +0 -0
  149. package/template/shared.vite.config.js +0 -39
  150. package/template/src/vite-env.d.ts +0 -2
  151. package/template/tsconfig.node.json +0 -12
  152. package/template/vite.config.js +0 -11
  153. package/tsconfig.json +0 -30
  154. package/tsconfig.node.json +0 -12
  155. package/vite.config.ts +0 -39
  156. /package/{template → extras}/transcription/Dockerfile.cpu +0 -0
  157. /package/{template → extras}/transcription/Dockerfile.gpu +0 -0
  158. /package/{template/public/Atkinson_Hyperlegible → src/fonts}/OFL.txt +0 -0
@@ -1,572 +1,244 @@
1
- /* eslint-disable @typescript-eslint/no-explicit-any */
2
-
3
- import { useRef, useEffect, useMemo, useCallback } from 'react';
4
-
1
+ import { useEffect, useRef } from 'react';
2
+ import { type BaseComponentProps, defineComponent } from '../core/component';
5
3
  import {
6
- compileTimeline,
7
- advanceToNextContent,
8
- applyMetadata,
9
- TimelineItem,
10
- UnifiedBytecodeInstruction,
11
- ExecuteContentInstruction,
12
- Store,
13
- TrialResult,
14
- CanvasResultData,
15
- } from '../utils/bytecode';
16
- import { BaseComponentProps, isFullscreen, now } from '../utils/common';
17
- import { registerSimulation, ParticipantState } from '../utils/simulation';
18
- import { registerFlattener, arrayFlattener } from '../utils/upload';
4
+ compileSlides,
5
+ endSlide,
6
+ type Slide,
7
+ type SlideAnswer,
8
+ type SlideData,
9
+ type SlideSimulatorResult,
10
+ type SlideTimeline,
11
+ slideTimeoutMs,
12
+ startSlides,
13
+ } from '../core/slides';
14
+ import { createTimelineContext } from '../core/timeline';
19
15
  import { uniform } from '../utils/distributions';
20
-
21
- registerFlattener('CanvasBlock', 'canvas', arrayFlattener);
22
-
23
- export type SlideSimulatorResult = {
24
- key: string | null;
25
- reactionTime: number | null;
26
- participantState: ParticipantState;
27
- };
28
-
29
- export type SlideSimulator = (
30
- slide: Record<string, any>,
31
- participant: ParticipantState,
32
- ) => SlideSimulatorResult;
33
-
34
- interface CanvasSlide {
35
- draw: (ctx: CanvasRenderingContext2D, width: number, height: number) => void;
36
- displayDuration?: number;
37
- responseTimeLimit?: number;
38
- endSlideOnResponse?: boolean;
39
- hideOnResponse?: boolean;
40
- ignoreData?: boolean;
41
- allowedKeys?: string[] | boolean;
42
- metadata?:
43
- | Record<string, any>
44
- | ((data?: TrialResult[], store?: Store) => Record<string, any>);
45
- nestMetadata?: boolean;
46
- simulate?: SlideSimulator;
47
- }
48
-
49
- type DynamicCanvasSlideGenerator = (data: TrialResult[], store: Store) => CanvasSlide;
50
-
51
- function isDynamicCanvasSlideGenerator(content: any): content is DynamicCanvasSlideGenerator {
52
- return typeof content === 'function';
53
- }
54
-
55
- function isCanvasSlide(content: any): content is CanvasSlide {
56
- return typeof content === 'object' && content !== null && typeof content.draw === 'function';
57
- }
16
+ import { type CanvasSize, canvasSize, type Draw, prepareCanvas } from '../utils/canvas';
17
+ import { keyAnswer } from '../utils/keys';
18
+ import { halfFrameMs } from '../utils/time';
58
19
 
59
20
  type CanvasBlockProps = {
60
- timeline: TimelineItem[];
61
- width?: number | string;
62
- height?: number | string;
63
- styleCanvas?: (ctx: CanvasRenderingContext2D, width: number, height: number) => void;
64
- initCanvas?: (ctx: CanvasRenderingContext2D, width: number, height: number) => void;
65
- } & BaseComponentProps;
66
-
67
- export default function CanvasBlock({
68
- next,
69
- updateStore,
21
+ /** The slides, with ifBlock, whileBlock and updateStore for control flow. */
22
+ timeline: SlideTimeline;
23
+ width?: CanvasSize;
24
+ height?: CanvasSize;
25
+ /** Sets colors and fonts before each slide is drawn. */
26
+ styleCanvas?: Draw;
27
+ /** Runs once, after the canvas is set up. */
28
+ initCanvas?: Draw;
29
+ } & BaseComponentProps<SlideData[]>;
30
+
31
+ function CanvasBlock({
70
32
  timeline,
71
33
  width,
72
34
  height,
35
+ data,
73
36
  store,
37
+ next,
38
+ updateStore,
74
39
  styleCanvas,
75
40
  initCanvas,
76
41
  }: CanvasBlockProps) {
77
- const { instructions, markers } = useMemo(() => compileTimeline(timeline), [timeline]);
78
-
79
- const instructionPointerRef = useRef(0);
80
- const slideStartTimeRef = useRef<number>(0);
81
- const isDrawingVisibleRef = useRef<boolean>(true);
82
- const responseRegisteredRef = useRef<null | Record<string, any>>(null);
83
42
  const canvasRef = useRef<HTMLCanvasElement>(null);
84
- const dataRef = useRef<TrialResult[]>([]);
85
- const storeRef = useRef<Store>(store ?? {});
86
- const animationFrameRef = useRef<number | null>(null);
87
- const contentInstructionsCompletedRef = useRef(0);
88
-
89
- const frameIntervalRef = useRef<number | null>(null);
43
+ // The loop reads the latest callbacks through this ref, so new identities never restart the block
44
+ const callbacks = useRef({ next, updateStore, styleCanvas, initCanvas });
45
+ callbacks.current = { next, updateStore, styleCanvas, initCanvas };
90
46
 
91
47
  useEffect(() => {
92
- const refreshRate = storeRef.current._reactiveScreenRefreshRate;
93
- const isValidRefreshRate =
94
- typeof refreshRate === 'number' && refreshRate >= 20 && refreshRate <= 300;
95
-
96
- frameIntervalRef.current = isValidRefreshRate ? 1000 / refreshRate : null;
97
- }, [store]);
98
-
99
- const resolveSlideContent = useCallback(
100
- (instruction: UnifiedBytecodeInstruction): CanvasSlide | null => {
101
- if (instruction.type !== 'ExecuteContent') return null;
102
-
103
- const content = instruction.content;
104
- if (isDynamicCanvasSlideGenerator(content)) {
105
- try {
106
- return content(dataRef.current, storeRef.current);
107
- } catch (e) {
108
- console.error('Error executing dynamic canvas slide generator:', e);
109
- return null;
110
- }
111
- } else if (isCanvasSlide(content)) {
112
- return content;
113
- }
114
- console.warn(
115
- 'ExecuteContent instruction content is not a valid CanvasSlide or Generator:',
116
- content,
117
- );
118
- return null;
119
- },
120
- [],
121
- );
122
-
123
- const getCanvas = useCallback(() => {
124
48
  const canvas = canvasRef.current;
125
- if (!canvas) return {};
126
- const ctx = canvas.getContext('2d');
127
- if (!ctx) return {};
128
- const dpr = window.devicePixelRatio || 1;
129
- const canvasWidth = canvas.width / dpr;
130
- const canvasHeight = canvas.height / dpr;
131
- return { ctx, canvasWidth, canvasHeight };
132
- }, []);
133
-
134
- const clearCanvas = useCallback(() => {
135
- const { ctx, canvasWidth, canvasHeight } = getCanvas();
136
- if (!ctx) return;
137
- ctx.fillStyle = 'white';
138
- ctx.fillRect(0, 0, canvasWidth, canvasHeight);
139
- isDrawingVisibleRef.current = false;
140
- }, [getCanvas]);
141
-
142
- const drawSlideInternal = useCallback(
143
- (slide: CanvasSlide) => {
144
- const { ctx, canvasWidth, canvasHeight } = getCanvas();
145
- if (!ctx) return;
146
- ctx.fillStyle = 'white';
147
- ctx.fillRect(0, 0, canvasWidth, canvasHeight);
148
-
149
- if (styleCanvas) {
150
- try {
151
- styleCanvas(ctx, canvasWidth, canvasHeight);
152
- } catch (e) {
153
- console.error('Error during styleCanvas function:', e);
154
- }
155
- } else {
156
- ctx.fillStyle = 'black';
157
- }
49
+ const prepared = canvas && prepareCanvas(canvas, width, height);
50
+ if (!canvas || !prepared) return;
51
+ const { ctx, size } = prepared;
158
52
 
53
+ // A mistake in drawing code leaves the canvas incomplete instead of stopping the experiment
54
+ const paint = (drawing: Draw | undefined) => {
159
55
  try {
160
- slide.draw(ctx, canvasWidth, canvasHeight);
161
- } catch (e) {
162
- console.error('Error during slide draw function:', e);
163
- }
164
- slideStartTimeRef.current = now();
165
- isDrawingVisibleRef.current = true;
166
- responseRegisteredRef.current = null;
167
- contentInstructionsCompletedRef.current += 1;
168
- },
169
- [getCanvas],
170
- );
171
-
172
- // Forward declare handleSlideEnd for tick
173
- let handleSlideEnd: () => void;
174
-
175
- const tick = useCallback(() => {
176
- const timeNow = now();
177
- const currentPointer = instructionPointerRef.current;
178
- if (currentPointer < 0 || currentPointer >= instructions.length) {
179
- if (animationFrameRef.current) cancelAnimationFrame(animationFrameRef.current);
180
- animationFrameRef.current = null;
181
- return;
182
- }
183
- const currentInstruction = instructions[currentPointer];
184
- const currentSlide = resolveSlideContent(currentInstruction);
185
- if (!currentSlide) {
186
- if (animationFrameRef.current) cancelAnimationFrame(animationFrameRef.current);
187
- animationFrameRef.current = null;
188
- return;
189
- }
190
-
191
- const displayDuration = currentSlide.displayDuration ?? Infinity;
192
- const responseTimeLimit = currentSlide.responseTimeLimit ?? Infinity;
193
- const allowedKeys = currentSlide.allowedKeys ?? false;
194
- const noKeysAllowed =
195
- allowedKeys === false || (Array.isArray(allowedKeys) && allowedKeys.length === 0);
196
- let shouldEndSlide = false;
197
-
198
- // if we know the screen refresh rate, add half the frame interval to the elapsed time to get more accurate time checking
199
- const elapsedSlideTime =
200
- timeNow -
201
- slideStartTimeRef.current +
202
- (frameIntervalRef.current !== null ? frameIntervalRef.current * 0.5 : 0);
203
-
204
- if (
205
- isDrawingVisibleRef.current &&
206
- displayDuration !== Infinity &&
207
- elapsedSlideTime >= displayDuration
208
- ) {
209
- clearCanvas();
210
- if (noKeysAllowed || responseTimeLimit === Infinity) {
211
- shouldEndSlide = true;
212
- }
213
- }
214
-
215
- if (
216
- !shouldEndSlide &&
217
- responseTimeLimit !== Infinity &&
218
- elapsedSlideTime >= responseTimeLimit
219
- ) {
220
- shouldEndSlide = true;
221
-
222
- if (
223
- isDrawingVisibleRef.current &&
224
- displayDuration !== Infinity &&
225
- elapsedSlideTime < displayDuration
226
- ) {
227
- clearCanvas();
56
+ drawing?.(ctx, size.width, size.height);
57
+ } catch (error) {
58
+ console.error('Drawing on the canvas failed:', error);
228
59
  }
229
- }
230
-
231
- if (shouldEndSlide) {
232
- handleSlideEnd();
233
- } else {
234
- if (
235
- (isDrawingVisibleRef.current &&
236
- displayDuration !== Infinity &&
237
- elapsedSlideTime < displayDuration) ||
238
- (responseTimeLimit !== Infinity && elapsedSlideTime < responseTimeLimit)
239
- ) {
240
- animationFrameRef.current = requestAnimationFrame(tick);
241
- } else {
242
- if (animationFrameRef.current) cancelAnimationFrame(animationFrameRef.current);
243
- animationFrameRef.current = null;
244
- }
245
- }
246
- }, [instructions, resolveSlideContent, clearCanvas]);
247
-
248
- const processControlFlow = useCallback(() => {
249
- if (animationFrameRef.current) cancelAnimationFrame(animationFrameRef.current);
250
- animationFrameRef.current = null;
251
-
252
- const pointer = advanceToNextContent(
253
- { instructions, markers },
254
- instructionPointerRef.current,
255
- () => storeRef.current,
256
- () => dataRef.current,
257
- (s) => { storeRef.current = s; },
258
- );
259
- instructionPointerRef.current = pointer;
260
-
261
- if (pointer >= instructions.length) {
262
- updateStore(storeRef.current);
263
- next(dataRef.current);
264
- return;
265
- }
266
-
267
- if (!canvasRef.current) {
268
- console.error('Canvas element not found during control flow.');
269
- return;
270
- }
271
-
272
- const currentSlide = resolveSlideContent(instructions[pointer]);
273
- if (currentSlide) {
274
- drawSlideInternal(currentSlide);
275
- const displayDuration = currentSlide.displayDuration ?? Infinity;
276
- const responseTimeLimit = currentSlide.responseTimeLimit ?? Infinity;
277
- if (displayDuration !== Infinity || responseTimeLimit !== Infinity) {
278
- animationFrameRef.current = requestAnimationFrame(tick);
279
- }
280
- } else {
281
- console.error('Failed to resolve slide content during control flow:', instructions[pointer]);
282
- instructionPointerRef.current++;
283
- processControlFlow();
284
- }
285
- }, [instructions, markers, resolveSlideContent, drawSlideInternal, tick, next]);
286
-
287
- handleSlideEnd = useCallback(() => {
288
- const responseData = responseRegisteredRef.current;
289
- const endTime = now();
290
- if (animationFrameRef.current) cancelAnimationFrame(animationFrameRef.current);
291
- animationFrameRef.current = null;
292
- const currentPointer = instructionPointerRef.current;
293
- if (
294
- currentPointer >= instructions.length ||
295
- instructions[currentPointer].type !== 'ExecuteContent'
296
- ) {
297
- instructionPointerRef.current++;
298
- processControlFlow();
299
- return;
300
- }
301
- const instruction = instructions[currentPointer] as ExecuteContentInstruction;
302
- const slide = resolveSlideContent(instruction);
303
-
304
- if (slide && !slide.ignoreData) {
305
- let trialData = {
306
- index: instructionPointerRef.current,
307
- trialNumber: contentInstructionsCompletedRef.current - 1,
308
- start: slideStartTimeRef.current,
309
- end: endTime,
310
- duration: endTime - slideStartTimeRef.current,
311
- key: responseData ? responseData.key : null,
312
- reactionTime: responseData ? responseData.reactionTime : null,
313
- } as CanvasResultData;
314
-
315
- trialData = applyMetadata(trialData, slide, dataRef.current, storeRef.current);
316
-
317
- dataRef.current.push(trialData);
318
- }
319
-
320
- instructionPointerRef.current++;
321
- responseRegisteredRef.current = null;
322
- processControlFlow();
323
- }, [instructions, resolveSlideContent, processControlFlow]);
324
-
325
- const handleKeyPress = useCallback(
326
- (event: KeyboardEvent) => {
327
- const keypressTime = now();
328
- const currentPointer = instructionPointerRef.current;
329
- if (currentPointer >= instructions.length || !isDrawingVisibleRef.current) return;
330
- const instruction = instructions[currentPointer];
331
- if (instruction.type !== 'ExecuteContent') return;
332
- const currentSlide = resolveSlideContent(instruction);
333
- if (!currentSlide) return;
334
-
335
- const responseTimeLimit = currentSlide.responseTimeLimit ?? Infinity;
336
- const isWithinTimeLimit = keypressTime - slideStartTimeRef.current < responseTimeLimit;
337
- const allowedKeys = currentSlide.allowedKeys ?? false;
338
- const isKeyAllowed =
339
- allowedKeys === true || (Array.isArray(allowedKeys) && allowedKeys.includes(event.key));
340
-
341
- if (isKeyAllowed && isWithinTimeLimit) {
342
- const endSlideOnResponse = currentSlide.endSlideOnResponse ?? true;
343
- const hideOnResponse = currentSlide.hideOnResponse ?? false;
344
- const ignoreData = currentSlide.ignoreData ?? false;
345
- if (!responseRegisteredRef.current || !endSlideOnResponse) {
346
- if (!responseRegisteredRef.current && !ignoreData) {
347
- responseRegisteredRef.current = {
348
- key: event.key,
349
- time: keypressTime,
350
- reactionTime: keypressTime - slideStartTimeRef.current,
351
- };
352
- }
353
-
354
- if (hideOnResponse) clearCanvas();
355
- if (endSlideOnResponse) handleSlideEnd();
356
- }
357
- }
358
- },
359
- [instructions, resolveSlideContent, handleSlideEnd, clearCanvas],
360
- );
60
+ };
61
+ const clear = () => {
62
+ ctx.fillStyle = 'white';
63
+ ctx.fillRect(0, 0, size.width, size.height);
64
+ };
65
+ paint(callbacks.current.initCanvas);
66
+
67
+ const halfFrame = halfFrameMs(store.__screenRefreshRate);
68
+ const compiled = compileSlides(timeline);
69
+ const context = createTimelineContext(data, store);
70
+ let run = startSlides(compiled, context);
71
+
72
+ // The slide on screen: the frame that drew it, the frame it appeared with, and its response
73
+ let drawnAt = 0;
74
+ let onset: number | undefined;
75
+ let answer: SlideAnswer | undefined;
76
+ let hidden = false;
77
+ // Key presses and clicks since the last frame, which the next frame judges
78
+ let inputs: ({ key: string; timeStamp: number } | { x: number; y: number; timeStamp: number })[] = [];
79
+ let frameId = 0;
80
+
81
+ // Draws the next slide, or ends the block once there is none
82
+ const show = (timestamp: number) => {
83
+ const { slide } = run;
84
+ if (!slide) {
85
+ callbacks.current.updateStore(run.store);
86
+ callbacks.current.next(run.slides);
87
+ return;
88
+ }
89
+ clear();
90
+ ctx.fillStyle = 'black';
91
+ paint(callbacks.current.styleCanvas);
92
+ paint(slide.draw);
93
+ drawnAt = timestamp;
94
+ onset = undefined;
95
+ answer = undefined;
96
+ hidden = false;
97
+ frameId = requestAnimationFrame(frame);
98
+ };
361
99
 
362
- useEffect(() => {
363
- const canvas = canvasRef.current;
364
- if (!canvas) return;
365
- const vpWidth = isFullscreen() ? window.screen.width : window.innerWidth;
366
- const vpHeight = isFullscreen() ? window.screen.height : window.innerHeight;
367
- let computedWidth: number;
368
- let computedHeight: number;
369
- const parseNonRatioDimension = (
370
- dim: number | string | undefined,
371
- vpDim: number,
372
- ): number | null => {
373
- if (typeof dim === 'number') {
374
- return dim;
375
- }
376
- if (typeof dim === 'string' && dim.includes('%')) {
377
- const p = parseFloat(dim);
378
- if (!isNaN(p)) {
379
- return (vpDim * p) / 100;
100
+ const frame = (timestamp: number) => {
101
+ const slide = run.slide as Slide;
102
+ const timeoutMs = slideTimeoutMs(slide);
103
+ // What a frame draws appears with the next frame
104
+ onset ??= timestamp;
105
+ for (const input of inputs) {
106
+ // Inputs are timestamped on the frames' clock; one from before the slide appeared does not count
107
+ const reactionTimeMs = input.timeStamp - onset;
108
+ if (answer || reactionTimeMs < 0 || reactionTimeMs >= timeoutMs) continue;
109
+ const given =
110
+ 'key' in input ? keyAnswer(slide.response, input.key) : slide.response?.click ? { x: input.x, y: input.y } : undefined;
111
+ if (!given) continue;
112
+ answer = { ...given, reactionTimeMs: Math.round(reactionTimeMs) };
113
+ if (slide.response?.hidesDrawing) {
114
+ clear();
115
+ hidden = true;
380
116
  }
381
117
  }
382
- return null;
118
+ inputs = [];
119
+
120
+ // Half a frame more ends the slide on the frame nearest its time
121
+ const elapsed = timestamp - drawnAt + halfFrame;
122
+ if ((answer && slide.response?.endsSlide !== false) || elapsed >= timeoutMs) {
123
+ run = endSlide(compiled, context, run, {
124
+ startMs: Math.round(onset),
125
+ // It disappears with the next frame, as long after this one as it appeared after the frame that drew it
126
+ endMs: Math.round(timestamp + onset - drawnAt),
127
+ answer,
128
+ });
129
+ show(timestamp);
130
+ return;
131
+ }
132
+ if (!hidden && elapsed >= (slide.displayDurationMs ?? Number.POSITIVE_INFINITY)) {
133
+ clear();
134
+ hidden = true;
135
+ }
136
+ frameId = requestAnimationFrame(frame);
383
137
  };
384
- let initialWidthPx = parseNonRatioDimension(width, vpWidth);
385
- let initialHeightPx = parseNonRatioDimension(height, vpHeight);
386
- const isWidthRatio = typeof width === 'string' && /^\d+(?:\.\d+)?:\d+(?:\.\d+)?$/.test(width);
387
- const isHeightRatio =
388
- typeof height === 'string' && /^\d+(?:\.\d+)?:\d+(?:\.\d+)?$/.test(height);
389
- if (initialWidthPx !== null && initialHeightPx !== null) {
390
- computedWidth = initialWidthPx;
391
- computedHeight = initialHeightPx;
392
- } else if (initialWidthPx !== null && initialHeightPx === null && !isHeightRatio) {
393
- computedWidth = initialWidthPx;
394
- computedHeight = initialWidthPx;
395
- } else if (initialHeightPx !== null && initialWidthPx === null && !isWidthRatio) {
396
- computedHeight = initialHeightPx;
397
- computedWidth = initialHeightPx;
398
- } else if (
399
- initialWidthPx === null &&
400
- initialHeightPx === null &&
401
- !isWidthRatio &&
402
- !isHeightRatio
403
- ) {
404
- const s = Math.min(vpWidth, vpHeight);
405
- computedWidth = s;
406
- computedHeight = s;
407
- } else {
408
- let baseW = initialWidthPx;
409
- let baseH = initialHeightPx;
410
- if (isHeightRatio && baseW === null) {
411
- baseW = baseH ?? vpHeight;
412
- }
413
- if (isWidthRatio && baseH === null) {
414
- baseH = baseW ?? vpWidth;
415
- }
416
- if (baseW === null && baseH === null) {
417
- const s = Math.min(vpWidth, vpHeight);
418
- baseW = s;
419
- baseH = s;
420
- } else if (baseW === null) {
421
- baseW = baseH!;
422
- } else if (baseH === null) {
423
- baseH = baseW!;
424
- }
425
- computedWidth = baseW;
426
- computedHeight = baseH ?? 0;
427
- }
428
- if (isWidthRatio && !isHeightRatio) {
429
- try {
430
- const m = (width as string).match(/^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?)$/);
431
- if (m) {
432
- computedWidth = (computedHeight / parseFloat(m[2])) * parseFloat(m[1]);
433
- }
434
- } catch (e) {
435
- console.error('Invalid width ratio string:', width);
436
- }
437
- } else if (isHeightRatio && !isWidthRatio) {
438
- try {
439
- const m = (height as string).match(/^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?)$/);
440
- if (m) {
441
- computedHeight = (computedWidth / parseFloat(m[1])) * parseFloat(m[2]);
442
- }
443
- } catch (e) {
444
- console.error('Invalid height ratio string:', height);
445
- }
446
- } else if (isWidthRatio && isHeightRatio) {
447
- console.warn(`Both width (${width}) and height (${height}) are ratios. Prioritizing width.`);
448
- try {
449
- const mW = (width as string).match(/^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?)$/);
450
- if (mW) {
451
- computedWidth = (vpHeight / parseFloat(mW[2])) * parseFloat(mW[1]);
452
- const mH = (height as string).match(/^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?)$/);
453
- if (mH) {
454
- computedHeight = (computedWidth / parseFloat(mH[1])) * parseFloat(mH[2]);
455
- } else {
456
- computedHeight = computedWidth;
457
- }
458
- } else {
459
- const s = Math.min(vpWidth, vpHeight);
460
- computedWidth = s;
461
- computedHeight = s;
462
- }
463
- } catch (e) {
464
- console.error('Error parsing ratios:', e);
465
- const s = Math.min(vpWidth, vpHeight);
466
- computedWidth = s;
467
- computedHeight = s;
468
- }
469
- }
470
- const dpr = window.devicePixelRatio || 1;
471
- const finalWidth = Math.round(computedWidth);
472
- const finalHeight = Math.round(computedHeight);
473
- canvas.width = Math.round(finalWidth * dpr);
474
- canvas.height = Math.round(finalHeight * dpr);
475
- canvas.style.width = finalWidth + 'px';
476
- canvas.style.height = finalHeight + 'px';
477
- const ctx = canvas.getContext('2d');
478
- if (ctx) {
479
- ctx.scale(dpr, dpr);
480
- }
481
-
482
- if (initCanvas && ctx) {
483
- try {
484
- initCanvas(ctx, finalWidth, finalHeight);
485
- } catch (e) {
486
- console.error('Error during canvas initialization:', e);
487
- }
488
- }
489
138
 
490
- window.addEventListener('keydown', handleKeyPress);
491
- processControlFlow();
139
+ const onKeyDown = (event: KeyboardEvent) => {
140
+ // A held key repeats, which is not another response
141
+ if (!event.repeat) inputs.push({ key: event.key, timeStamp: event.timeStamp });
142
+ };
143
+ // In CSS pixels from the canvas's corner, the coordinates that drawing uses
144
+ const onPointerDown = (event: PointerEvent) => {
145
+ const bounds = canvas.getBoundingClientRect();
146
+ inputs.push({ x: event.clientX - bounds.left, y: event.clientY - bounds.top, timeStamp: event.timeStamp });
147
+ };
148
+ window.addEventListener('keydown', onKeyDown);
149
+ canvas.addEventListener('pointerdown', onPointerDown);
150
+ frameId = requestAnimationFrame(show);
492
151
  return () => {
493
- window.removeEventListener('keydown', handleKeyPress);
494
- if (animationFrameRef.current) cancelAnimationFrame(animationFrameRef.current);
152
+ window.removeEventListener('keydown', onKeyDown);
153
+ canvas.removeEventListener('pointerdown', onPointerDown);
154
+ cancelAnimationFrame(frameId);
495
155
  };
496
- }, [timeline, width, height, handleKeyPress, processControlFlow]);
156
+ }, [timeline, width, height, data, store]);
497
157
 
498
158
  return (
499
- <div
500
- style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}
501
- >
159
+ <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
502
160
  <canvas ref={canvasRef} />
503
161
  </div>
504
162
  );
505
163
  }
506
164
 
507
- // --- Default simulator ---
508
-
509
- registerSimulation('CanvasBlock', (trialProps, experimentState, simulators, participant) => {
510
- const timeline = trialProps.timeline;
511
- if (!timeline) return { responseData: [], participantState: participant };
512
-
513
- const bytecode = compileTimeline(timeline);
514
- const innerData: CanvasResultData[] = [];
515
- let innerStore: Store = { ...(experimentState.store || {}) };
516
- let currentTime = 0;
517
- let slideNumber = 0;
518
-
519
- const getStore = () => innerStore;
520
- const getData = () => innerData as TrialResult[];
521
- const onUpdateStore = (s: Store) => { innerStore = s; };
522
-
523
- let pointer = advanceToNextContent(bytecode, 0, getStore, getData, onUpdateStore);
524
-
525
- while (pointer < bytecode.instructions.length) {
526
- let slide = (bytecode.instructions[pointer] as ExecuteContentInstruction).content;
527
- if (typeof slide === 'function') slide = slide(innerData, innerStore);
528
-
529
- const sim = slide.simulate || simulators.respondToSlide;
530
- const result = sim(slide, participant);
531
- participant = result.participantState;
532
-
533
- if (!slide.ignoreData) {
534
- const duration = slide.displayDuration || result.reactionTime || 1000;
535
-
536
- let td: CanvasResultData = {
537
- index: pointer,
538
- trialNumber: slideNumber,
539
- start: currentTime,
540
- end: currentTime + duration,
541
- duration,
542
- key: result.key,
543
- reactionTime: result.reactionTime,
544
- };
545
-
546
- td = applyMetadata(td, slide, innerData, innerStore);
165
+ export default defineComponent({
166
+ name: 'CanvasBlock',
167
+ component: CanvasBlock,
168
+ // Every slide's row has metadata, if only empty, so the block's own always goes to slideblock_meta_ columns
169
+ csv: { canvas: (item) => item.recorded.map((row) => ({ metadata: {}, ...row })) },
170
+ simulate: ({ props, simulators, participant, data, store }) => {
171
+ const compiled = compileSlides(props.timeline);
172
+ const context = { data, store, slides: [] };
173
+ let run = startSlides(compiled, context);
174
+ let time = 0;
175
+
176
+ while (run.slide) {
177
+ const slide = run.slide;
178
+ const result = simulators.respondToSlide({ props, participant, slide });
179
+ participant = result.participant ?? participant;
180
+
181
+ // The same rules as in the browser: a key or click counts within the slide's time, and ends it
182
+ // unless the slide says otherwise
183
+ const timeoutMs = slideTimeoutMs(slide);
184
+ const { key, x, y, reactionTimeMs } = result.value;
185
+ const given =
186
+ key != null
187
+ ? keyAnswer(slide.response, key)
188
+ : x !== undefined && y !== undefined && slide.response?.click
189
+ ? { x, y }
190
+ : undefined;
191
+ const answer = given && reactionTimeMs !== null && reactionTimeMs < timeoutMs ? { ...given, reactionTimeMs } : undefined;
192
+ const durationMs = answer && slide.response?.endsSlide !== false ? answer.reactionTimeMs : timeoutMs;
193
+ if (durationMs === Number.POSITIVE_INFINITY) {
194
+ throw new Error('A simulated participant gave no response to a slide that only a response ends.');
195
+ }
196
+
197
+ run = endSlide(compiled, context, run, { startMs: time, endMs: time + durationMs, answer });
198
+ time += durationMs;
199
+ }
200
+
201
+ return { recorded: run.slides, participant, storeUpdates: run.store, durationMs: time };
202
+ },
203
+ defaultSimulators: {
204
+ // One of the slide's ways to respond, at random: a listed key, any key, a choice's key, or a click
205
+ respondToSlide: ({ props, slide }): SlideSimulatorResult => {
206
+ const response = (slide as Slide).response;
207
+ const keys = response?.keys === true ? [' '] : (response?.keys ?? []);
208
+ const options: { key?: string; x?: number; y?: number }[] = [
209
+ ...keys.map((key) => ({ key })),
210
+ ...Object.values(response?.choices ?? {}).map(({ key }) => ({ key })),
211
+ ];
212
+ if (response?.click) {
213
+ // A point on the canvas as it would be sized on a 1920 by 1080 screen
214
+ const size = canvasSize(props.width, props.height, 1920, 1080);
215
+ options.push({ x: uniform(0, size.width), y: uniform(0, size.height) });
216
+ }
217
+ if (options.length === 0) return { value: { key: null, reactionTimeMs: null } };
218
+ return { value: { ...options[Math.floor(uniform(0, options.length))], reactionTimeMs: uniform(200, 800) } };
219
+ },
220
+ },
221
+ });
547
222
 
548
- innerData.push(td);
549
- currentTime += duration;
550
- }
223
+ /** Slides that count down from `seconds`, one second each, recording nothing. */
224
+ export function canvasCountdown(seconds: number): Slide[] {
225
+ return Array.from({ length: seconds }, (_, i) => {
226
+ const number = seconds - i;
551
227
 
552
- slideNumber++;
553
- pointer = advanceToNextContent(bytecode, pointer + 1, getStore, getData, onUpdateStore);
554
- }
228
+ return {
229
+ draw: (ctx: CanvasRenderingContext2D, w: number, h: number) => {
230
+ ctx.save();
555
231
 
556
- return { responseData: innerData, participantState: participant, storeUpdates: innerStore, duration: currentTime };
557
- }, {
558
- respondToSlide: (slide: any, participant: any) => {
559
- const keys = slide.allowedKeys;
560
- if (keys === true) {
561
- return { key: ' ', reactionTime: uniform(200, 800), participantState: participant };
562
- }
563
- if (Array.isArray(keys) && keys.length > 0) {
564
- return {
565
- key: keys[Math.floor(uniform(0, keys.length))],
566
- reactionTime: uniform(200, 800),
567
- participantState: participant,
568
- };
569
- }
570
- return { key: null, reactionTime: null, participantState: participant };
571
- },
572
- });
232
+ ctx.fillStyle = 'black';
233
+ ctx.font = `bold ${Math.min(w, h) * 0.02 * 2}px sans-serif`; // Make countdown text larger
234
+ ctx.textAlign = 'center';
235
+ ctx.textBaseline = 'middle';
236
+ ctx.fillText(number.toString(), w / 2, h / 2);
237
+
238
+ ctx.restore();
239
+ },
240
+ displayDurationMs: 1000,
241
+ ignoreData: true,
242
+ };
243
+ });
244
+ }