@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
@@ -25,8 +25,8 @@ declare global {
25
25
  pipe<U>(fn: (arr: Array<T>) => U): U;
26
26
 
27
27
  /**
28
- * Splits array into chunks
29
- * @param n Number of chunks to create
28
+ * Splits array into chunks of n items; the last chunk holds what is left
29
+ * @param n Number of items per chunk
30
30
  */
31
31
  chunk(n: number): Array<Array<T>>;
32
32
 
@@ -82,20 +82,10 @@ export function shuffle<T>(array: T[]): T[] {
82
82
  }
83
83
 
84
84
  /**
85
- * Applies a function to an array
86
- */
87
- export function pipe<T, U>(array: T[], fn: (arr: T[]) => U): U {
88
- return fn(array);
89
- }
90
-
91
- /**
92
- * Splits array into chunks
85
+ * Splits array into chunks of n items; the last chunk holds what is left
93
86
  */
94
87
  export function chunk<T>(array: T[], n: number): T[][] {
95
- const size = Math.ceil(array.length / n);
96
- return Array.from({ length: Math.ceil(array.length / size) }, (_, i) =>
97
- array.slice(i * size, i * size + size),
98
- );
88
+ return Array.from({ length: Math.ceil(array.length / n) }, (_, i) => array.slice(i * n, i * n + n));
99
89
  }
100
90
 
101
91
  /**
@@ -113,53 +103,31 @@ export function sum(array: number[]): number {
113
103
  return array.reduce((a, b) => a + b, 0);
114
104
  }
115
105
 
116
- /**
117
- * Registers array methods on the Array prototype.
118
- * Call this function once to make array methods available globally.
119
- *
120
- * Example:
121
- * ```
122
- * import { registerArrayExtensions } from '@adriansteffan/reactive/array';
123
- * registerArrayExtensions();
124
- *
125
- * const myArray = [1, 2, 3, 4, 5];
126
- * myArray.shuffle();
127
- * ```
128
- */
129
- export function registerArrayExtensions(): void {
130
- if (typeof Array.prototype.sample !== 'function') {
131
- Array.prototype.sample = function <T>(this: T[], n?: number, options?: SampleOptions): T[] {
132
- return sample(this, n, options);
133
- };
134
- }
135
-
136
- if (typeof Array.prototype.shuffle !== 'function') {
137
- Array.prototype.shuffle = function <T>(this: T[]): T[] {
138
- return shuffle(this);
139
- };
140
- }
141
-
142
- if (typeof Array.prototype.pipe !== 'function') {
143
- Array.prototype.pipe = function <T, U>(this: T[], fn: (arr: T[]) => U): U {
144
- return pipe(this, fn);
145
- };
146
- }
147
-
148
- if (typeof Array.prototype.mean !== 'function') {
149
- Array.prototype.mean = function (this: number[]): number {
150
- return mean(this);
151
- };
152
- }
153
-
154
- if (typeof Array.prototype.sum !== 'function') {
155
- Array.prototype.sum = function (this: number[]): number {
156
- return sum(this);
157
- };
158
- }
106
+ const methods = {
107
+ sample(this: unknown[], n?: number, options?: SampleOptions) {
108
+ return sample(this, n, options);
109
+ },
110
+ shuffle(this: unknown[]) {
111
+ return shuffle(this);
112
+ },
113
+ pipe(this: unknown[], fn: (arr: unknown[]) => unknown) {
114
+ return fn(this);
115
+ },
116
+ chunk(this: unknown[], n: number) {
117
+ return chunk(this, n);
118
+ },
119
+ mean(this: number[]) {
120
+ return mean(this);
121
+ },
122
+ sum(this: number[]) {
123
+ return sum(this);
124
+ },
125
+ };
159
126
 
160
- if (typeof Array.prototype.chunk !== 'function') {
161
- Array.prototype.chunk = function <T>(this: T[], n: number): T[][] {
162
- return chunk(this, n);
163
- };
127
+ // Added to every array when the library loads. They are not enumerable, so that for...in over an
128
+ // array does not list them, and a built-in method of the same name is left in place.
129
+ for (const [name, method] of Object.entries(methods)) {
130
+ if (!(name in Array.prototype)) {
131
+ Object.defineProperty(Array.prototype, name, { value: method, writable: true, configurable: true });
164
132
  }
165
- }
133
+ }
@@ -0,0 +1,66 @@
1
+ import { isFullscreen } from './fullscreen';
2
+
3
+ /** Pixels, a share of the screen (`'80%'`), or a ratio to the other side (`'16:9'`). */
4
+ export type CanvasSize = number | `${number}%` | `${number}:${number}`;
5
+
6
+ /** Draws on a canvas whose size, in CSS pixels, is `width` by `height`. */
7
+ export type Draw = (ctx: CanvasRenderingContext2D, width: number, height: number) => void;
8
+
9
+ /**
10
+ * The canvas's size in CSS pixels on a screen of the given size. A number is pixels, and a percentage
11
+ * is a share of the screen. A ratio such as `'16:9'` is width to height: it sets one side from the
12
+ * other, or without the other, makes the largest canvas of that shape that fits the screen. Without
13
+ * any, the canvas is the largest square that fits.
14
+ */
15
+ export function canvasSize(
16
+ width: CanvasSize | undefined,
17
+ height: CanvasSize | undefined,
18
+ screenWidth: number,
19
+ screenHeight: number,
20
+ ) {
21
+ const pixels = (size: CanvasSize | undefined, screen: number) =>
22
+ typeof size === 'number' ? size : size?.endsWith('%') ? (screen * Number.parseFloat(size)) / 100 : undefined;
23
+ const ratio = (size: CanvasSize | undefined) => {
24
+ if (typeof size !== 'string' || !size.includes(':')) return undefined;
25
+ const [w, h] = size.split(':').map(Number);
26
+ return w / h;
27
+ };
28
+ let w = pixels(width, screenWidth);
29
+ let h = pixels(height, screenHeight);
30
+ const shape = ratio(width) ?? ratio(height);
31
+ if (shape === undefined) {
32
+ w ??= h ?? Math.min(screenWidth, screenHeight);
33
+ h ??= w;
34
+ } else if (w !== undefined) {
35
+ h = w / shape;
36
+ } else if (h !== undefined) {
37
+ w = h * shape;
38
+ } else {
39
+ w = Math.min(screenWidth, screenHeight * shape);
40
+ h = w / shape;
41
+ }
42
+ return { width: Math.round(w), height: Math.round(h) };
43
+ }
44
+
45
+ /**
46
+ * Sizes the canvas for the screen, or the whole display in fullscreen, at the display's pixel
47
+ * density, so that drawing uses CSS pixels. Undefined where the browser has no 2D canvas.
48
+ */
49
+ export function prepareCanvas(canvas: HTMLCanvasElement, width: CanvasSize | undefined, height: CanvasSize | undefined) {
50
+ const ctx = canvas.getContext('2d');
51
+ if (!ctx) return undefined;
52
+ const fullscreen = isFullscreen();
53
+ const size = canvasSize(
54
+ width,
55
+ height,
56
+ fullscreen ? window.screen.width : window.innerWidth,
57
+ fullscreen ? window.screen.height : window.innerHeight,
58
+ );
59
+ const dpr = window.devicePixelRatio || 1;
60
+ canvas.width = Math.round(size.width * dpr);
61
+ canvas.height = Math.round(size.height * dpr);
62
+ canvas.style.width = `${size.width}px`;
63
+ canvas.style.height = `${size.height}px`;
64
+ ctx.scale(dpr, dpr);
65
+ return { ctx, size };
66
+ }
package/src/utils/ddm.ts CHANGED
@@ -1,10 +1,8 @@
1
- import { normal, uniform } from './distributions';
1
+ import { type NormalSpec, normal, type UniformSpec, uniform } from './distributions';
2
2
 
3
3
  // --- Distribution & Parameter Types ---
4
4
 
5
- export type NormalDist = { type: 'normal'; mean: number; sd: number };
6
- export type UniformDist = { type: 'uniform'; min: number; max: number };
7
- export type ParameterDef = number | NormalDist | UniformDist;
5
+ export type ParameterDef = number | NormalSpec | UniformSpec;
8
6
 
9
7
  export type BoundaryDef =
10
8
  | number // Symmetric: upper is +b, lower is -b
@@ -12,24 +10,24 @@ export type BoundaryDef =
12
10
 
13
11
  export type CollapseDef = {
14
12
  rate: number; // Speed at which boundaries shrink per ms
15
- delay?: number; // Pause in ms (from phase start) before collapse begins
13
+ delayMs?: number; // Pause (from phase start) before collapse begins
16
14
  };
17
15
 
18
16
  // --- Post-Stimulus Strategy Types ---
19
17
 
20
18
  export type ContinueStrategy = {
21
19
  type: 'continue';
22
- residualDrift?: number; // Drift rate after stimOffset (Default: 0)
20
+ residualDrift?: number; // Drift rate after stimOffsetMs (Default: 0)
23
21
  noiseMultiplier?: number; // Multiplier for noiseLevel (Default: 1)
24
22
  };
25
23
 
26
24
  export type CollapseStrategy = {
27
25
  type: 'collapse';
28
- collapseDef: CollapseDef; // Takes over boundary dynamics after stimOffset
26
+ collapseDef: CollapseDef; // Takes over boundary dynamics after stimOffsetMs
29
27
  };
30
28
 
31
29
  export type SnapshotStrategy = {
32
- type: 'snapshot'; // Immediate forced choice at stimOffset
30
+ type: 'snapshot'; // Immediate forced choice at stimOffsetMs
33
31
  };
34
32
 
35
33
  export type PostStimStrategyDef = ContinueStrategy | CollapseStrategy | SnapshotStrategy;
@@ -44,11 +42,11 @@ export interface DDMTrialParams {
44
42
  noiseLevel: ParameterDef;
45
43
 
46
44
  // Timing parameters
47
- sensoryDelay?: ParameterDef; // Dead time before accumulation (ms)
48
- motorDelay?: ParameterDef; // Dead time for physical execution (ms)
49
- timeLimit: number; // Maximum allowed trial duration (ms)
50
- stimOffset: number; // Timestamp when stimulus vanishes (ms)
51
- dt?: number; // Resolution in ms (Default: 1)
45
+ sensoryDelayMs?: ParameterDef; // Dead time before accumulation
46
+ motorDelayMs?: ParameterDef; // Dead time for physical execution
47
+ timeLimitMs: number; // Maximum allowed trial duration
48
+ stimOffsetMs: number; // Timestamp when stimulus vanishes
49
+ dtMs?: number; // Resolution (Default: 1)
52
50
 
53
51
  // Global behaviors
54
52
  contaminationRate?: number; // Probability (0-1) of a random guess
@@ -62,7 +60,7 @@ export interface DDMTrialParams {
62
60
 
63
61
  export interface DDMTrialResult {
64
62
  choice: 0 | 1 | null;
65
- rt: number; // Total reaction time including delays (ms)
63
+ reactionTimeMs: number; // Total reaction time including delays
66
64
  finalEvidence: number; // Accumulator value at trial end
67
65
  isContaminated: boolean; // True if trial was a random lapse
68
66
  }
@@ -71,18 +69,20 @@ export interface DDMTrialResult {
71
69
 
72
70
  function resolveParam(def: ParameterDef): number {
73
71
  if (typeof def === 'number') return def;
74
- if (def.type === 'normal') return normal(def.mean, def.sd);
72
+ if (def.distribution === 'normal') return normal(def.mean, def.sd);
75
73
  return uniform(def.min, def.max);
76
74
  }
77
75
 
78
- function resolveParamClamped(def: ParameterDef): number {
79
- return Math.max(0, resolveParam(def));
76
+ function crossed(evidence: number, lower: number, upper: number): 0 | 1 | null {
77
+ if (evidence >= upper) return 1;
78
+ if (evidence <= lower) return 0;
79
+ return null;
80
80
  }
81
81
 
82
82
  // --- Simulation ---
83
83
 
84
84
  export function simulateDDMTrial(params: DDMTrialParams): DDMTrialResult {
85
- const dt = params.dt ?? 1;
85
+ const dt = params.dtMs ?? 1;
86
86
  const sqrtDt = Math.sqrt(dt);
87
87
 
88
88
  // A1. Resolve starting point
@@ -92,7 +92,7 @@ export function simulateDDMTrial(params: DDMTrialParams): DDMTrialResult {
92
92
  if (params.contaminationRate && uniform(0, 1) < params.contaminationRate) {
93
93
  return {
94
94
  choice: uniform(0, 1) < 0.5 ? 0 : 1,
95
- rt: uniform(0, params.timeLimit),
95
+ reactionTimeMs: uniform(0, params.timeLimitMs),
96
96
  finalEvidence: startingPoint,
97
97
  isContaminated: true,
98
98
  };
@@ -101,8 +101,8 @@ export function simulateDDMTrial(params: DDMTrialParams): DDMTrialResult {
101
101
  // A3. Resolve remaining distributions for this trial
102
102
  const baseDrift = resolveParam(params.driftRate);
103
103
  const baseNoise = Math.max(0, resolveParam(params.noiseLevel));
104
- const sensoryDelay = params.sensoryDelay != null ? resolveParamClamped(params.sensoryDelay) : 0;
105
- const motorDelay = params.motorDelay != null ? resolveParamClamped(params.motorDelay) : 0;
104
+ const sensoryDelay = Math.max(0, resolveParam(params.sensoryDelayMs ?? 0));
105
+ const motorDelay = Math.max(0, resolveParam(params.motorDelayMs ?? 0));
106
106
 
107
107
  // A4. Resolve boundaries
108
108
  let currentUpper: number;
@@ -118,21 +118,20 @@ export function simulateDDMTrial(params: DDMTrialParams): DDMTrialResult {
118
118
  // A5. Fast-forward clock past sensory delay
119
119
  let time = sensoryDelay;
120
120
  let evidence = startingPoint;
121
- let boundaryHit = false;
122
121
  let choice: 0 | 1 | null = null;
123
122
 
124
123
  // B. Simulation loop
125
- while (time < params.timeLimit) {
124
+ while (time < params.timeLimitMs) {
126
125
  time += dt;
127
126
 
128
127
  let currentDrift = baseDrift;
129
128
  let currentNoise = baseNoise;
130
129
 
131
- if (time <= params.stimOffset) {
130
+ if (time <= params.stimOffsetMs) {
132
131
  // Phase 1: Stimulus visible
133
132
  if (params.stimulusCollapse) {
134
133
  const elapsed = time - sensoryDelay;
135
- if (elapsed > (params.stimulusCollapse.delay ?? 0)) {
134
+ if (elapsed > (params.stimulusCollapse.delayMs ?? 0)) {
136
135
  currentUpper -= params.stimulusCollapse.rate * dt;
137
136
  currentLower += params.stimulusCollapse.rate * dt;
138
137
  }
@@ -145,7 +144,7 @@ export function simulateDDMTrial(params: DDMTrialParams): DDMTrialResult {
145
144
  const distToLower = Math.abs(evidence - currentLower);
146
145
  return {
147
146
  choice: distToUpper <= distToLower ? 1 : 0,
148
- rt: time + motorDelay,
147
+ reactionTimeMs: time + motorDelay,
149
148
  finalEvidence: evidence,
150
149
  isContaminated: false,
151
150
  };
@@ -155,76 +154,54 @@ export function simulateDDMTrial(params: DDMTrialParams): DDMTrialResult {
155
154
  } else {
156
155
  // collapse
157
156
  currentDrift = 0;
158
- const elapsed = time - params.stimOffset;
159
- if (elapsed > (strategy.collapseDef.delay ?? 0)) {
157
+ const elapsed = time - params.stimOffsetMs;
158
+ if (elapsed > (strategy.collapseDef.delayMs ?? 0)) {
160
159
  currentUpper -= strategy.collapseDef.rate * dt;
161
160
  currentLower += strategy.collapseDef.rate * dt;
162
161
  }
163
162
  }
164
163
  }
165
164
 
166
- // B3. Check if evidence crossed or was passed by a boundary
167
- if (evidence >= currentUpper) {
168
- choice = 1;
169
- boundaryHit = true;
170
- break;
171
- }
172
- if (evidence <= currentLower) {
173
- choice = 0;
174
- boundaryHit = true;
175
- break;
176
- }
165
+ // B3. A collapsing boundary can pass the evidence, so check before the step as well
166
+ choice = crossed(evidence, currentLower, currentUpper);
167
+ if (choice !== null) break;
177
168
 
178
169
  // B4. Step evidence
179
170
  evidence += currentDrift * dt + currentNoise * sqrtDt * normal(0, 1);
180
171
 
181
172
  // B5. Check thresholds after stepping
182
- if (evidence >= currentUpper) {
183
- choice = 1;
184
- boundaryHit = true;
185
- break;
186
- }
187
- if (evidence <= currentLower) {
188
- choice = 0;
189
- boundaryHit = true;
190
- break;
191
- }
192
- }
193
-
194
- // C. Finalize output
195
- let rt: number;
196
- if (boundaryHit) {
197
- rt = time + motorDelay;
198
- } else {
199
- // timeLimit reached; no decision made
200
- rt = params.timeLimit;
201
- choice = null;
173
+ choice = crossed(evidence, currentLower, currentUpper);
174
+ if (choice !== null) break;
202
175
  }
203
176
 
204
- return { choice, rt, finalEvidence: evidence, isContaminated: false };
177
+ // C. Without a decision, the trial ends at the time limit
178
+ return {
179
+ choice,
180
+ reactionTimeMs: choice === null ? params.timeLimitMs : time + motorDelay,
181
+ finalEvidence: evidence,
182
+ isContaminated: false,
183
+ };
205
184
  }
206
185
 
207
186
  export function mapDDMChoice(
208
187
  choice: 0 | 1 | null,
209
- validKeys: string[],
210
- correctResponse?: string | string[],
188
+ allowedResponseKeys: readonly string[],
189
+ correctResponse?: string | readonly string[],
211
190
  ): string | null {
212
- if (choice == null || validKeys.length === 0) return null;
213
- const correctKeys = Array.isArray(correctResponse)
214
- ? correctResponse.map((k) => k.toLowerCase())
215
- : correctResponse ? [correctResponse.toLowerCase()] : null;
191
+ if (choice == null || allowedResponseKeys.length === 0) return null;
192
+ const correctKeys = correctResponse === undefined ? null : [correctResponse].flat().map((k) => k.toLowerCase());
216
193
 
217
194
  if (!correctKeys) {
218
- return validKeys[Math.floor(uniform(0, validKeys.length))];
195
+ return allowedResponseKeys[Math.floor(uniform(0, allowedResponseKeys.length))];
219
196
  }
220
197
 
221
198
  if (choice === 1) {
222
- const matches = validKeys.filter((k) => correctKeys.includes(k.toLowerCase()));
199
+ const matches = allowedResponseKeys.filter((k) => correctKeys.includes(k.toLowerCase()));
223
200
  if (matches.length > 0) return matches[Math.floor(uniform(0, matches.length))];
224
201
  } else {
225
- const wrong = validKeys.filter((k) => !correctKeys.includes(k.toLowerCase()));
202
+ const wrong = allowedResponseKeys.filter((k) => !correctKeys.includes(k.toLowerCase()));
226
203
  if (wrong.length > 0) return wrong[Math.floor(uniform(0, wrong.length))];
227
204
  }
228
205
 
229
- return validKeys[Math.floor(uniform(0, validKeys.length))];
206
+ return allowedResponseKeys[Math.floor(uniform(0, allowedResponseKeys.length))];
230
207
  }