@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
@@ -8,18 +8,17 @@ import {
8
8
  useImperativeHandle,
9
9
  } from 'react';
10
10
  import type { CSSProperties } from 'react';
11
- import { BaseComponentProps, shuffle } from '../mod';
12
- import { registerSimulation } from '../utils/simulation';
13
- import { registerFlattener } from '../utils/upload';
11
+ import { BaseComponentProps } from '../core/component';
12
+ import { shuffle } from '../utils/array';
13
+ import { defineComponent } from '../core/component';
14
14
  import { simulateDDMTrial, mapDDMChoice } from '../utils/ddm';
15
-
16
- registerFlattener('RandomDotKinematogram', 'rdk');
15
+ import { type ResponseKey, responseKey } from '../utils/keys';
17
16
 
18
17
  // Single source of truth for all RDK parameter defaults.
19
18
  // Used by RDKCanvas, the trial component, and the simulation.
20
19
  const RDK_DEFAULTS = {
21
- validKeys: [] as string[],
22
- duration: 1000,
20
+ allowedResponseKeys: true as readonly ResponseKey[] | boolean,
21
+ timeLimitMs: 1000,
23
22
  responseEndsTrial: true,
24
23
  dotCount: 300,
25
24
  dotSetCount: 1,
@@ -27,7 +26,7 @@ const RDK_DEFAULTS = {
27
26
  coherence: 0.5,
28
27
  opposite: 0,
29
28
  speed: 60,
30
- dotLifetime: -1,
29
+ dotLifetimeMs: -1,
31
30
  dotRadius: 2,
32
31
  dotColor: 'white',
33
32
  backgroundColor: 'gray',
@@ -36,8 +35,8 @@ const RDK_DEFAULTS = {
36
35
  apertureHeight: 400,
37
36
  reinsertMode: 'opposite' as ReinsertType,
38
37
  noiseMovement: 'randomDirection' as NoiseMovement,
39
- fixationTime: 500,
40
- showFixation: false,
38
+ fixationTimeMs: 500,
39
+ showFixation: true,
41
40
  fixationWidth: 15,
42
41
  fixationHeight: 15,
43
42
  fixationColor: 'white',
@@ -47,84 +46,13 @@ const RDK_DEFAULTS = {
47
46
  borderColor: 'black',
48
47
  };
49
48
 
50
- registerSimulation('RandomDotKinematogram', (trialProps, _experimentState, simulators, participant) => {
51
- const merged: any = { ...RDK_DEFAULTS, ...trialProps };
52
- const result = simulators.respond(merged, participant);
53
- const { rt, response } = result.value;
54
-
55
- const preTrialDuration = merged.preTrialMessage?.duration ?? 0;
56
- const fixation = merged.fixationTime ?? RDK_DEFAULTS.fixationTime;
57
- const trialDuration = merged.duration ?? RDK_DEFAULTS.duration;
58
- const responseEndsTrial = merged.responseEndsTrial ?? RDK_DEFAULTS.responseEndsTrial;
59
- const elapsed = (responseEndsTrial && rt != null) ? rt : trialDuration;
60
-
61
- const correctKeys = Array.isArray(merged.correctResponse)
62
- ? merged.correctResponse.map((c: string) => c.toLowerCase())
63
- : merged.correctResponse ? [merged.correctResponse.toLowerCase()] : null;
64
- const correct = response && correctKeys ? correctKeys.includes(response.toLowerCase()) : null;
65
-
66
- let totalDuration = preTrialDuration + fixation + elapsed;
67
-
68
- const responseData: Record<string, any> = {
69
- ...merged,
70
- rt,
71
- response,
72
- correct,
73
- framesDisplayed: 0,
74
- measuredRefreshRate: null,
75
- feedbackShown: null as string | null,
76
- feedbackDuration: null as number | null,
77
- };
78
-
79
- const fb = merged.feedback as RDKFeedback | undefined;
80
- if (fb) {
81
- let shown: RDKMessage | null = null;
82
- if (rt === null && fb.onTimeout) shown = fb.onTimeout;
83
- else if (correct === false && fb.onIncorrect) shown = fb.onIncorrect;
84
- else if (correct === true && fb.onCorrect) shown = fb.onCorrect;
85
-
86
- if (shown) {
87
- responseData.feedbackShown = shown.content;
88
- responseData.feedbackDuration = shown.duration;
89
- totalDuration += shown.duration;
90
- }
91
- }
92
-
93
- return {
94
- responseData,
95
- participantState: result.participantState,
96
- duration: totalDuration,
97
- };
98
- }, {
99
- respond: (trialProps: any, participant: any) => {
100
- const ddm = simulateDDMTrial({
101
- driftRate: { type: 'normal', mean: 0.005 * (trialProps.coherence ?? RDK_DEFAULTS.coherence), sd: 0.0012 },
102
- boundaries: 0.75,
103
- startingPoint: 0,
104
- noiseLevel: 0.02,
105
- sensoryDelay: { type: 'uniform', min: 150, max: 250 },
106
- motorDelay: { type: 'uniform', min: 130, max: 210 },
107
- timeLimit: trialProps.duration ?? RDK_DEFAULTS.duration,
108
- stimOffset: trialProps.stimulusDuration ?? trialProps.duration ?? RDK_DEFAULTS.duration,
109
- postStimStrategy: { type: 'continue' },
110
- });
111
-
112
- const key = mapDDMChoice(ddm.choice, trialProps.validKeys, trialProps.correctResponse);
113
-
114
- return {
115
- value: { rt: key ? ddm.rt : null, response: key },
116
- participantState: participant,
117
- };
118
- },
119
- });
120
-
121
49
  export interface RDKMessage {
122
50
  content: string;
123
- duration: number;
51
+ durationMs: number;
124
52
  }
125
53
 
126
54
  export interface RDKFeedback {
127
- /** Shown when rt === null (no response within duration) */
55
+ /** Shown when no key counted within the time limit */
128
56
  onTimeout?: RDKMessage;
129
57
  /** Shown when the response was incorrect (correct === false) */
130
58
  onIncorrect?: RDKMessage;
@@ -174,7 +102,7 @@ interface Aperture {
174
102
  centerY: number;
175
103
  getRandomPosition(): [number, number];
176
104
  isOutside(x: number, y: number, margin: number): boolean;
177
- getOppositePosition(dot: Dot, dirX?: number, dirY?: number): [number, number];
105
+ getOppositePosition(dot: Dot, dirX: number, dirY: number): [number, number];
178
106
  getOppositePositionSimple(dot: Dot): [number, number];
179
107
  wrap(x: number, y: number): [number, number];
180
108
  clip(ctx: CanvasRenderingContext2D): void;
@@ -223,35 +151,33 @@ const createAperture = (
223
151
  },
224
152
  getOppositePosition(dot, dirX, dirY) {
225
153
  // Ray-ellipse intersection: find where backward ray hits far side of boundary
226
- if (dirX !== undefined && dirY !== undefined) {
227
- const dirMagSq = dirX * dirX + dirY * dirY;
228
- if (dirMagSq > 1e-10) {
229
- // Normalize direction
230
- const mag = Math.sqrt(dirMagSq);
231
- const dx = dirX / mag;
232
- const dy = dirY / mag;
233
-
234
- // Position relative to center
235
- const xRel = dot.x - centerX;
236
- const yRel = dot.y - centerY;
237
-
238
- // Ellipse: semi-axes squared
239
- const a2 = horizontalAxis * horizontalAxis;
240
- const b2 = verticalAxis * verticalAxis;
241
-
242
- // Quadratic coefficients for ray-ellipse intersection
243
- // Ray: P(t) = (dot.x - dx*t, dot.y - dy*t)
244
- const A = (dx * dx) / a2 + (dy * dy) / b2;
245
- const B = (xRel * dx) / a2 + (yRel * dy) / b2;
246
- const C = (xRel * xRel) / a2 + (yRel * yRel) / b2 - 1;
247
-
248
- const discriminant = B * B - A * C;
249
- if (discriminant >= 0) {
250
- // Larger root gives far intersection (entry point from other side)
251
- const t = (B + Math.sqrt(discriminant)) / A;
252
- if (t > 0 && Number.isFinite(t)) {
253
- return [dot.x - dx * t, dot.y - dy * t];
254
- }
154
+ const dirMagSq = dirX * dirX + dirY * dirY;
155
+ if (dirMagSq > 1e-10) {
156
+ // Normalize direction
157
+ const mag = Math.sqrt(dirMagSq);
158
+ const dx = dirX / mag;
159
+ const dy = dirY / mag;
160
+
161
+ // Position relative to center
162
+ const xRel = dot.x - centerX;
163
+ const yRel = dot.y - centerY;
164
+
165
+ // Ellipse: semi-axes squared
166
+ const a2 = horizontalAxis * horizontalAxis;
167
+ const b2 = verticalAxis * verticalAxis;
168
+
169
+ // Quadratic coefficients for ray-ellipse intersection
170
+ // Ray: P(t) = (dot.x - dx*t, dot.y - dy*t)
171
+ const A = (dx * dx) / a2 + (dy * dy) / b2;
172
+ const B = (xRel * dx) / a2 + (yRel * dy) / b2;
173
+ const C = (xRel * xRel) / a2 + (yRel * yRel) / b2 - 1;
174
+
175
+ const discriminant = B * B - A * C;
176
+ if (discriminant >= 0) {
177
+ // Larger root gives far intersection (entry point from other side)
178
+ const t = (B + Math.sqrt(discriminant)) / A;
179
+ if (t > 0 && Number.isFinite(t)) {
180
+ return [dot.x - dx * t, dot.y - dy * t];
255
181
  }
256
182
  }
257
183
  }
@@ -311,10 +237,6 @@ const createAperture = (
311
237
  },
312
238
  getOppositePosition(dot, dirX, dirY) {
313
239
  // Ray-rectangle intersection using slab method
314
- if (dirX === undefined || dirY === undefined) {
315
- return this.getOppositePositionSimple(dot);
316
- }
317
-
318
240
  const mag = Math.sqrt(dirX * dirX + dirY * dirY);
319
241
  if (mag < 1e-10) {
320
242
  return this.getOppositePositionSimple(dot);
@@ -507,7 +429,7 @@ export interface RDKCanvasProps {
507
429
  coherence?: number;
508
430
  opposite?: number;
509
431
  speed?: number;
510
- dotLifetime?: number;
432
+ dotLifetimeMs?: number;
511
433
  updateRate?: number;
512
434
  dotRadius?: number;
513
435
  dotCharacter?: string;
@@ -521,6 +443,7 @@ export interface RDKCanvasProps {
521
443
  apertureCenterY?: number;
522
444
  reinsertMode?: ReinsertType;
523
445
  noiseMovement?: NoiseMovement;
446
+ /** How often the dots' roles are drawn again: never without it, every update with 0, or every this many milliseconds. */
524
447
  reassignEveryMs?: number;
525
448
  showFixation?: boolean;
526
449
  fixationWidth?: number;
@@ -547,7 +470,7 @@ export const RDKCanvas = forwardRef<RDKCanvasHandle, RDKCanvasProps>(
547
470
  const {
548
471
  width,
549
472
  height,
550
- dotCount, dotSetCount, direction, coherence, opposite, speed, dotLifetime,
473
+ dotCount, dotSetCount, direction, coherence, opposite, speed, dotLifetimeMs,
551
474
  updateRate, dotRadius, dotCharacter, dotColor, coherentDotColor, backgroundColor,
552
475
  apertureShape, apertureWidth, apertureHeight, apertureCenterX, apertureCenterY,
553
476
  reinsertMode, noiseMovement, reassignEveryMs,
@@ -568,7 +491,6 @@ export const RDKCanvas = forwardRef<RDKCanvasHandle, RDKCanvasProps>(
568
491
  // Refresh rate estimation
569
492
  const frameIntervalsRef = useRef<number[]>([]);
570
493
  const estimatedFrameIntervalRef = useRef<number | null>(null);
571
- const isCalibrated = useRef(false);
572
494
 
573
495
  // Default aperture center to canvas center
574
496
  const effectiveCenterX = apertureCenterX ?? width / 2;
@@ -597,20 +519,13 @@ export const RDKCanvas = forwardRef<RDKCanvasHandle, RDKCanvasProps>(
597
519
 
598
520
  // Initialize dots
599
521
  useEffect(() => {
600
- const nCoherent = Math.floor(dotCount * coherence);
601
- const nOpposite = Math.floor(dotCount * opposite);
602
-
603
522
  dotSetsRef.current = Array.from({ length: dotSetCount }, () =>
604
- Array.from({ length: dotCount }, (_, i) => {
605
- let assignedMovement: FrameMovement;
606
- if (i < nCoherent) assignedMovement = 'coherent';
607
- else if (i < nCoherent + nOpposite) assignedMovement = 'opposite';
608
- else assignedMovement = noiseMovement;
609
-
610
- return createDot(assignedMovement, dotLifetime, aperture);
611
- }),
523
+ generateShuffledAssignments(dotCount, coherence, opposite, noiseMovement).map((movement) =>
524
+ createDot(movement, dotLifetimeMs, aperture),
525
+ ),
612
526
  );
613
- }, []);
527
+ currentSetRef.current = 0;
528
+ }, [dotCount, dotSetCount, coherence, opposite, noiseMovement, dotLifetimeMs, aperture]);
614
529
 
615
530
  // Seed refresh rate estimate
616
531
  useEffect(() => {
@@ -620,7 +535,6 @@ export const RDKCanvas = forwardRef<RDKCanvasHandle, RDKCanvasProps>(
620
535
  initialRefreshRate <= 300
621
536
  ) {
622
537
  estimatedFrameIntervalRef.current = 1000 / initialRefreshRate;
623
- isCalibrated.current = true;
624
538
  }
625
539
  }, [initialRefreshRate]);
626
540
 
@@ -708,27 +622,25 @@ export const RDKCanvas = forwardRef<RDKCanvasHandle, RDKCanvasProps>(
708
622
  frameCountRef.current++;
709
623
 
710
624
  // Update refresh rate estimate
625
+ const estimate = estimatedFrameIntervalRef.current;
711
626
  if (frameDelta > 0 && frameDelta < 500) {
712
- if (!isCalibrated.current) {
627
+ if (estimate === null) {
713
628
  frameIntervalsRef.current.push(frameDelta);
714
629
  if (frameIntervalsRef.current.length >= CALIBRATION_FRAME_COUNT) {
715
630
  const sorted = [...frameIntervalsRef.current].sort((a, b) => a - b);
716
631
  const mid = Math.floor(sorted.length / 2);
717
632
  estimatedFrameIntervalRef.current =
718
633
  sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
719
- isCalibrated.current = true;
720
634
  }
721
635
  } else {
722
- estimatedFrameIntervalRef.current =
723
- EMA_ALPHA * frameDelta + (1 - EMA_ALPHA) * estimatedFrameIntervalRef.current!;
636
+ estimatedFrameIntervalRef.current = EMA_ALPHA * frameDelta + (1 - EMA_ALPHA) * estimate;
724
637
  }
725
638
  }
726
639
 
727
- const rawTimeSinceLastUpdate = timestamp - (lastUpdateTimeRef.current ?? timestamp);
728
640
  // Cap delta to avoid massive jumps when returning from a backgrounded tab
729
- const timeSinceLastUpdate = Math.min(rawTimeSinceLastUpdate, 100);
641
+ const timeSinceLastUpdate = Math.min(timestamp - lastUpdateTimeRef.current, 100);
730
642
  const updateInterval = updateRate && updateRate > 0 ? 1000 / updateRate : 0;
731
- const shouldUpdate = !updateRate || updateRate <= 0 || timeSinceLastUpdate >= updateInterval;
643
+ const shouldUpdate = timeSinceLastUpdate >= updateInterval;
732
644
 
733
645
  ctx.clearRect(0, 0, canvas.width, canvas.height);
734
646
 
@@ -752,10 +664,7 @@ export const RDKCanvas = forwardRef<RDKCanvasHandle, RDKCanvasProps>(
752
664
  shouldReassign = true;
753
665
  } else {
754
666
  timeSinceReassignRef.current += timeSinceLastUpdate;
755
- const halfFrameCorrection =
756
- isCalibrated.current && estimatedFrameIntervalRef.current
757
- ? estimatedFrameIntervalRef.current * 0.5
758
- : 0;
667
+ const halfFrameCorrection = (estimatedFrameIntervalRef.current ?? 0) * 0.5;
759
668
  const correctedTime = timeSinceReassignRef.current + halfFrameCorrection;
760
669
  shouldReassign = correctedTime >= reassignEveryMs;
761
670
  if (shouldReassign) {
@@ -774,7 +683,7 @@ export const RDKCanvas = forwardRef<RDKCanvasHandle, RDKCanvasProps>(
774
683
  dot,
775
684
  distance,
776
685
  timeSinceLastUpdate,
777
- dotLifetime,
686
+ dotLifetimeMs,
778
687
  aperture,
779
688
  reinsertMode,
780
689
  dotRadius,
@@ -811,7 +720,7 @@ export const RDKCanvas = forwardRef<RDKCanvasHandle, RDKCanvasProps>(
811
720
  opposite,
812
721
  dotCount,
813
722
  speed,
814
- dotLifetime,
723
+ dotLifetimeMs,
815
724
  aperture,
816
725
  reinsertMode,
817
726
  dotSetCount,
@@ -863,42 +772,33 @@ export const RDKCanvas = forwardRef<RDKCanvasHandle, RDKCanvasProps>(
863
772
 
864
773
  // ─── Trial Component ────────────────────────────────────────────────────────────
865
774
 
866
- export interface RDKProps extends BaseComponentProps {
867
- validKeys?: string[];
868
- correctResponse?: string | string[];
869
- duration?: number;
870
- stimulusDuration?: number; // How long to show stimulus (defaults to duration)
775
+ // The message shown after the response, or after no response in time
776
+ const feedbackFor = (feedback: RDKFeedback | undefined, rt: number | null, correct: boolean | null) => {
777
+ if (rt === null) return feedback?.onTimeout ?? null;
778
+ if (correct === false) return feedback?.onIncorrect ?? null;
779
+ if (correct === true) return feedback?.onCorrect ?? null;
780
+ return null;
781
+ };
782
+
783
+ // Whether the key is a correct response, ignoring case like the keys that count; `null` without a key or a correct response
784
+ const isCorrect = (key: string | null, correctResponse: ResponseKey | readonly ResponseKey[] | undefined) =>
785
+ key && correctResponse !== undefined ? responseKey([correctResponse].flat(), key) !== undefined : null;
786
+
787
+ // The canvas's settings, which a trial passes on as they are
788
+ type CanvasSettings = Omit<RDKCanvasProps, 'width' | 'height' | 'active' | 'initialRefreshRate' | 'style' | 'className'>;
789
+
790
+ /** A trial's settings: the canvas's, and how the trial takes its response. */
791
+ export interface RDKSettings extends CanvasSettings {
792
+ /** Keys that count as a response, letters in either case; `true` for any key. */
793
+ allowedResponseKeys?: readonly ResponseKey[] | boolean;
794
+ correctResponse?: ResponseKey | readonly ResponseKey[];
795
+ /** How long after the dots appear a key counts as a response. The trial ends then, if no response has ended it. */
796
+ timeLimitMs?: number;
797
+ /** How long the dots are shown; `timeLimitMs` by default. */
798
+ displayDurationMs?: number;
799
+ /** Whether the first response ends the trial. Defaults to `true`. */
871
800
  responseEndsTrial?: boolean;
872
- dotCount?: number;
873
- dotSetCount?: number;
874
- direction?: number;
875
- coherence?: number;
876
- opposite?: number;
877
- speed?: number;
878
- dotLifetime?: number;
879
- updateRate?: number;
880
- dotRadius?: number;
881
- dotCharacter?: string;
882
- dotColor?: string;
883
- coherentDotColor?: string;
884
- backgroundColor?: string;
885
- apertureShape?: ApertureShape;
886
- apertureWidth?: number;
887
- apertureHeight?: number;
888
- apertureCenterX?: number;
889
- apertureCenterY?: number;
890
- reinsertMode?: ReinsertType;
891
- noiseMovement?: NoiseMovement;
892
- reassignEveryMs?: number; // undefined = never, 0 = every update, > 0 = every X ms
893
- showFixation?: boolean;
894
- fixationTime?: number;
895
- fixationWidth?: number;
896
- fixationHeight?: number;
897
- fixationColor?: string;
898
- fixationThickness?: number;
899
- showBorder?: boolean;
900
- borderWidth?: number;
901
- borderColor?: string;
801
+ fixationTimeMs?: number;
902
802
  responseHint?: string;
903
803
  /** Timed message shown before the fixation cross. Useful for per-trial condition cues. */
904
804
  preTrialMessage?: RDKMessage;
@@ -906,44 +806,54 @@ export interface RDKProps extends BaseComponentProps {
906
806
  feedback?: RDKFeedback;
907
807
  }
908
808
 
909
- export const RandomDotKinematogram = (rawProps: RDKProps) => {
809
+ /** What a trial records: its settings, the key pressed and when, and what it showed. */
810
+ export type RDKResponse = RDKSettings & {
811
+ key: string | null;
812
+ /** From when the dots appeared. */
813
+ reactionTimeMs: number | null;
814
+ correct: boolean | null;
815
+ framesDisplayed: number;
816
+ measuredRefreshRate: number | null;
817
+ feedbackShown: string | null;
818
+ feedbackDurationMs: number | null;
819
+ };
820
+
821
+ export type RDKProps = RDKSettings & BaseComponentProps<RDKResponse>;
822
+
823
+ const RandomDotKinematogramComponent = (rawProps: RDKProps) => {
910
824
  const {
911
- store,
912
- stimulusDuration, updateRate, dotCharacter, coherentDotColor,
913
- apertureCenterX = window.innerWidth / 2,
914
- apertureCenterY = window.innerHeight / 2,
915
- reassignEveryMs, responseHint,
916
- validKeys, duration, responseEndsTrial,
917
- dotCount, dotSetCount, direction, coherence, opposite, speed, dotLifetime,
918
- dotRadius, dotColor, backgroundColor,
919
- apertureShape, apertureWidth, apertureHeight, reinsertMode, noiseMovement,
920
- showFixation, fixationTime, fixationWidth, fixationHeight, fixationColor, fixationThickness,
921
- showBorder, borderWidth, borderColor,
825
+ next: _next, data: _data, store, updateStore: _updateStore, name: _name,
826
+ allowedResponseKeys, correctResponse: _correctResponse, timeLimitMs, displayDurationMs, responseEndsTrial,
827
+ fixationTimeMs, responseHint, preTrialMessage: _preTrialMessage, feedback: _feedback,
828
+ ...canvasSettings
922
829
  } = { ...RDK_DEFAULTS, ...rawProps };
830
+ const { backgroundColor } = canvasSettings;
923
831
  // Keep a ref to the latest props so endTrial can read them without recreating on every render.
924
832
  const propsRef = useRef(rawProps);
925
833
  propsRef.current = rawProps;
926
834
 
927
- const preTrialDuration = rawProps.preTrialMessage?.duration ?? 0;
835
+ const preTrialDuration = rawProps.preTrialMessage?.durationMs ?? 0;
928
836
 
929
837
  const canvasHandle = useRef<RDKCanvasHandle>(null);
930
- const startTimeRef = useRef<number>(performance.now());
838
+ // When the dots appeared, which reaction times count from
839
+ const startTimeRef = useRef(0);
931
840
  const trialEndedRef = useRef(false);
932
841
  const responseRef = useRef<string | null>(null);
933
842
  const responseTimeRef = useRef<number | null>(null);
934
843
 
935
844
  const [preTrialDone, setPreTrialDone] = useState(!rawProps.preTrialMessage);
936
845
  const [response, setResponse] = useState<string | null>(null);
937
- const [fixationComplete, setFixationComplete] = useState(fixationTime <= 0);
846
+ const [fixationComplete, setFixationComplete] = useState(fixationTimeMs <= 0);
938
847
  const [stimulusVisible, setStimulusVisible] = useState(true);
939
848
  const [feedbackMsg, setFeedbackMsg] = useState<RDKMessage | null>(null);
940
849
 
941
- const initialRefreshRate = store?._reactiveScreenRefreshRate;
850
+ const initialRefreshRate = store.__screenRefreshRate;
942
851
 
943
852
  // Pre-trial message timer
853
+ // biome-ignore lint/correctness/useExhaustiveDependencies: the message is shown once per trial, a new props object must not restart it
944
854
  useEffect(() => {
945
855
  if (!rawProps.preTrialMessage) return;
946
- const timer = setTimeout(() => setPreTrialDone(true), rawProps.preTrialMessage.duration);
856
+ const timer = setTimeout(() => setPreTrialDone(true), rawProps.preTrialMessage.durationMs);
947
857
  return () => clearTimeout(timer);
948
858
  }, []);
949
859
 
@@ -951,78 +861,69 @@ export const RandomDotKinematogram = (rawProps: RDKProps) => {
951
861
  if (trialEndedRef.current) return;
952
862
  trialEndedRef.current = true;
953
863
 
954
- const { next: nextFn, data: _d, store: _s, updateStore: _u, ...rdkProps } = propsRef.current;
864
+ const { next: nextFn, data: _d, store: _s, updateStore: _u, name: _n, ...rdkProps } = propsRef.current;
955
865
  const stats = canvasHandle.current?.getStats();
956
- const correctKeys = Array.isArray(rdkProps.correctResponse)
957
- ? rdkProps.correctResponse.map((c) => c.toLowerCase())
958
- : rdkProps.correctResponse
959
- ? [rdkProps.correctResponse.toLowerCase()]
960
- : null;
961
- const correct = key && correctKeys ? correctKeys.includes(key) : null;
962
-
963
- const responseData: Record<string, any> = {
866
+ const correct = isCorrect(key, rdkProps.correctResponse);
867
+
868
+ const recorded: RDKResponse = {
964
869
  ...RDK_DEFAULTS,
965
870
  ...rdkProps,
966
- rt,
967
- response: key,
871
+ key,
872
+ reactionTimeMs: rt,
968
873
  correct,
969
874
  framesDisplayed: stats?.framesDisplayed ?? 0,
970
875
  measuredRefreshRate: stats?.measuredRefreshRate ?? null,
971
876
  feedbackShown: null,
972
- feedbackDuration: null,
877
+ feedbackDurationMs: null,
973
878
  };
974
879
 
975
- const fb = rdkProps.feedback;
976
- let shown: RDKMessage | null = null;
977
- if (fb) {
978
- if (rt === null && fb.onTimeout) shown = fb.onTimeout;
979
- else if (correct === false && fb.onIncorrect) shown = fb.onIncorrect;
980
- else if (correct === true && fb.onCorrect) shown = fb.onCorrect;
981
- }
982
-
880
+ const shown = feedbackFor(rdkProps.feedback, rt, correct);
983
881
  if (shown) {
984
- responseData.feedbackShown = shown.content;
985
- responseData.feedbackDuration = shown.duration;
882
+ recorded.feedbackShown = shown.content;
883
+ recorded.feedbackDurationMs = shown.durationMs;
986
884
  setFeedbackMsg(shown);
987
- setTimeout(() => nextFn(responseData), shown.duration);
885
+ setTimeout(() => nextFn(recorded), shown.durationMs);
988
886
  } else {
989
- nextFn(responseData);
887
+ nextFn(recorded);
990
888
  }
991
889
  }, []);
992
890
 
993
891
  // Fixation duration delay before showing dots (offset by preTrialDuration)
994
892
  useEffect(() => {
995
- if (fixationTime <= 0) return;
996
- const timer = setTimeout(() => setFixationComplete(true), preTrialDuration + fixationTime);
893
+ if (fixationTimeMs <= 0) return;
894
+ const timer = setTimeout(() => setFixationComplete(true), preTrialDuration + fixationTimeMs);
997
895
  return () => clearTimeout(timer);
998
- }, [fixationTime, preTrialDuration]);
896
+ }, [fixationTimeMs, preTrialDuration]);
999
897
 
1000
898
  // Stimulus duration timer (offset by preTrialDuration)
1001
899
  useEffect(() => {
1002
- const effectiveStimDur = stimulusDuration ?? duration;
900
+ const effectiveStimDur = displayDurationMs ?? timeLimitMs;
1003
901
  if (effectiveStimDur <= 0) return;
1004
- const timer = setTimeout(() => setStimulusVisible(false), preTrialDuration + fixationTime + effectiveStimDur);
902
+ const timer = setTimeout(() => setStimulusVisible(false), preTrialDuration + fixationTimeMs + effectiveStimDur);
1005
903
  return () => clearTimeout(timer);
1006
- }, [preTrialDuration, fixationTime, stimulusDuration, duration]);
904
+ }, [preTrialDuration, fixationTimeMs, displayDurationMs, timeLimitMs]);
1007
905
 
1008
906
  // Trial duration timer — ends trial with whatever response was collected (offset by preTrialDuration)
1009
907
  useEffect(() => {
1010
- if (duration <= 0) return;
908
+ if (timeLimitMs <= 0) return;
1011
909
  const timer = setTimeout(() => {
1012
910
  endTrial(responseRef.current, responseTimeRef.current);
1013
- }, preTrialDuration + fixationTime + duration);
911
+ }, preTrialDuration + fixationTimeMs + timeLimitMs);
1014
912
  return () => clearTimeout(timer);
1015
- }, [preTrialDuration, fixationTime, duration, endTrial]);
913
+ }, [preTrialDuration, fixationTimeMs, timeLimitMs, endTrial]);
1016
914
 
1017
- // Handle keyboard response (blocked during preTrialMessage)
915
+ // The dots appear once the pre-trial message and the fixation are over, and keys count from then on
916
+ const stimulusShown = preTrialDone && fixationComplete;
1018
917
  useEffect(() => {
1019
- const handleKeyPress = (e: KeyboardEvent) => {
1020
- if (trialEndedRef.current || responseRef.current || !preTrialDone) return;
918
+ if (stimulusShown) startTimeRef.current = performance.now();
919
+ }, [stimulusShown]);
1021
920
 
1022
- const key = e.key.toLowerCase();
1023
- const allowedKeys = validKeys.length > 0 ? validKeys.map((c) => c.toLowerCase()) : null;
921
+ useEffect(() => {
922
+ const handleKeyPress = (e: KeyboardEvent) => {
923
+ if (trialEndedRef.current || responseRef.current || !stimulusShown) return;
1024
924
 
1025
- if (!allowedKeys || allowedKeys.includes(key)) {
925
+ const key = responseKey(allowedResponseKeys, e.key);
926
+ if (key !== undefined) {
1026
927
  const rt = performance.now() - startTimeRef.current;
1027
928
  responseRef.current = key;
1028
929
  responseTimeRef.current = rt;
@@ -1036,7 +937,7 @@ export const RandomDotKinematogram = (rawProps: RDKProps) => {
1036
937
 
1037
938
  window.addEventListener('keydown', handleKeyPress);
1038
939
  return () => window.removeEventListener('keydown', handleKeyPress);
1039
- }, [validKeys, responseEndsTrial, endTrial, preTrialDone]);
940
+ }, [allowedResponseKeys, responseEndsTrial, endTrial, stimulusShown]);
1040
941
 
1041
942
  const messageOverlay = (text: string) => (
1042
943
  <div
@@ -1063,40 +964,12 @@ export const RandomDotKinematogram = (rawProps: RDKProps) => {
1063
964
  ) : (
1064
965
  <>
1065
966
  <RDKCanvas
967
+ {...canvasSettings}
1066
968
  ref={canvasHandle}
1067
969
  width={window.innerWidth}
1068
970
  height={window.innerHeight}
1069
971
  active={fixationComplete && stimulusVisible}
1070
972
  initialRefreshRate={initialRefreshRate}
1071
- dotCount={dotCount}
1072
- dotSetCount={dotSetCount}
1073
- direction={direction}
1074
- coherence={coherence}
1075
- opposite={opposite}
1076
- speed={speed}
1077
- dotLifetime={dotLifetime}
1078
- updateRate={updateRate}
1079
- dotRadius={dotRadius}
1080
- dotCharacter={dotCharacter}
1081
- dotColor={dotColor}
1082
- coherentDotColor={coherentDotColor}
1083
- backgroundColor={backgroundColor}
1084
- apertureShape={apertureShape}
1085
- apertureWidth={apertureWidth}
1086
- apertureHeight={apertureHeight}
1087
- apertureCenterX={apertureCenterX}
1088
- apertureCenterY={apertureCenterY}
1089
- reinsertMode={reinsertMode}
1090
- noiseMovement={noiseMovement}
1091
- reassignEveryMs={reassignEveryMs}
1092
- showFixation={showFixation}
1093
- fixationWidth={fixationWidth}
1094
- fixationHeight={fixationHeight}
1095
- fixationColor={fixationColor}
1096
- fixationThickness={fixationThickness}
1097
- showBorder={showBorder}
1098
- borderWidth={borderWidth}
1099
- borderColor={borderColor}
1100
973
  />
1101
974
  {responseHint && !stimulusVisible && !response && (
1102
975
  <div
@@ -1117,3 +990,68 @@ export const RandomDotKinematogram = (rawProps: RDKProps) => {
1117
990
  </div>
1118
991
  );
1119
992
  };
993
+
994
+ export const RandomDotKinematogram = defineComponent({
995
+ name: 'RandomDotKinematogram',
996
+ component: RandomDotKinematogramComponent,
997
+ csv: 'rdk',
998
+ simulate: ({ props, simulators, participant }) => {
999
+ const merged: any = { ...RDK_DEFAULTS, ...props };
1000
+ const result = simulators.respond({ props: merged, participant });
1001
+ const { reactionTimeMs: rt, key } = result.value;
1002
+
1003
+ const preTrialDuration = merged.preTrialMessage?.durationMs ?? 0;
1004
+ const elapsed = merged.responseEndsTrial && rt != null ? rt : merged.timeLimitMs;
1005
+
1006
+ const correct = isCorrect(key, merged.correctResponse);
1007
+
1008
+ let totalDuration = preTrialDuration + merged.fixationTimeMs + elapsed;
1009
+
1010
+ const recorded: RDKResponse = {
1011
+ ...merged,
1012
+ key,
1013
+ reactionTimeMs: rt,
1014
+ correct,
1015
+ framesDisplayed: 0,
1016
+ measuredRefreshRate: null,
1017
+ feedbackShown: null as string | null,
1018
+ feedbackDurationMs: null as number | null,
1019
+ };
1020
+
1021
+ const shown = feedbackFor(merged.feedback, rt, correct);
1022
+ if (shown) {
1023
+ recorded.feedbackShown = shown.content;
1024
+ recorded.feedbackDurationMs = shown.durationMs;
1025
+ totalDuration += shown.durationMs;
1026
+ }
1027
+
1028
+ return {
1029
+ recorded,
1030
+ participant: result.participant,
1031
+ durationMs: totalDuration,
1032
+ };
1033
+ },
1034
+ defaultSimulators: {
1035
+ respond: ({ props }) => {
1036
+ const ddm = simulateDDMTrial({
1037
+ driftRate: { distribution: 'normal', mean: 0.005 * (props.coherence ?? RDK_DEFAULTS.coherence), sd: 0.0012 },
1038
+ boundaries: 0.75,
1039
+ startingPoint: 0,
1040
+ noiseLevel: 0.02,
1041
+ sensoryDelayMs: { distribution: 'uniform', min: 150, max: 250 },
1042
+ motorDelayMs: { distribution: 'uniform', min: 130, max: 210 },
1043
+ timeLimitMs: props.timeLimitMs ?? RDK_DEFAULTS.timeLimitMs,
1044
+ stimOffsetMs: props.displayDurationMs ?? props.timeLimitMs ?? RDK_DEFAULTS.timeLimitMs,
1045
+ postStimStrategy: { type: 'continue' },
1046
+ });
1047
+
1048
+ const allowed = props.allowedResponseKeys ?? RDK_DEFAULTS.allowedResponseKeys;
1049
+ const correct = props.correctResponse === undefined ? [] : [props.correctResponse].flat();
1050
+ // With any key allowed, the simulated participant presses the correct key, or else space
1051
+ const keys = allowed === true ? [...correct, ' '] : allowed === false ? [] : allowed;
1052
+ const key = mapDDMChoice(ddm.choice, keys, props.correctResponse);
1053
+
1054
+ return { value: { reactionTimeMs: key ? ddm.reactionTimeMs : null, key } };
1055
+ },
1056
+ },
1057
+ });