@adriansteffan/reactive 0.2.6 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +796 -229
- package/bin/add.js +56 -0
- package/bin/deploy.js +48 -0
- package/bin/download.js +28 -0
- package/bin/ghsetup.js +21 -0
- package/bin/native.js +81 -0
- package/bin/setup.js +11 -17
- package/bin/study-deploy.js +60 -0
- package/bin/undeploy.js +15 -0
- package/extras/transcription/compose.yaml +32 -0
- package/{template → extras}/transcription/transcribe.py +4 -9
- package/package.json +62 -64
- package/src/bun-env.d.ts +1 -0
- package/src/bun-plugin.ts +22 -0
- package/src/components/canvasblock.tsx +209 -537
- package/src/components/checkdevice.tsx +64 -84
- package/src/components/fullscreenblock.tsx +130 -0
- package/src/components/icons.tsx +50 -0
- package/src/components/index.ts +9 -11
- package/src/components/microphonecheck.tsx +76 -38
- package/src/components/plaininput.tsx +48 -41
- package/src/components/prolificending.tsx +64 -28
- package/src/components/quest.tsx +89 -87
- package/src/components/{randomdotkinetogram.tsx → randomdotkinematogram.tsx} +205 -267
- package/src/components/{voicerecorder.tsx → recorder.tsx} +81 -106
- package/src/components/requestfilepermission.tsx +63 -0
- package/src/components/stimulus.tsx +373 -0
- package/src/components/storeui.tsx +94 -148
- package/src/components/text.tsx +61 -59
- package/src/components/tutorial.tsx +45 -47
- package/src/components/upload.tsx +133 -309
- package/src/components/voicerecording.tsx +90 -94
- package/src/core/backend.ts +20 -0
- package/src/core/bytecode.ts +178 -0
- package/src/core/columns.ts +50 -0
- package/src/core/component.ts +238 -0
- package/src/core/development.ts +32 -0
- package/src/core/experiment.ts +263 -0
- package/src/core/files.ts +291 -0
- package/src/core/params.ts +166 -0
- package/src/core/platform.ts +29 -0
- package/src/core/rows.ts +106 -0
- package/src/core/simulation.ts +158 -0
- package/src/core/slides.ts +178 -0
- package/src/core/store.ts +22 -0
- package/src/core/timeline.ts +399 -0
- package/src/fonts/AtkinsonHyperlegible-Bold.woff2 +0 -0
- package/src/fonts/AtkinsonHyperlegible-BoldItalic.woff2 +0 -0
- package/src/fonts/AtkinsonHyperlegible-Italic.woff2 +0 -0
- package/src/fonts/AtkinsonHyperlegible-Regular.woff2 +0 -0
- package/src/index.css +5 -7
- package/src/mod.tsx +31 -17
- package/src/native.ts +127 -0
- package/src/quest.ts +2 -0
- package/src/runner/contexts.ts +35 -0
- package/src/runner/devpanel.tsx +68 -0
- package/src/runner/experimentrunner.tsx +210 -0
- package/src/runner/fullscreenguard.tsx +93 -0
- package/src/runner/paraminput.tsx +86 -0
- package/src/runner/progressbar.tsx +20 -0
- package/src/runner/settingsscreen.tsx +517 -0
- package/src/{utils → runner}/theme.ts +9 -8
- package/src/server.ts +93 -0
- package/src/tutorial.ts +3 -0
- package/src/utils/array.ts +30 -62
- package/src/utils/canvas.ts +66 -0
- package/src/utils/ddm.ts +47 -70
- package/src/utils/distributions.ts +352 -61
- package/src/utils/fullscreen.ts +38 -0
- package/src/utils/ids.ts +11 -0
- package/src/utils/keys.ts +46 -0
- package/src/utils/llm.ts +15 -15
- package/src/utils/time.ts +12 -0
- package/src/utils/tts.ts +24 -24
- package/template/.dockerignore +3 -1
- package/template/.env.example +5 -0
- package/template/.github/workflows/deploy.yml +25 -0
- package/template/.gitignore +14 -0
- package/template/Dockerfile +9 -14
- package/template/README.md +74 -214
- package/template/biome.json +34 -0
- package/template/build.ts +20 -0
- package/template/bunfig.toml +3 -0
- package/template/docker-compose.yaml +4 -33
- package/template/index.html +2 -2
- package/template/package.json +16 -89
- package/template/public/.gitkeep +0 -0
- package/template/server.ts +32 -0
- package/template/simulate.ts +4 -44
- package/template/src/Experiment.tsx +76 -128
- package/template/src/bun-env.d.ts +1 -0
- package/template/src/index.css +1 -9
- package/template/src/main.tsx +25 -10
- package/template/tsconfig.json +4 -6
- package/.claude/settings.local.json +0 -61
- package/.eslintrc.cjs +0 -18
- package/.playwright-mcp/console-2026-04-07T14-22-59-060Z.log +0 -1
- package/.prettierrc +0 -5
- package/Dockerfile +0 -20
- package/dist/mod-HDegGPrf.js +0 -87434
- package/dist/mod.d.ts +0 -946
- package/dist/reactive.es.js +0 -87
- package/dist/reactive.umd.js +0 -10255
- package/dist/style.css +0 -5
- package/dist/web-7BbR1Ad7.js +0 -435
- package/dist/web-CATfZO1Q.js +0 -12
- package/planned.md +0 -103
- package/postcss.config.js +0 -6
- package/raw-loader-hooks.mjs +0 -25
- package/raw-loader.mjs +0 -5
- package/rdk_doc.md +0 -341
- package/src/components/enterfullscreen.tsx +0 -230
- package/src/components/exitfullscreen.tsx +0 -113
- package/src/components/experimentprovider.tsx +0 -69
- package/src/components/experimentrunner.tsx +0 -497
- package/src/components/mobilefilepermission.tsx +0 -68
- package/src/components/settingsscreen.tsx +0 -770
- package/src/types/array.d.ts +0 -6
- package/src/utils/audiodevice.ts +0 -4
- package/src/utils/bytecode.ts +0 -261
- package/src/utils/common.ts +0 -291
- package/src/utils/ddm.test.ts +0 -233
- package/src/utils/distributions.test.ts +0 -209
- package/src/utils/nodecompat.ts +0 -11
- package/src/utils/overlays.ts +0 -19
- package/src/utils/request.ts +0 -25
- package/src/utils/simulation.ts +0 -299
- package/src/utils/upload.ts +0 -275
- package/src/vite-env.d.ts +0 -1
- package/template/.env.template +0 -2
- package/template/.eslintrc.cjs +0 -18
- package/template/.prettierrc +0 -5
- package/template/backend/package-lock.json +0 -2544
- package/template/backend/package.json +0 -31
- package/template/backend/src/backend.ts +0 -131
- package/template/backend/tsconfig.json +0 -110
- package/template/capacitor.config.ts +0 -15
- package/template/electron/main.js +0 -131
- package/template/electron/preload.js +0 -9
- package/template/electron.vite.config.js +0 -45
- package/template/package-lock.json +0 -12467
- package/template/postcss.config.js +0 -5
- package/template/public/Atkinson_Hyperlegible/AtkinsonHyperlegible-Bold.ttf +0 -0
- package/template/public/Atkinson_Hyperlegible/AtkinsonHyperlegible-BoldItalic.ttf +0 -0
- package/template/public/Atkinson_Hyperlegible/AtkinsonHyperlegible-Italic.ttf +0 -0
- package/template/public/Atkinson_Hyperlegible/AtkinsonHyperlegible-Regular.ttf +0 -0
- package/template/shared.vite.config.js +0 -39
- package/template/src/vite-env.d.ts +0 -2
- package/template/tsconfig.node.json +0 -12
- package/template/vite.config.js +0 -11
- package/tsconfig.json +0 -30
- package/tsconfig.node.json +0 -12
- package/vite.config.ts +0 -39
- /package/{template → extras}/transcription/Dockerfile.cpu +0 -0
- /package/{template → extras}/transcription/Dockerfile.gpu +0 -0
- /package/{template/public/Atkinson_Hyperlegible → src/fonts}/OFL.txt +0 -0
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import { countDraws, seedDistributions, withStream } from '../utils/distributions';
|
|
2
|
+
import { setBackendUrl } from './backend';
|
|
3
|
+
import type { ParticipantState, SimulateResult, SimulatorInput } from './component';
|
|
4
|
+
import { createRunState, type Experiment, respond, startRun, trialAt } from './experiment';
|
|
5
|
+
import { createExperimentData, type ExperimentData } from './rows';
|
|
6
|
+
import { createTimelineContext } from './timeline';
|
|
7
|
+
|
|
8
|
+
/** A simulation for components without a response, such as entering fullscreen. */
|
|
9
|
+
export const noopSimulate = () => ({ recorded: {} as any });
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Runs one simulated participant through the experiment. Its `params` set the experiment's
|
|
13
|
+
* params, and its `urlParams` are recorded like undeclared URL params.
|
|
14
|
+
*/
|
|
15
|
+
export async function simulateParticipant(
|
|
16
|
+
experiment: Experiment<any>,
|
|
17
|
+
participant: ParticipantState,
|
|
18
|
+
): Promise<ExperimentData> {
|
|
19
|
+
const initialParticipant = { ...participant };
|
|
20
|
+
// The participant as the trials so far have left it
|
|
21
|
+
let current = { ...participant };
|
|
22
|
+
|
|
23
|
+
const run = startRun(experiment, { url: {}, overrides: participant.params });
|
|
24
|
+
const { compiled } = run;
|
|
25
|
+
let state = createRunState(
|
|
26
|
+
compiled,
|
|
27
|
+
createExperimentData({ userAgent: 'simulated', url: participant.urlParams ?? {}, run }),
|
|
28
|
+
{},
|
|
29
|
+
);
|
|
30
|
+
let currentTime = 0;
|
|
31
|
+
|
|
32
|
+
let content = trialAt(compiled, state.pointer);
|
|
33
|
+
while (content) {
|
|
34
|
+
const { name, simulate, defaultSimulators } = content.component.reactive;
|
|
35
|
+
// The trial as errors name it, numbered as in the data
|
|
36
|
+
const trial = `${name} trial ${content.name ? `'${content.name}' ` : ''}(trial ${state.data.trials.length + 1})`;
|
|
37
|
+
if (!simulate) {
|
|
38
|
+
throw new Error(
|
|
39
|
+
`The ${trial} cannot be simulated, since ${name} has no simulation. Add a simulate function to its defineComponent call.`,
|
|
40
|
+
);
|
|
41
|
+
}
|
|
42
|
+
// A replacement receives the default it replaces; one set to undefined removes the simulator
|
|
43
|
+
const replacements = Object.fromEntries(
|
|
44
|
+
Object.entries(content.simulators ?? {}).map(([key, replacement]) => [
|
|
45
|
+
key,
|
|
46
|
+
replacement && ((input: SimulatorInput) => replacement(input, defaultSimulators?.[key])),
|
|
47
|
+
]),
|
|
48
|
+
);
|
|
49
|
+
let result: SimulateResult;
|
|
50
|
+
try {
|
|
51
|
+
result = await simulate({
|
|
52
|
+
...createTimelineContext(state.data, state.store),
|
|
53
|
+
props: state.props,
|
|
54
|
+
participant: current,
|
|
55
|
+
initialParticipant,
|
|
56
|
+
simulators: { ...defaultSimulators, ...replacements },
|
|
57
|
+
components: compiled.components,
|
|
58
|
+
});
|
|
59
|
+
} catch (error) {
|
|
60
|
+
throw new Error(`In the ${trial}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
61
|
+
}
|
|
62
|
+
current = result.participant ?? current;
|
|
63
|
+
|
|
64
|
+
const startMs = currentTime;
|
|
65
|
+
currentTime += result.durationMs ?? 0;
|
|
66
|
+
state = respond(compiled, state, {
|
|
67
|
+
recorded: result.recorded,
|
|
68
|
+
storeUpdates: result.storeUpdates,
|
|
69
|
+
startMs,
|
|
70
|
+
endMs: currentTime,
|
|
71
|
+
});
|
|
72
|
+
content = trialAt(compiled, state.pointer);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
return state.data;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export interface RunSimulationConfig {
|
|
79
|
+
/**
|
|
80
|
+
* Produces the simulated participants when the simulation starts. Anything drawn at random
|
|
81
|
+
* here is drawn from the simulation's seed, so the list stays the same between runs and
|
|
82
|
+
* while you edit the experiment.
|
|
83
|
+
*/
|
|
84
|
+
createParticipants: () => ParticipantState[];
|
|
85
|
+
/** Seed for reproducible simulations. The participant list and each participant draw from their own streams, derived from it. */
|
|
86
|
+
seed?: number;
|
|
87
|
+
/** How many participants are simulated at the same time. */
|
|
88
|
+
concurrency?: number;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// What a random stream is for, as part of its seed
|
|
92
|
+
const PARTICIPANT_LIST = 0;
|
|
93
|
+
const PARTICIPANT = 1;
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Simulates the experiment's participants, several at a time, and uploads their data through
|
|
97
|
+
* the backend's `routes`.
|
|
98
|
+
*/
|
|
99
|
+
export async function runSimulation(
|
|
100
|
+
loadExperiment: () => Promise<{ default: Experiment<any> }>,
|
|
101
|
+
routes: Record<string, any>,
|
|
102
|
+
): Promise<void> {
|
|
103
|
+
const [{ default: experiment }, drawsWhileLoading] = await countDraws(loadExperiment);
|
|
104
|
+
if (drawsWhileLoading > 0) {
|
|
105
|
+
console.warn(
|
|
106
|
+
`The experiment drew ${drawsWhileLoading} random number(s) while it loaded. Every simulated participant shares them, while real participants each get their own; draw them in a param default or in the timeline function instead.`,
|
|
107
|
+
);
|
|
108
|
+
}
|
|
109
|
+
const config = experiment.simulation;
|
|
110
|
+
if (!config) throw new Error('Add a simulation config to defineExperiment to simulate participants.');
|
|
111
|
+
|
|
112
|
+
const seed = config.seed ?? Math.floor(Math.random() * 2 ** 31);
|
|
113
|
+
// The list and every participant draw from streams of their own, which never overlap, also across seeds
|
|
114
|
+
seedDistributions([seed, PARTICIPANT_LIST]);
|
|
115
|
+
const participants = config.createParticipants();
|
|
116
|
+
const concurrency = config.concurrency ?? process.getBuiltinModule('os').cpus().length;
|
|
117
|
+
|
|
118
|
+
// On a free port, so that it never collides with a running dev server
|
|
119
|
+
const server = Bun.serve({ port: 0, routes });
|
|
120
|
+
setBackendUrl(`${server.url}backend`);
|
|
121
|
+
console.log(`Simulating ${participants.length} participants (concurrency: ${concurrency})...`);
|
|
122
|
+
|
|
123
|
+
let completed = 0;
|
|
124
|
+
const errors: { index: number; error: unknown }[] = [];
|
|
125
|
+
const writeProgress = () => {
|
|
126
|
+
const pct = participants.length ? Math.round((completed / participants.length) * 100) : 100;
|
|
127
|
+
const bar = '█'.repeat(Math.floor(pct / 2)) + '░'.repeat(50 - Math.floor(pct / 2));
|
|
128
|
+
process.stdout.write(`\r ${bar} ${completed}/${participants.length} (${pct}%)`);
|
|
129
|
+
};
|
|
130
|
+
writeProgress();
|
|
131
|
+
|
|
132
|
+
let nextIndex = 0;
|
|
133
|
+
const simulateNext = async (): Promise<void> => {
|
|
134
|
+
while (nextIndex < participants.length) {
|
|
135
|
+
const index = nextIndex++;
|
|
136
|
+
try {
|
|
137
|
+
await withStream([seed, PARTICIPANT, index], () => simulateParticipant(experiment, participants[index]));
|
|
138
|
+
} catch (error) {
|
|
139
|
+
errors.push({ index, error });
|
|
140
|
+
}
|
|
141
|
+
completed++;
|
|
142
|
+
writeProgress();
|
|
143
|
+
}
|
|
144
|
+
};
|
|
145
|
+
await Promise.all(Array.from({ length: Math.min(concurrency, participants.length) }, simulateNext));
|
|
146
|
+
server.stop();
|
|
147
|
+
process.stdout.write('\n');
|
|
148
|
+
|
|
149
|
+
if (errors.length > 0) {
|
|
150
|
+
console.error(`\n${errors.length} participant(s) failed:`);
|
|
151
|
+
for (const { index, error } of errors) {
|
|
152
|
+
console.error(` Participant ${index}:`, error);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
console.log(
|
|
156
|
+
`Simulation complete. ${completed - errors.length}/${participants.length} participants simulated successfully.`,
|
|
157
|
+
);
|
|
158
|
+
}
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
import { advanceToNextContent, type Bytecode, compileTimeline } from './bytecode';
|
|
2
|
+
import type { ParticipantState } from './component';
|
|
3
|
+
import { freezeInDevelopment, report } from './development';
|
|
4
|
+
import type { Store } from './store';
|
|
5
|
+
import type { ResponseKey } from '../utils/keys';
|
|
6
|
+
import type { Block, TimelineContext } from './timeline';
|
|
7
|
+
|
|
8
|
+
export type SlideSimulatorResult = {
|
|
9
|
+
/** The key pressed, or on a slide that takes clicks the point clicked, and when; nulls for no response. */
|
|
10
|
+
value: { key?: string | null; x?: number; y?: number; reactionTimeMs: number | null };
|
|
11
|
+
/** Without it, the participant stays as it was. */
|
|
12
|
+
participant?: ParticipantState;
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
/** A response a slide records by its name, given by its key. */
|
|
16
|
+
export type SlideChoice = { key: ResponseKey };
|
|
17
|
+
|
|
18
|
+
interface SlideResponseFields {
|
|
19
|
+
/** The keys that count as a response, letters in either case, or `true` for any key. */
|
|
20
|
+
keys?: readonly ResponseKey[] | true;
|
|
21
|
+
/** Responses recorded by their names, each given by its key, such as keys counterbalanced across participants. */
|
|
22
|
+
choices?: Record<string, SlideChoice>;
|
|
23
|
+
/** Takes a click on the canvas as a response, recorded as its `x` and `y` in the coordinates `draw` uses. */
|
|
24
|
+
click?: boolean;
|
|
25
|
+
/** How long after the slide appears a key counts as a response. The slide ends then, if no response has ended it. */
|
|
26
|
+
timeLimitMs?: number;
|
|
27
|
+
/** Whether the first response ends the slide. Defaults to `true`. */
|
|
28
|
+
endsSlide?: boolean;
|
|
29
|
+
/** Clears the drawing at the first response. */
|
|
30
|
+
hidesDrawing?: boolean;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** What a slide takes as a response, keys, choices or a click, and what the first response does. */
|
|
34
|
+
export type SlideResponse = SlideResponseFields &
|
|
35
|
+
({ keys: readonly ResponseKey[] | true } | { choices: Record<string, SlideChoice> } | { click: true });
|
|
36
|
+
|
|
37
|
+
interface SlideFields {
|
|
38
|
+
/** Draws the slide on a canvas cleared to white, with black as the fill color unless the block's `styleCanvas` sets another. */
|
|
39
|
+
draw: (ctx: CanvasRenderingContext2D, width: number, height: number) => void;
|
|
40
|
+
/** How long the drawing stays visible. Unless the response has a time limit, the slide ends then. */
|
|
41
|
+
displayDurationMs?: number;
|
|
42
|
+
response?: SlideResponse;
|
|
43
|
+
/** Records no row for the slide. */
|
|
44
|
+
ignoreData?: boolean;
|
|
45
|
+
/** Extra values for the slide's row, as `meta_` columns in the CSV. */
|
|
46
|
+
metadata?: Record<string, any>;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* One screen of a CanvasBlock. It ends at the first response, unless `endsSlide` is `false`. If no
|
|
51
|
+
* response ends it, it ends when the response's time limit runs out, or, without one, when the display
|
|
52
|
+
* duration does. The types require one of these ways to end.
|
|
53
|
+
*/
|
|
54
|
+
export type Slide = SlideFields &
|
|
55
|
+
(
|
|
56
|
+
| { displayDurationMs: number }
|
|
57
|
+
| { response: SlideResponse & ({ timeLimitMs: number } | { endsSlide?: true }) }
|
|
58
|
+
);
|
|
59
|
+
|
|
60
|
+
/** Makes a slide when it starts, from the context: the experiment's trials and the block's slides so far. */
|
|
61
|
+
export type SlideFunction = (context: TimelineContext) => Slide;
|
|
62
|
+
|
|
63
|
+
/** A list of slides and blocks, nested and with `false`, `null` and `undefined` skipped like a timeline. */
|
|
64
|
+
export type SlideTimeline = readonly SlideEntry[];
|
|
65
|
+
export type SlideEntry = Slide | SlideFunction | Block<'slides'> | SlideTimeline | false | null | undefined;
|
|
66
|
+
|
|
67
|
+
/** The row a slide records. */
|
|
68
|
+
export interface SlideData {
|
|
69
|
+
/** The order in which the participant saw the slide, from 1, counting the slides that record no row. */
|
|
70
|
+
slideNumber: number;
|
|
71
|
+
startMs: number;
|
|
72
|
+
endMs: number;
|
|
73
|
+
durationMs: number;
|
|
74
|
+
/** On a slide with choices: the name of the choice the response gave. */
|
|
75
|
+
response?: string | null;
|
|
76
|
+
key: string | null;
|
|
77
|
+
/** On a slide that takes clicks: where the click landed, in the coordinates `draw` uses. */
|
|
78
|
+
x?: number | null;
|
|
79
|
+
y?: number | null;
|
|
80
|
+
reactionTimeMs: number | null;
|
|
81
|
+
/** Set with the slide's `metadata`. */
|
|
82
|
+
metadata?: Record<string, any>;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export type CompiledSlides = Bytecode<Slide | SlideFunction>;
|
|
86
|
+
|
|
87
|
+
export function compileSlides(timeline: SlideTimeline): CompiledSlides {
|
|
88
|
+
return compileTimeline(timeline, (item) => {
|
|
89
|
+
if (typeof item === 'function' || typeof (item as Partial<Slide>)?.draw === 'function') {
|
|
90
|
+
return item as Slide | SlideFunction;
|
|
91
|
+
}
|
|
92
|
+
throw new Error(
|
|
93
|
+
`A CanvasBlock's timeline can only hold slides, functions that make them, blocks and lists of them, but it holds ${JSON.stringify(item) ?? String(item)}.`,
|
|
94
|
+
);
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const takesResponse = ({ response }: Slide) =>
|
|
99
|
+
response !== undefined &&
|
|
100
|
+
(response.keys === true ||
|
|
101
|
+
(response.keys?.length ?? 0) > 0 ||
|
|
102
|
+
Object.keys(response.choices ?? {}).length > 0 ||
|
|
103
|
+
response.click === true);
|
|
104
|
+
|
|
105
|
+
/** How long after it appears the slide ends, unless a response ends it first. */
|
|
106
|
+
export function slideTimeoutMs(slide: Slide): number {
|
|
107
|
+
return slide.response?.timeLimitMs ?? slide.displayDurationMs ?? Number.POSITIVE_INFINITY;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Where a CanvasBlock is: the slide on screen, made once when it started, and what the block has recorded. */
|
|
111
|
+
export interface SlideRun {
|
|
112
|
+
/** The instruction of the slide on screen, or the length of the bytecode once the block is finished. */
|
|
113
|
+
pointer: number;
|
|
114
|
+
/** The slide on screen, or `undefined` once the block is finished. */
|
|
115
|
+
slide: Slide | undefined;
|
|
116
|
+
/** How many slides the participant has seen, counting the one on screen. */
|
|
117
|
+
shown: number;
|
|
118
|
+
slides: SlideData[];
|
|
119
|
+
/** The store with the block's changes so far, which reach the experiment when the block ends. */
|
|
120
|
+
store: Store;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// Runs control flow from `from` up to the next slide and makes it
|
|
124
|
+
function advance(
|
|
125
|
+
compiled: CompiledSlides,
|
|
126
|
+
context: TimelineContext,
|
|
127
|
+
from: number,
|
|
128
|
+
slides: SlideData[],
|
|
129
|
+
fromStore: Store,
|
|
130
|
+
shown: number,
|
|
131
|
+
): SlideRun {
|
|
132
|
+
const contextFor = (store: Store): TimelineContext => ({ ...context, store, slides });
|
|
133
|
+
const { pointer, store } = advanceToNextContent(compiled, from, fromStore, contextFor);
|
|
134
|
+
const instruction = compiled.instructions[pointer];
|
|
135
|
+
if (instruction?.type !== 'ExecuteContent') return { pointer, slide: undefined, shown, slides, store };
|
|
136
|
+
|
|
137
|
+
const content = instruction.content;
|
|
138
|
+
const slide = typeof content === 'function' ? content(contextFor(store)) : content;
|
|
139
|
+
if (slideTimeoutMs(slide) === Number.POSITIVE_INFINITY && (!takesResponse(slide) || slide.response?.endsSlide === false)) {
|
|
140
|
+
report(
|
|
141
|
+
'A slide in a CanvasBlock would never end. Give it a displayDurationMs, or a response with a timeLimitMs or with keys, choices or a click that end the slide.',
|
|
142
|
+
);
|
|
143
|
+
}
|
|
144
|
+
return { pointer, slide, shown: shown + 1, slides, store };
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** Starts a CanvasBlock in the context of its trial: runs control flow up to the first slide. */
|
|
148
|
+
export function startSlides(compiled: CompiledSlides, context: TimelineContext): SlideRun {
|
|
149
|
+
return advance(compiled, context, 0, freezeInDevelopment([]), context.store, 0);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** A slide's response: the choice and the key that gave it, or the point clicked, and when. */
|
|
153
|
+
export type SlideAnswer = { response?: string; key?: string; x?: number; y?: number; reactionTimeMs: number };
|
|
154
|
+
|
|
155
|
+
/** Ends the slide on screen: records its row, unless it ignores data, and moves on to the next slide. */
|
|
156
|
+
export function endSlide(
|
|
157
|
+
compiled: CompiledSlides,
|
|
158
|
+
context: TimelineContext,
|
|
159
|
+
run: SlideRun,
|
|
160
|
+
result: { startMs: number; endMs: number; answer: SlideAnswer | undefined },
|
|
161
|
+
): SlideRun {
|
|
162
|
+
const { slide } = run;
|
|
163
|
+
if (!slide) return run;
|
|
164
|
+
const { answer } = result;
|
|
165
|
+
const row: SlideData = {
|
|
166
|
+
slideNumber: run.shown,
|
|
167
|
+
startMs: result.startMs,
|
|
168
|
+
endMs: result.endMs,
|
|
169
|
+
durationMs: result.endMs - result.startMs,
|
|
170
|
+
...(slide.response?.choices ? { response: answer?.response ?? null } : {}),
|
|
171
|
+
key: answer?.key ?? null,
|
|
172
|
+
...(slide.response?.click ? { x: answer?.x ?? null, y: answer?.y ?? null } : {}),
|
|
173
|
+
reactionTimeMs: answer?.reactionTimeMs ?? null,
|
|
174
|
+
...(slide.metadata !== undefined ? { metadata: slide.metadata } : {}),
|
|
175
|
+
};
|
|
176
|
+
const slides = slide.ignoreData ? run.slides : freezeInDevelopment([...run.slides, row]);
|
|
177
|
+
return advance(compiled, context, run.pointer + 1, slides, run.store, run.shown);
|
|
178
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The shape of the experiment's store. Projects declare it by extending this interface:
|
|
3
|
+
* `declare module '@adriansteffan/reactive' { interface ExperimentStore { bonus: number } }`
|
|
4
|
+
*/
|
|
5
|
+
// biome-ignore lint/suspicious/noEmptyInterface: projects extend it through module augmentation
|
|
6
|
+
export interface ExperimentStore {}
|
|
7
|
+
|
|
8
|
+
// Keys the library itself keeps in the store
|
|
9
|
+
interface LibraryStore {
|
|
10
|
+
__uploadId?: string;
|
|
11
|
+
__audioInputId?: string;
|
|
12
|
+
__screenRefreshRate?: number;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
type StoreDeclared = keyof ExperimentStore extends never ? false : true;
|
|
16
|
+
|
|
17
|
+
/** The store as timeline callbacks and components see it: typed once the project declares `ExperimentStore`. */
|
|
18
|
+
export type Store = StoreDeclared extends true
|
|
19
|
+
? Partial<ExperimentStore> & LibraryStore
|
|
20
|
+
: Record<string, any>;
|
|
21
|
+
|
|
22
|
+
export type StoreUpdate = StoreDeclared extends true ? Partial<ExperimentStore> : Record<string, any>;
|