@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.
- 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 +45 -40
- 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/.playwright-mcp/console-2026-09-20T12-17-32-043Z.log +0 -1
- package/.playwright-mcp/page-2026-09-20T12-17-32-084Z.yml +0 -10
- package/.prettierrc +0 -5
- package/Dockerfile +0 -20
- package/dist/mod-BTpABl23.js +0 -87435
- package/dist/mod.d.ts +0 -947
- package/dist/reactive.es.js +0 -87
- package/dist/reactive.umd.js +0 -10255
- package/dist/style.css +0 -5
- package/dist/web-DV4cj_8Q.js +0 -435
- package/dist/web-DprbPn6i.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,238 @@
|
|
|
1
|
+
import type { ReactNode } from 'react';
|
|
2
|
+
import type { ComponentCsv, CsvTarget, SessionColumns, TrialRow } from './files';
|
|
3
|
+
import type { CheckedParams, ParamSpec, ParamValues } from './params';
|
|
4
|
+
import { type ExperimentData, rowsOf } from './rows';
|
|
5
|
+
import { report } from './development';
|
|
6
|
+
import type { Store } from './store';
|
|
7
|
+
import type { ReservedTrialName } from './columns';
|
|
8
|
+
import { type TimelineContext, type ContextArg, makeTrial, type Trial, type TrialName } from './timeline';
|
|
9
|
+
|
|
10
|
+
export type ParticipantState = Record<string, any>;
|
|
11
|
+
|
|
12
|
+
/** Props the runner passes to every component. `R` is the type of what the component records with `next`. */
|
|
13
|
+
export interface BaseComponentProps<R = unknown> {
|
|
14
|
+
/** Ends the trial with what it recorded, which can only be left out if its type allows `undefined`. */
|
|
15
|
+
next: undefined extends R ? (data?: R) => void : (data: R) => void;
|
|
16
|
+
/** Everything recorded so far: the session, and the rows of the trials that have ended. */
|
|
17
|
+
data: ExperimentData;
|
|
18
|
+
store: Store;
|
|
19
|
+
updateStore: (mergeIn: Store) => void;
|
|
20
|
+
/** The trial's name, for naming what the component produces before its row is recorded. */
|
|
21
|
+
name?: string;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export type AnyComponent = (props: any) => ReactNode;
|
|
25
|
+
|
|
26
|
+
type PropsOf<C> = C extends (props: infer P) => any ? P : never;
|
|
27
|
+
|
|
28
|
+
/** The props a trial passes to its component: everything except what the runner provides. */
|
|
29
|
+
export type OwnProps<C> = WithoutRunnerProps<PropsOf<C>>;
|
|
30
|
+
|
|
31
|
+
// Each variant of a union of props keeps its own fields. A mapped type, which error messages print
|
|
32
|
+
// as the fields themselves
|
|
33
|
+
type WithoutRunnerProps<P> = P extends unknown
|
|
34
|
+
? { [K in keyof P as K extends keyof BaseComponentProps ? never : K]: P[K] }
|
|
35
|
+
: never;
|
|
36
|
+
|
|
37
|
+
/** What a component records with `next`. */
|
|
38
|
+
export type RecordedOf<C> =
|
|
39
|
+
PropsOf<C> extends { next: (data: infer R, ...rest: any[]) => void } ? R : unknown;
|
|
40
|
+
|
|
41
|
+
/** What a simulator receives: the trial's props, the participant, and whatever else the component's simulation passes along. */
|
|
42
|
+
export type SimulatorInput<C = any> = {
|
|
43
|
+
props: OwnProps<C>;
|
|
44
|
+
participant: ParticipantState;
|
|
45
|
+
[extra: string]: any;
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
/** A simulator's decision, as `value`. Without `participant`, the participant stays as it was. */
|
|
49
|
+
export type SimulatorResult = { value?: any; participant?: ParticipantState };
|
|
50
|
+
|
|
51
|
+
/** Decides one part of a simulated participant's behavior. */
|
|
52
|
+
export type Simulator<C = any> = (input: SimulatorInput<C>) => SimulatorResult;
|
|
53
|
+
|
|
54
|
+
/** A trial's replacement for a default simulator, which it receives to build on. */
|
|
55
|
+
export type SimulatorReplacement = (input: SimulatorInput, defaultSimulator: Simulator) => SimulatorResult;
|
|
56
|
+
|
|
57
|
+
// A replacement takes what a simulator of the component takes, along with the default simulator,
|
|
58
|
+
// returns what the default returns, and may leave the participant as it was
|
|
59
|
+
type Replacement<C, F> = F extends (...args: any[]) => infer R
|
|
60
|
+
? (
|
|
61
|
+
input: SimulatorInput<C>,
|
|
62
|
+
defaultSimulator: (input: SimulatorInput<C>) => R,
|
|
63
|
+
) => Omit<R, 'participant'> & { participant?: ParticipantState }
|
|
64
|
+
: never;
|
|
65
|
+
|
|
66
|
+
/** Replacements for some of the default simulators `D` of component `C`. */
|
|
67
|
+
export type SimulatorOverrides<C, D> = { [K in keyof D]?: Replacement<C, D[K]> };
|
|
68
|
+
|
|
69
|
+
export type SimulateResult<R = unknown> = {
|
|
70
|
+
recorded: R;
|
|
71
|
+
/** Without it, the participant stays as it was. */
|
|
72
|
+
participant?: ParticipantState;
|
|
73
|
+
durationMs?: number;
|
|
74
|
+
storeUpdates?: Record<string, any>;
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
/** What a component's simulation receives: the context of the trial, plus its props, the participant and the simulators. */
|
|
78
|
+
export type SimulateInput<C = any, S extends string = string> = TimelineContext & {
|
|
79
|
+
props: OwnProps<C>;
|
|
80
|
+
participant: ParticipantState;
|
|
81
|
+
/** The participant as the simulation started it. */
|
|
82
|
+
initialParticipant: ParticipantState;
|
|
83
|
+
simulators: Record<S, Simulator<C>>;
|
|
84
|
+
/** The components of the timeline, by name, for building the CSV files. */
|
|
85
|
+
components: ReadonlyMap<string, RuntimeComponent>;
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
export type SimulateFunction<C = any, S extends string = string> = (
|
|
89
|
+
input: SimulateInput<C, S>,
|
|
90
|
+
) => SimulateResult<RecordedOf<C>> | Promise<SimulateResult<RecordedOf<C>>>;
|
|
91
|
+
|
|
92
|
+
/** What a component's `check` sees of one of its trials when the experiment loads. */
|
|
93
|
+
export interface TrialCheck<C = any, P = {}> {
|
|
94
|
+
/** The trial's props, or `undefined` when they are computed during the run. */
|
|
95
|
+
props: OwnProps<C> | undefined;
|
|
96
|
+
/** The run's params: the experiment's, the components' and the library's. */
|
|
97
|
+
params: ParamValues<P> & Record<string, unknown>;
|
|
98
|
+
/** Every trial of the timeline, in order. */
|
|
99
|
+
trials: readonly { type: string; name?: string }[];
|
|
100
|
+
/** This trial's position in `trials`. */
|
|
101
|
+
index: number;
|
|
102
|
+
/**
|
|
103
|
+
* Whether this is a production build. A check for what only the real link provides, such as a
|
|
104
|
+
* URL param, can leave development and simulation alone.
|
|
105
|
+
*/
|
|
106
|
+
production: boolean;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export interface ComponentInfo {
|
|
110
|
+
name: string;
|
|
111
|
+
/** The CSV files its rows go to. */
|
|
112
|
+
csv: CsvTarget[];
|
|
113
|
+
/** Its trials' columns in the session CSV, if they go there. */
|
|
114
|
+
session?: SessionColumns;
|
|
115
|
+
params: Record<string, ParamSpec>;
|
|
116
|
+
defaultSimulators: Record<string, Simulator>;
|
|
117
|
+
simulate?: SimulateFunction;
|
|
118
|
+
check?: (trial: TrialCheck) => string | undefined;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** A defined component as the runner sees it, whatever its props. */
|
|
122
|
+
export type RuntimeComponent = AnyComponent & { reactive: ComponentInfo };
|
|
123
|
+
|
|
124
|
+
type HasRequired<T> = {} extends T ? false : true;
|
|
125
|
+
|
|
126
|
+
// Props are an object, so that a name is never taken for them, even by a component without props of
|
|
127
|
+
// its own. Keyed on the component's props, which error messages name, as in TrialProps<StimulusProps>
|
|
128
|
+
type TrialProps<P> = ContextArg<WithoutRunnerProps<P> & object>;
|
|
129
|
+
|
|
130
|
+
// TypeScript reports the error of the last overload, so a name that reaches it, being taken or
|
|
131
|
+
// missing the props after it, is turned into a message about the name
|
|
132
|
+
type PropsOrName<C, P> = [P] extends [string]
|
|
133
|
+
? P extends ReservedTrialName
|
|
134
|
+
? TrialName<P>
|
|
135
|
+
: `The trial '${P & string}' needs its props after its name`
|
|
136
|
+
: TrialProps<PropsOf<C>>;
|
|
137
|
+
|
|
138
|
+
type TrialFunction<C, D, H extends string> =
|
|
139
|
+
HasRequired<OwnProps<C>> extends true
|
|
140
|
+
? {
|
|
141
|
+
<const N extends string>(name: TrialName<N>, props: TrialProps<PropsOf<C>>): Trial<C, D, H>;
|
|
142
|
+
<const P = TrialProps<PropsOf<C>>>(props: PropsOrName<C, P>): Trial<C, D, H>;
|
|
143
|
+
}
|
|
144
|
+
: {
|
|
145
|
+
<const N extends string>(name: TrialName<N>, props?: TrialProps<PropsOf<C>>): Trial<C, D, H>;
|
|
146
|
+
<const P = TrialProps<PropsOf<C>>>(props?: PropsOrName<C, P>): Trial<C, D, H>;
|
|
147
|
+
};
|
|
148
|
+
|
|
149
|
+
/** A component defined with `defineComponent`, with default simulators `D` and params `H`. */
|
|
150
|
+
export type DefinedComponent<C extends AnyComponent = AnyComponent, D = any, H extends string = string> = C & {
|
|
151
|
+
reactive: ComponentInfo;
|
|
152
|
+
trial: TrialFunction<C, D, H>;
|
|
153
|
+
/** The recorded rows of this component's trials, or of its trial named `name`, in the order they ran. */
|
|
154
|
+
getAll: (data: ExperimentData, name?: string) => TrialRow<RecordedOf<C>>[];
|
|
155
|
+
/** The latest recorded row of this component's trials, or of its trial named `name`. Stops if none has run yet. */
|
|
156
|
+
getLatest: (data: ExperimentData, name?: string) => TrialRow<RecordedOf<C>>;
|
|
157
|
+
};
|
|
158
|
+
|
|
159
|
+
export function defineComponent<
|
|
160
|
+
C extends AnyComponent,
|
|
161
|
+
S extends string = never,
|
|
162
|
+
D extends Partial<Record<S, Simulator<C>>> = {},
|
|
163
|
+
const P extends Record<string, ParamSpec> = {},
|
|
164
|
+
>(definition: {
|
|
165
|
+
/** Identifies the component in the data. Required, since function names do not survive minification. */
|
|
166
|
+
name: string;
|
|
167
|
+
component: C;
|
|
168
|
+
/**
|
|
169
|
+
* The CSV file its rows go to: one row per trial, or per item of a response that is a list.
|
|
170
|
+
* Defaults to the name in lowercase, unless the component sets `session`; `null` keeps them out of
|
|
171
|
+
* the CSVs. A map gives files the function that turns a row into the file's rows, or `true`.
|
|
172
|
+
*/
|
|
173
|
+
csv?: ComponentCsv<RecordedOf<C>>;
|
|
174
|
+
/**
|
|
175
|
+
* Puts its trials' columns in the session CSV, the single row per participant: `true` for the
|
|
176
|
+
* response's fields, or a function that returns them.
|
|
177
|
+
*/
|
|
178
|
+
session?: SessionColumns<RecordedOf<C>>;
|
|
179
|
+
/** Params it reads with `useParams`, which the settings screen lists whenever it is in the timeline. */
|
|
180
|
+
params?: CheckedParams<P>;
|
|
181
|
+
defaultSimulators?: Record<S, Simulator<C>> & D;
|
|
182
|
+
simulate?: SimulateFunction<C, S>;
|
|
183
|
+
/**
|
|
184
|
+
* Checks each of its trials when the experiment loads, and returns what is wrong with it. Any
|
|
185
|
+
* message keeps the run from starting, and the settings screen shows it.
|
|
186
|
+
*/
|
|
187
|
+
check?: (trial: TrialCheck<C, P>) => string | undefined;
|
|
188
|
+
}): DefinedComponent<C, D, keyof P & string> {
|
|
189
|
+
const { name, component, session, params = {}, simulate } = definition;
|
|
190
|
+
const csv = definition.csv !== undefined ? definition.csv : session === undefined ? name.toLowerCase() : null;
|
|
191
|
+
const files: CsvTarget[] =
|
|
192
|
+
csv === null
|
|
193
|
+
? []
|
|
194
|
+
: typeof csv === 'string'
|
|
195
|
+
? [{ file: csv }]
|
|
196
|
+
: Object.entries(csv).map(([file, flatten]) => (flatten === true ? { file } : { file, flatten }));
|
|
197
|
+
if (files.some((target) => target.file === 'session')) {
|
|
198
|
+
throw new Error(
|
|
199
|
+
`${name} cannot write a CSV file named 'session', which is the session CSV. To put its trials' columns in the session row, give it session: true.`,
|
|
200
|
+
);
|
|
201
|
+
}
|
|
202
|
+
// A hot reload can run a definition again with the same function and name
|
|
203
|
+
const previous = (component as { reactive?: ComponentInfo }).reactive;
|
|
204
|
+
if (previous && previous.name !== name) {
|
|
205
|
+
throw new Error(
|
|
206
|
+
`The components '${previous.name}' and '${name}' are defined with the same function, so their trials could not be told apart. Give one of them a function of its own that renders the shared one.`,
|
|
207
|
+
);
|
|
208
|
+
}
|
|
209
|
+
const defined = component as DefinedComponent<C, D, keyof P & string>;
|
|
210
|
+
defined.reactive = {
|
|
211
|
+
name,
|
|
212
|
+
csv: files,
|
|
213
|
+
session: session as SessionColumns | undefined,
|
|
214
|
+
params: params as Record<string, ParamSpec>,
|
|
215
|
+
defaultSimulators: (definition.defaultSimulators ?? {}) as Record<string, Simulator>,
|
|
216
|
+
simulate: simulate as SimulateFunction | undefined,
|
|
217
|
+
check: definition.check as ComponentInfo['check'],
|
|
218
|
+
};
|
|
219
|
+
defined.getAll = (data, trialName) => rowsOf(name, data, trialName);
|
|
220
|
+
// For real participants, report only logs, and a trial that has not run reads as undefined
|
|
221
|
+
defined.getLatest = (data, trialName) =>
|
|
222
|
+
(rowsOf(name, data, trialName).at(-1) ??
|
|
223
|
+
report(
|
|
224
|
+
trialName === undefined
|
|
225
|
+
? `No ${name} trial has run yet. For trials that may not have run, ${name}.getAll(data).at(-1) is undefined until one has.`
|
|
226
|
+
: `The ${name} trial '${trialName}' has not run yet. For a trial that may not have run, ${name}.getAll(data, '${trialName}').at(-1) is undefined until it has.`,
|
|
227
|
+
)) as TrialRow<RecordedOf<C>>;
|
|
228
|
+
defined.trial = ((first?: unknown, second?: unknown) => {
|
|
229
|
+
const named = typeof first === 'string';
|
|
230
|
+
const props = (named ? second : first) as ContextArg<Record<string, any>> | undefined;
|
|
231
|
+
return makeTrial({
|
|
232
|
+
component: defined,
|
|
233
|
+
name: named ? first : undefined,
|
|
234
|
+
props: props ?? {},
|
|
235
|
+
});
|
|
236
|
+
}) as TrialFunction<C, D, keyof P & string>;
|
|
237
|
+
return defined;
|
|
238
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
export function isProduction(): boolean {
|
|
2
|
+
// Builds replace process.env.NODE_ENV; in a browser without a replacement, process does not exist
|
|
3
|
+
try {
|
|
4
|
+
return process.env.NODE_ENV === 'production';
|
|
5
|
+
} catch {
|
|
6
|
+
return false;
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/** A mistake in the experiment stops it during development and simulation, but only logs for real participants. */
|
|
11
|
+
export function report(message: string): undefined {
|
|
12
|
+
if (isProduction()) {
|
|
13
|
+
console.error(message);
|
|
14
|
+
return undefined;
|
|
15
|
+
}
|
|
16
|
+
throw new Error(message);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function deepFreeze(value: unknown): void {
|
|
20
|
+
if (typeof value !== 'object' || value === null || Object.isFrozen(value)) return;
|
|
21
|
+
const prototype = Object.getPrototypeOf(value);
|
|
22
|
+
// Class instances such as Blobs or typed arrays are left alone
|
|
23
|
+
if (!Array.isArray(value) && prototype !== Object.prototype && prototype !== null) return;
|
|
24
|
+
Object.freeze(value);
|
|
25
|
+
for (const child of Object.values(value)) deepFreeze(child);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Freezes the data and store that timeline callbacks read, so that mutating them throws during development and simulation. */
|
|
29
|
+
export function freezeInDevelopment<T>(value: T): T {
|
|
30
|
+
if (!isProduction()) deepFreeze(value);
|
|
31
|
+
return value;
|
|
32
|
+
}
|
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
// Timelines use the array methods, such as .shuffle(), so they are added wherever one is built
|
|
2
|
+
import '../utils/array';
|
|
3
|
+
import type { Theme } from '../runner/theme';
|
|
4
|
+
import { withSeed } from '../utils/distributions';
|
|
5
|
+
import { advanceToNextContent } from './bytecode';
|
|
6
|
+
import { isReservedParamName, sessionColumns, sessionPrefixes } from './columns';
|
|
7
|
+
import { freezeInDevelopment, isProduction } from './development';
|
|
8
|
+
import { type CheckedParams, libraryParams, type ParamSpec, type ParamValues, resolveParams } from './params';
|
|
9
|
+
import { createTrialRow, type ExperimentData } from './rows';
|
|
10
|
+
import type { RunSimulationConfig } from './simulation';
|
|
11
|
+
import type { Store } from './store';
|
|
12
|
+
import {
|
|
13
|
+
type CompiledTimeline,
|
|
14
|
+
compileExperimentTimeline,
|
|
15
|
+
createTimelineContext,
|
|
16
|
+
describeTimeline,
|
|
17
|
+
excludeEntries,
|
|
18
|
+
itemsOf,
|
|
19
|
+
resolve,
|
|
20
|
+
type Timeline,
|
|
21
|
+
type TrialContent,
|
|
22
|
+
} from './timeline';
|
|
23
|
+
|
|
24
|
+
// --- Definition ---
|
|
25
|
+
|
|
26
|
+
export interface ExperimentConfig {
|
|
27
|
+
showProgressBar?: boolean;
|
|
28
|
+
theme?: Theme;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface Experiment<Params extends Record<string, ParamSpec> = Record<string, ParamSpec>> {
|
|
32
|
+
/** The experiment's inputs, read from the URL. */
|
|
33
|
+
params?: Params;
|
|
34
|
+
/** The trials, or a function that builds them from the params once per participant. */
|
|
35
|
+
timeline: Timeline | ((params: ParamValues<Params>) => Timeline);
|
|
36
|
+
config?: ExperimentConfig;
|
|
37
|
+
simulation?: RunSimulationConfig;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function defineExperiment<const Params extends Record<string, ParamSpec> = {}>(
|
|
41
|
+
experiment: Omit<Experiment<Params>, 'params'> & { params?: CheckedParams<Params> },
|
|
42
|
+
): Experiment<Params> {
|
|
43
|
+
// The checked params are the declared ones, which the types only compare against what they allow
|
|
44
|
+
return experiment as Experiment<Params>;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// --- Runs ---
|
|
48
|
+
|
|
49
|
+
export interface Run {
|
|
50
|
+
/** The values of every param: the experiment's, those of the components in its timeline, and the library's. */
|
|
51
|
+
params: Record<string, unknown>;
|
|
52
|
+
/** Seeds the random draws made while the timeline is built, so that a rebuild repeats them. */
|
|
53
|
+
buildSeed: number;
|
|
54
|
+
compiled: CompiledTimeline;
|
|
55
|
+
/** Every param of the run as declared, for recording them. */
|
|
56
|
+
specs: Record<string, ParamSpec>;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** What a run keeps across hot reloads, so that the rebuilt timeline matches the one the participant is in. */
|
|
60
|
+
export type KeptRun = Pick<Run, 'params' | 'buildSeed'>;
|
|
61
|
+
|
|
62
|
+
/** Builds the timeline for the experiment's params and returns its top-level entries, with nested lists flattened. */
|
|
63
|
+
export function buildTimeline(
|
|
64
|
+
experiment: Experiment<any>,
|
|
65
|
+
params: Record<string, unknown>,
|
|
66
|
+
buildSeed: number,
|
|
67
|
+
): Timeline {
|
|
68
|
+
const timeline = withSeed(buildSeed, () =>
|
|
69
|
+
typeof experiment.timeline === 'function' ? experiment.timeline(params) : experiment.timeline,
|
|
70
|
+
);
|
|
71
|
+
return itemsOf(timeline) as Timeline;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* The params of the components in the timeline, the component that declares each, and which of
|
|
76
|
+
* them some trial shows on the settings screen.
|
|
77
|
+
*/
|
|
78
|
+
export function componentParams(compiled: CompiledTimeline) {
|
|
79
|
+
const specs: Record<string, ParamSpec> = {};
|
|
80
|
+
const owners: Record<string, string> = {};
|
|
81
|
+
const shown = new Set<string>();
|
|
82
|
+
for (const instruction of compiled.bytecode.instructions) {
|
|
83
|
+
if (instruction.type !== 'ExecuteContent') continue;
|
|
84
|
+
const { component, hideParams } = instruction.content;
|
|
85
|
+
for (const [name, spec] of Object.entries(component.reactive.params)) {
|
|
86
|
+
specs[name] = spec;
|
|
87
|
+
owners[name] ??= component.reactive.name;
|
|
88
|
+
const hidden = hideParams === true || (Array.isArray(hideParams) && hideParams.includes(name));
|
|
89
|
+
if (!hidden) shown.add(name);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return { specs, owners, shown };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** What the components' checks find wrong with the trials, which keeps a run from starting. */
|
|
96
|
+
export function checkTrials(compiled: CompiledTimeline, params: Record<string, unknown>, production: boolean): string[] {
|
|
97
|
+
const contents = compiled.bytecode.instructions.flatMap((instruction) =>
|
|
98
|
+
instruction.type === 'ExecuteContent' ? [instruction.content] : [],
|
|
99
|
+
);
|
|
100
|
+
const trials = contents.map(({ type, name }) => ({ type, name }));
|
|
101
|
+
return contents.flatMap((content, index) => {
|
|
102
|
+
const problem = content.component.reactive.check?.({
|
|
103
|
+
props: typeof content.props === 'function' ? undefined : content.props,
|
|
104
|
+
params,
|
|
105
|
+
trials,
|
|
106
|
+
index,
|
|
107
|
+
production,
|
|
108
|
+
});
|
|
109
|
+
return problem ? [problem] : [];
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// What a run and the settings screen both work out: the params, the timeline they build with the
|
|
114
|
+
// trials the URL selects, and what the components' checks find wrong with it
|
|
115
|
+
function prepareRun(
|
|
116
|
+
experiment: Experiment<any>,
|
|
117
|
+
sources: { url: Record<string, unknown>; overrides?: Record<string, unknown> },
|
|
118
|
+
previous: KeptRun | undefined,
|
|
119
|
+
) {
|
|
120
|
+
const experimentValues = resolveParams(experiment.params, { ...sources, previous: previous?.params });
|
|
121
|
+
const buildSeed = previous?.buildSeed ?? Math.floor(Math.random() * 2 ** 32);
|
|
122
|
+
const entries = buildTimeline(experiment, experimentValues, buildSeed);
|
|
123
|
+
// The settings screen's unchecked trials, which its link lists by name or position
|
|
124
|
+
const excluded = new Set(String(sources.url.excludeSubset ?? '').split(','));
|
|
125
|
+
const compiled = compileExperimentTimeline(excludeEntries(entries, excluded));
|
|
126
|
+
const components = componentParams(compiled);
|
|
127
|
+
const own = experiment.params ?? {};
|
|
128
|
+
// The library's params come first, which keeps the order of the CSV columns
|
|
129
|
+
const settings = Object.fromEntries(
|
|
130
|
+
Object.entries({ ...libraryParams, ...components.specs }).filter(([name]) => !(name in own)),
|
|
131
|
+
);
|
|
132
|
+
for (const name of Object.keys({ ...settings, ...own })) {
|
|
133
|
+
if (isReservedParamName(name)) {
|
|
134
|
+
throw new Error(
|
|
135
|
+
`A param cannot be named '${name}': the session CSV keeps ${sessionColumns.join(', ')} and names starting with ${sessionPrefixes.join(' or ')} for itself.`,
|
|
136
|
+
);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
const params = { ...resolveParams(settings, { ...sources, previous: previous?.params }), ...experimentValues };
|
|
140
|
+
const run: Run = { params, buildSeed, compiled, specs: { ...settings, ...own } };
|
|
141
|
+
return { run, entries, components, problems: checkTrials(compiled, params, isProduction()) };
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* Starts a participant's run: resolves the experiment's params, builds and compiles its
|
|
146
|
+
* timeline, and resolves the params of the components in it and the library's. A run kept
|
|
147
|
+
* across a hot reload keeps its values and build seed.
|
|
148
|
+
*/
|
|
149
|
+
export function startRun(
|
|
150
|
+
experiment: Experiment<any>,
|
|
151
|
+
sources: { url: Record<string, unknown>; overrides?: Record<string, unknown> },
|
|
152
|
+
previous?: KeptRun,
|
|
153
|
+
): Run {
|
|
154
|
+
const { run, problems } = prepareRun(experiment, sources, previous);
|
|
155
|
+
if (problems.length > 0) throw new Error(`The experiment cannot start: ${problems.join(' ')}`);
|
|
156
|
+
return run;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* What the settings screen shows for the values in `url`: the top-level entries of the timeline
|
|
161
|
+
* its params build, the settings besides the experiment's own params, by whose they are (the
|
|
162
|
+
* library's under `General`, then each component's), and what would keep a run from starting. As
|
|
163
|
+
* in a run, only the components of the trials that `url` selects count. Params that `url` does not
|
|
164
|
+
* set take the values in `defaults`.
|
|
165
|
+
*/
|
|
166
|
+
export function previewTimeline(
|
|
167
|
+
experiment: Experiment<any>,
|
|
168
|
+
url: Record<string, unknown>,
|
|
169
|
+
defaults: Record<string, unknown>,
|
|
170
|
+
) {
|
|
171
|
+
const { entries, components, problems } = prepareRun(experiment, { url }, { params: defaults, buildSeed: 0 });
|
|
172
|
+
const { specs, owners, shown } = components;
|
|
173
|
+
const own = experiment.params ?? {};
|
|
174
|
+
const settings: Record<string, Record<string, ParamSpec>> = { General: {} };
|
|
175
|
+
for (const [name, spec] of Object.entries(libraryParams)) {
|
|
176
|
+
if (!(name in own)) settings.General[name] = spec;
|
|
177
|
+
}
|
|
178
|
+
for (const name of shown) {
|
|
179
|
+
if (!(name in own)) settings[owners[name]] = { ...settings[owners[name]], [name]: specs[name] };
|
|
180
|
+
}
|
|
181
|
+
return { entries: describeTimeline(entries), settings, problems };
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// --- Steps ---
|
|
185
|
+
|
|
186
|
+
/** Where a participant is in their run, and what they have done so far. */
|
|
187
|
+
export interface RunState {
|
|
188
|
+
/** The instruction of the trial on screen, or the length of the bytecode once the run is finished. */
|
|
189
|
+
pointer: number;
|
|
190
|
+
/** Everything recorded so far: the session, and the rows of the trials that have ended. */
|
|
191
|
+
data: ExperimentData;
|
|
192
|
+
store: Store;
|
|
193
|
+
/** The props of the trial on screen, resolved once when it started. */
|
|
194
|
+
props: Record<string, any>;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** The trial at `pointer`, or `undefined` once the run is finished. */
|
|
198
|
+
export function trialAt(compiled: CompiledTimeline, pointer: number): TrialContent | undefined {
|
|
199
|
+
const instruction = compiled.bytecode.instructions[pointer];
|
|
200
|
+
return instruction?.type === 'ExecuteContent' ? instruction.content : undefined;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// Runs control flow from `from` up to the next trial and resolves that trial's props
|
|
204
|
+
function advance(compiled: CompiledTimeline, data: ExperimentData, fromStore: Store, from: number): RunState {
|
|
205
|
+
const contextFor = (store: Store) => createTimelineContext(data, store);
|
|
206
|
+
const { pointer, store } = advanceToNextContent(compiled.bytecode, from, fromStore, contextFor);
|
|
207
|
+
const trial = trialAt(compiled, pointer);
|
|
208
|
+
return { pointer, data, store, props: trial ? resolve(trial.props, contextFor(store)) : {} };
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** The state a run starts in, with its first trial on screen. */
|
|
212
|
+
export function createRunState(compiled: CompiledTimeline, data: ExperimentData, store: Store): RunState {
|
|
213
|
+
return advance(compiled, freezeInDevelopment(data), freezeInDevelopment(store), 0);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* Ends the trial on screen: merges the changes it made to the store, records its response, and
|
|
218
|
+
* moves on to the next trial.
|
|
219
|
+
*/
|
|
220
|
+
export function respond(
|
|
221
|
+
compiled: CompiledTimeline,
|
|
222
|
+
state: RunState,
|
|
223
|
+
trial: { recorded: unknown; storeUpdates?: Record<string, any>; startMs: number; endMs: number },
|
|
224
|
+
): RunState {
|
|
225
|
+
const content = trialAt(compiled, state.pointer);
|
|
226
|
+
if (!content) return state;
|
|
227
|
+
const store = freezeInDevelopment({ ...state.store, ...trial.storeUpdates });
|
|
228
|
+
const row = createTrialRow(
|
|
229
|
+
content,
|
|
230
|
+
{
|
|
231
|
+
trialNumber: state.data.trials.length + 1,
|
|
232
|
+
startMs: trial.startMs,
|
|
233
|
+
endMs: trial.endMs,
|
|
234
|
+
recorded: trial.recorded,
|
|
235
|
+
},
|
|
236
|
+
createTimelineContext(state.data, store),
|
|
237
|
+
);
|
|
238
|
+
const data = { ...state.data, trials: [...state.data.trials, row] };
|
|
239
|
+
return advance(compiled, freezeInDevelopment(data), store, state.pointer + 1);
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/**
|
|
243
|
+
* After a hot reload, finds the trial that was on screen in the rebuilt timeline: the nearest
|
|
244
|
+
* trial with the same component and name, or else the next trial from the same position on.
|
|
245
|
+
*/
|
|
246
|
+
export function realign(previous: CompiledTimeline, compiled: CompiledTimeline, state: RunState): RunState {
|
|
247
|
+
const shown = trialAt(previous, state.pointer);
|
|
248
|
+
const { instructions } = compiled.bytecode;
|
|
249
|
+
let best = -1;
|
|
250
|
+
if (shown?.name !== undefined) {
|
|
251
|
+
instructions.forEach((instruction, index) => {
|
|
252
|
+
const same =
|
|
253
|
+
instruction.type === 'ExecuteContent' &&
|
|
254
|
+
instruction.content.type === shown.type &&
|
|
255
|
+
instruction.content.name === shown.name;
|
|
256
|
+
if (same && (best === -1 || Math.abs(index - state.pointer) < Math.abs(best - state.pointer))) best = index;
|
|
257
|
+
});
|
|
258
|
+
}
|
|
259
|
+
const from = best !== -1 ? best : Math.min(state.pointer, instructions.length);
|
|
260
|
+
// The edited timeline can name other trials, which getAll and getLatest check against
|
|
261
|
+
const data = { ...state.data, session: { ...state.data.session, namedTrials: compiled.namedTrials } };
|
|
262
|
+
return advance(compiled, freezeInDevelopment(data), state.store, from);
|
|
263
|
+
}
|