@adriansteffan/reactive 0.2.7 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (158) hide show
  1. package/README.md +796 -229
  2. package/bin/add.js +56 -0
  3. package/bin/deploy.js +48 -0
  4. package/bin/download.js +28 -0
  5. package/bin/ghsetup.js +21 -0
  6. package/bin/native.js +81 -0
  7. package/bin/setup.js +11 -17
  8. package/bin/study-deploy.js +60 -0
  9. package/bin/undeploy.js +15 -0
  10. package/extras/transcription/compose.yaml +32 -0
  11. package/{template → extras}/transcription/transcribe.py +4 -9
  12. package/package.json +62 -64
  13. package/src/bun-env.d.ts +1 -0
  14. package/src/bun-plugin.ts +22 -0
  15. package/src/components/canvasblock.tsx +209 -537
  16. package/src/components/checkdevice.tsx +64 -84
  17. package/src/components/fullscreenblock.tsx +130 -0
  18. package/src/components/icons.tsx +50 -0
  19. package/src/components/index.ts +9 -11
  20. package/src/components/microphonecheck.tsx +76 -38
  21. package/src/components/plaininput.tsx +45 -40
  22. package/src/components/prolificending.tsx +64 -28
  23. package/src/components/quest.tsx +89 -87
  24. package/src/components/{randomdotkinetogram.tsx → randomdotkinematogram.tsx} +205 -267
  25. package/src/components/{voicerecorder.tsx → recorder.tsx} +81 -106
  26. package/src/components/requestfilepermission.tsx +63 -0
  27. package/src/components/stimulus.tsx +373 -0
  28. package/src/components/storeui.tsx +94 -148
  29. package/src/components/text.tsx +61 -59
  30. package/src/components/tutorial.tsx +45 -47
  31. package/src/components/upload.tsx +133 -309
  32. package/src/components/voicerecording.tsx +90 -94
  33. package/src/core/backend.ts +20 -0
  34. package/src/core/bytecode.ts +178 -0
  35. package/src/core/columns.ts +50 -0
  36. package/src/core/component.ts +238 -0
  37. package/src/core/development.ts +32 -0
  38. package/src/core/experiment.ts +263 -0
  39. package/src/core/files.ts +291 -0
  40. package/src/core/params.ts +166 -0
  41. package/src/core/platform.ts +29 -0
  42. package/src/core/rows.ts +106 -0
  43. package/src/core/simulation.ts +158 -0
  44. package/src/core/slides.ts +178 -0
  45. package/src/core/store.ts +22 -0
  46. package/src/core/timeline.ts +399 -0
  47. package/src/fonts/AtkinsonHyperlegible-Bold.woff2 +0 -0
  48. package/src/fonts/AtkinsonHyperlegible-BoldItalic.woff2 +0 -0
  49. package/src/fonts/AtkinsonHyperlegible-Italic.woff2 +0 -0
  50. package/src/fonts/AtkinsonHyperlegible-Regular.woff2 +0 -0
  51. package/src/index.css +5 -7
  52. package/src/mod.tsx +31 -17
  53. package/src/native.ts +127 -0
  54. package/src/quest.ts +2 -0
  55. package/src/runner/contexts.ts +35 -0
  56. package/src/runner/devpanel.tsx +68 -0
  57. package/src/runner/experimentrunner.tsx +210 -0
  58. package/src/runner/fullscreenguard.tsx +93 -0
  59. package/src/runner/paraminput.tsx +86 -0
  60. package/src/runner/progressbar.tsx +20 -0
  61. package/src/runner/settingsscreen.tsx +517 -0
  62. package/src/{utils → runner}/theme.ts +9 -8
  63. package/src/server.ts +93 -0
  64. package/src/tutorial.ts +3 -0
  65. package/src/utils/array.ts +30 -62
  66. package/src/utils/canvas.ts +66 -0
  67. package/src/utils/ddm.ts +47 -70
  68. package/src/utils/distributions.ts +352 -61
  69. package/src/utils/fullscreen.ts +38 -0
  70. package/src/utils/ids.ts +11 -0
  71. package/src/utils/keys.ts +46 -0
  72. package/src/utils/llm.ts +15 -15
  73. package/src/utils/time.ts +12 -0
  74. package/src/utils/tts.ts +24 -24
  75. package/template/.dockerignore +3 -1
  76. package/template/.env.example +5 -0
  77. package/template/.github/workflows/deploy.yml +25 -0
  78. package/template/.gitignore +14 -0
  79. package/template/Dockerfile +9 -14
  80. package/template/README.md +74 -214
  81. package/template/biome.json +34 -0
  82. package/template/build.ts +20 -0
  83. package/template/bunfig.toml +3 -0
  84. package/template/docker-compose.yaml +4 -33
  85. package/template/index.html +2 -2
  86. package/template/package.json +16 -89
  87. package/template/public/.gitkeep +0 -0
  88. package/template/server.ts +32 -0
  89. package/template/simulate.ts +4 -44
  90. package/template/src/Experiment.tsx +76 -128
  91. package/template/src/bun-env.d.ts +1 -0
  92. package/template/src/index.css +1 -9
  93. package/template/src/main.tsx +25 -10
  94. package/template/tsconfig.json +4 -6
  95. package/.claude/settings.local.json +0 -61
  96. package/.eslintrc.cjs +0 -18
  97. package/.playwright-mcp/console-2026-04-07T14-22-59-060Z.log +0 -1
  98. package/.playwright-mcp/console-2026-09-20T12-17-32-043Z.log +0 -1
  99. package/.playwright-mcp/page-2026-09-20T12-17-32-084Z.yml +0 -10
  100. package/.prettierrc +0 -5
  101. package/Dockerfile +0 -20
  102. package/dist/mod-BTpABl23.js +0 -87435
  103. package/dist/mod.d.ts +0 -947
  104. package/dist/reactive.es.js +0 -87
  105. package/dist/reactive.umd.js +0 -10255
  106. package/dist/style.css +0 -5
  107. package/dist/web-DV4cj_8Q.js +0 -435
  108. package/dist/web-DprbPn6i.js +0 -12
  109. package/planned.md +0 -103
  110. package/postcss.config.js +0 -6
  111. package/raw-loader-hooks.mjs +0 -25
  112. package/raw-loader.mjs +0 -5
  113. package/rdk_doc.md +0 -341
  114. package/src/components/enterfullscreen.tsx +0 -230
  115. package/src/components/exitfullscreen.tsx +0 -113
  116. package/src/components/experimentprovider.tsx +0 -69
  117. package/src/components/experimentrunner.tsx +0 -497
  118. package/src/components/mobilefilepermission.tsx +0 -68
  119. package/src/components/settingsscreen.tsx +0 -770
  120. package/src/types/array.d.ts +0 -6
  121. package/src/utils/audiodevice.ts +0 -4
  122. package/src/utils/bytecode.ts +0 -261
  123. package/src/utils/common.ts +0 -291
  124. package/src/utils/ddm.test.ts +0 -233
  125. package/src/utils/distributions.test.ts +0 -209
  126. package/src/utils/nodecompat.ts +0 -11
  127. package/src/utils/overlays.ts +0 -19
  128. package/src/utils/request.ts +0 -25
  129. package/src/utils/simulation.ts +0 -299
  130. package/src/utils/upload.ts +0 -275
  131. package/src/vite-env.d.ts +0 -1
  132. package/template/.env.template +0 -2
  133. package/template/.eslintrc.cjs +0 -18
  134. package/template/.prettierrc +0 -5
  135. package/template/backend/package-lock.json +0 -2544
  136. package/template/backend/package.json +0 -31
  137. package/template/backend/src/backend.ts +0 -131
  138. package/template/backend/tsconfig.json +0 -110
  139. package/template/capacitor.config.ts +0 -15
  140. package/template/electron/main.js +0 -131
  141. package/template/electron/preload.js +0 -9
  142. package/template/electron.vite.config.js +0 -45
  143. package/template/package-lock.json +0 -12467
  144. package/template/postcss.config.js +0 -5
  145. package/template/public/Atkinson_Hyperlegible/AtkinsonHyperlegible-Bold.ttf +0 -0
  146. package/template/public/Atkinson_Hyperlegible/AtkinsonHyperlegible-BoldItalic.ttf +0 -0
  147. package/template/public/Atkinson_Hyperlegible/AtkinsonHyperlegible-Italic.ttf +0 -0
  148. package/template/public/Atkinson_Hyperlegible/AtkinsonHyperlegible-Regular.ttf +0 -0
  149. package/template/shared.vite.config.js +0 -39
  150. package/template/src/vite-env.d.ts +0 -2
  151. package/template/tsconfig.node.json +0 -12
  152. package/template/vite.config.js +0 -11
  153. package/tsconfig.json +0 -30
  154. package/tsconfig.node.json +0 -12
  155. package/vite.config.ts +0 -39
  156. /package/{template → extras}/transcription/Dockerfile.cpu +0 -0
  157. /package/{template → extras}/transcription/Dockerfile.gpu +0 -0
  158. /package/{template/public/Atkinson_Hyperlegible → src/fonts}/OFL.txt +0 -0
@@ -1,9 +1,8 @@
1
- import { BaseComponentProps } from '../mod';
2
- import React, { useState, useEffect } from 'react';
3
- import { registerSimulation } from '../utils/simulation';
4
- import { registerFlattener } from '../utils/upload';
5
-
6
- registerFlattener('StoreUI', 'storeui');
1
+ import { BaseComponentProps } from '../core/component';
2
+ import React, { useState } from 'react';
3
+ import { defineComponent } from '../core/component';
4
+ import { t, useTheme } from '../runner/theme';
5
+ import type { ExperimentStore } from '../core/store';
7
6
 
8
7
  interface BaseFieldConfig {
9
8
  type: 'string' | 'integer' | 'float' | 'boolean';
@@ -37,7 +36,24 @@ interface BooleanFieldConfig extends BaseFieldConfig {
37
36
 
38
37
  type FieldConfig = StringFieldConfig | NumberFieldConfig | BooleanFieldConfig;
39
38
 
40
- function buildFieldValues(fields: FieldConfig[], store?: Record<string, any>): Record<string, any> {
39
+ type StoreKey = keyof ExperimentStore & string;
40
+
41
+ // The fields that can write the store key K, whose values are of type V
42
+ type FieldsFor<K extends string, V> =
43
+ | (string extends V ? StringFieldConfig & { storeKey: K } : never)
44
+ | (number extends V ? NumberFieldConfig & { storeKey: K } : never)
45
+ | (boolean extends V ? BooleanFieldConfig & { storeKey: K } : never);
46
+
47
+ /**
48
+ * A field of StoreUI. When the project declares its store (`interface ExperimentStore` in
49
+ * `declare module '@adriansteffan/reactive'`), the types check each field against it: `storeKey`
50
+ * must be one of the store's keys, and the field's `type` must fit that key's values, `'string'`
51
+ * for a string, `'integer'` or `'float'` for a number, `'boolean'` for a boolean. A key whose values
52
+ * are of another type, such as a list, takes no field. Without a declared store, any key is allowed.
53
+ */
54
+ export type StoreField = [StoreKey] extends [never] ? FieldConfig : { [K in StoreKey]: FieldsFor<K, ExperimentStore[K]> }[StoreKey];
55
+
56
+ function buildFieldValues(fields: readonly FieldConfig[], store?: Record<string, any>): Record<string, any> {
41
57
  const values: Record<string, any> = {};
42
58
  fields.forEach(field => {
43
59
  values[field.storeKey] = store?.[field.storeKey] !== undefined ? store[field.storeKey] : field.defaultValue;
@@ -45,142 +61,75 @@ function buildFieldValues(fields: FieldConfig[], store?: Record<string, any>): R
45
61
  return values;
46
62
  }
47
63
 
48
- registerSimulation('StoreUI', (trialProps, experimentState, _simulators, participant) => {
49
- const values = buildFieldValues(trialProps.fields || [], experimentState.store);
50
- return { responseData: values, participantState: participant, storeUpdates: values };
51
- }, {});
64
+ interface StoreUIProps extends BaseComponentProps<Record<string, any>> {
65
+ /** Shown above the fields. */
66
+ content?: React.ReactNode;
67
+ /** The fields, each writing its value to the store under its `storeKey`; see `StoreField` for how the types check them. */
68
+ fields: readonly StoreField[];
69
+ buttonText?: string;
70
+ }
52
71
 
53
- interface StoreUIProps extends BaseComponentProps {
54
- title?: string;
55
- description?: string;
56
- fields: FieldConfig[];
57
- saveButtonText?: string;
72
+ function validateField(field: FieldConfig, value: any): string | null {
73
+ if (field.type === 'integer' || field.type === 'float') {
74
+ if (value === undefined || value === null || value === '') {
75
+ return 'This field is required';
76
+ } else if (field.min !== undefined && value < field.min) {
77
+ return `Value must be at least ${field.min}`;
78
+ } else if (field.max !== undefined && value > field.max) {
79
+ return `Value must be at most ${field.max}`;
80
+ }
81
+ } else if (field.type === 'string') {
82
+ // A field nobody has typed in is empty
83
+ const length = (value ?? '').length;
84
+ if (field.minLength !== undefined && length < field.minLength) {
85
+ return `Must be at least ${field.minLength} characters`;
86
+ } else if (field.maxLength !== undefined && length > field.maxLength) {
87
+ return `Must be at most ${field.maxLength} characters`;
88
+ }
89
+ }
90
+
91
+ if (field.validate) {
92
+ const validationResult = field.validate(value);
93
+ if (validationResult !== true && validationResult !== '') {
94
+ return typeof validationResult === 'string'
95
+ ? validationResult
96
+ : 'Invalid value';
97
+ }
98
+ }
99
+
100
+ return null;
58
101
  }
59
102
 
60
103
  function StoreUI({
61
104
  next,
62
105
  updateStore,
63
106
  store,
64
- title = 'Settings',
65
- description,
66
- fields,
67
- saveButtonText = 'Save Configuration',
107
+ content = <h1>Settings</h1>,
108
+ fields: declaredFields,
109
+ buttonText = 'Save Configuration',
68
110
  }: StoreUIProps) {
111
+ // The fields that the store allows are a few of these; the component handles every kind
112
+ const fields: readonly FieldConfig[] = declaredFields;
113
+ const th = t(useTheme());
69
114
 
70
- const [values, setValues] = useState<Record<string, any>>({});
71
- const [errors, setErrors] = useState<Record<string, string>>({});
115
+ const [values, setValues] = useState<Record<string, any>>(() => buildFieldValues(fields, store));
72
116
  const [touched, setTouched] = useState<Record<string, boolean>>({});
73
-
74
-
75
- useEffect(() => {
76
- setValues(buildFieldValues(fields, store));
77
-
78
- const initialTouched: Record<string, boolean> = {};
79
- fields.forEach(field => {
80
- initialTouched[field.storeKey] = false;
81
- });
82
- setTouched(initialTouched);
83
- }, [store, fields]);
84
-
85
- const validateField = (field: FieldConfig, value: any): string | null => {
86
- if (field.type === 'integer' || field.type === 'float') {
87
- if (value === undefined || value === null || value === '') {
88
- return 'This field is required';
89
- } else if (field.min !== undefined && value < field.min) {
90
- return `Value must be at least ${field.min}`;
91
- } else if (field.max !== undefined && value > field.max) {
92
- return `Value must be at most ${field.max}`;
93
- }
94
- } else if (field.type === 'string') {
95
- if (field.minLength !== undefined && value.length < field.minLength) {
96
- return `Must be at least ${field.minLength} characters`;
97
- } else if (field.maxLength !== undefined && value.length > field.maxLength) {
98
- return `Must be at most ${field.maxLength} characters`;
99
- }
100
- }
101
-
102
- if (field.validate) {
103
- const validationResult = field.validate(value);
104
- if (validationResult !== true && validationResult !== '') {
105
- return typeof validationResult === 'string'
106
- ? validationResult
107
- : 'Invalid value';
108
- }
109
- }
110
-
111
- return null;
112
- };
113
-
114
- useEffect(() => {
115
- const newErrors: Record<string, string> = {};
116
-
117
- fields.forEach(field => {
118
- const value = values[field.storeKey];
119
-
120
- if (!touched[field.storeKey]) return;
121
-
122
- const error = validateField(field, value);
123
- if (error) {
124
- newErrors[field.storeKey] = error;
125
- }
126
- });
127
-
128
- setErrors(newErrors);
129
- }, [values, fields, touched]);
130
-
117
+ // A field shows its error once the participant has changed it, or tried to save
118
+ const errors = Object.fromEntries(
119
+ fields.flatMap((field) => {
120
+ const error = touched[field.storeKey] ? validateField(field, values[field.storeKey]) : null;
121
+ return error ? [[field.storeKey, error]] : [];
122
+ }),
123
+ );
124
+
131
125
  const handleChange = (storeKey: string, value: any) => {
132
- setValues(prev => ({
133
- ...prev,
134
- [storeKey]: value
135
- }));
136
-
137
- setTouched(prev => ({
138
- ...prev,
139
- [storeKey]: true
140
- }));
126
+ setValues((prev) => ({ ...prev, [storeKey]: value }));
127
+ setTouched((prev) => ({ ...prev, [storeKey]: true }));
141
128
  };
142
-
143
- const handleSave = () => {
144
- const allTouched: Record<string, boolean> = {};
145
- fields.forEach(field => {
146
- allTouched[field.storeKey] = true;
147
- });
148
- setTouched(allTouched);
149
-
150
- const newErrors: Record<string, string> = {};
151
- fields.forEach(field => {
152
- const value = values[field.storeKey];
153
-
154
129
 
155
- if (field.type === 'integer' || field.type === 'float') {
156
- if (value === undefined || value === null || value === '') {
157
- newErrors[field.storeKey] = 'This field is required';
158
- } else if (field.min !== undefined && value < field.min) {
159
- newErrors[field.storeKey] = `Value must be at least ${field.min}`;
160
- } else if (field.max !== undefined && value > field.max) {
161
- newErrors[field.storeKey] = `Value must be at most ${field.max}`;
162
- }
163
- } else if (field.type === 'string') {
164
- if (field.minLength !== undefined && value.length < field.minLength) {
165
- newErrors[field.storeKey] = `Must be at least ${field.minLength} characters`;
166
- } else if (field.maxLength !== undefined && value.length > field.maxLength) {
167
- newErrors[field.storeKey] = `Must be at most ${field.maxLength} characters`;
168
- }
169
- }
170
-
171
- if (field.validate && !newErrors[field.storeKey]) {
172
- const validationResult = field.validate(value);
173
- if (validationResult !== true && validationResult !== '') {
174
- newErrors[field.storeKey] = typeof validationResult === 'string'
175
- ? validationResult
176
- : 'Invalid value';
177
- }
178
- }
179
- });
180
-
181
- setErrors(newErrors);
182
-
183
- if (Object.keys(newErrors).length === 0) {
130
+ const handleSave = () => {
131
+ setTouched(Object.fromEntries(fields.map((field) => [field.storeKey, true])));
132
+ if (fields.every((field) => validateField(field, values[field.storeKey]) === null)) {
184
133
  updateStore(values);
185
134
  next(values);
186
135
  }
@@ -190,22 +139,14 @@ function StoreUI({
190
139
 
191
140
  return (
192
141
  <div className="max-w-prose mx-auto mt-20 mb-20 px-4">
193
- <h1 className="text-4xl font-bold mb-6">{title}</h1>
194
-
195
- {description && (
196
- <article className="prose prose-lg mb-10">
197
- {description}
198
- </article>
199
- )}
142
+ <article className={th.article}>{content}</article>
200
143
 
201
144
  <div className="mt-12 space-y-12">
202
145
  {fields.map((field) => (
203
146
  <div key={field.storeKey} className="space-y-2">
204
147
  <label className="block text-xl font-medium text-gray-900">
205
148
  {field.label}
206
- {field.type === 'integer' && field.min !== undefined && field.max !== undefined &&
207
- ` (${field.min}-${field.max})`}
208
- {field.type === 'float' && field.min !== undefined && field.max !== undefined &&
149
+ {(field.type === 'integer' || field.type === 'float') && field.min !== undefined && field.max !== undefined &&
209
150
  ` (${field.min}-${field.max})`}
210
151
  </label>
211
152
 
@@ -259,7 +200,7 @@ function StoreUI({
259
200
  value={values[field.storeKey] || ''}
260
201
  onChange={(e) => {
261
202
  const rawValue = e.target.value;
262
- let parsedValue;
203
+ let parsedValue: number | '' | undefined;
263
204
 
264
205
  if (field.type === 'integer') {
265
206
  parsedValue = rawValue === '' ? '' : parseInt(rawValue, 10);
@@ -267,13 +208,10 @@ function StoreUI({
267
208
  parsedValue = rawValue === '' ? '' : parseFloat(rawValue);
268
209
  }
269
210
 
270
- if (rawValue === '' || !isNaN(parsedValue as number)) {
211
+ if (rawValue === '' || (typeof parsedValue === 'number' && !Number.isNaN(parsedValue))) {
271
212
  handleChange(field.storeKey, parsedValue);
272
213
  }
273
214
  }}
274
- step={field.step || (field.type === 'integer' ? 1 : 0.1)}
275
- min={field.min}
276
- max={field.max}
277
215
  className="w-24 px-4 py-2 text-center border-2 border-black rounded-xl text-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
278
216
  />
279
217
 
@@ -322,13 +260,21 @@ function StoreUI({
322
260
  <button
323
261
  onClick={handleSave}
324
262
  disabled={hasErrors}
325
- className={`bg-white cursor-pointer px-8 py-3 border-2 border-black font-bold text-black text-lg rounded-xl shadow-[2px_2px_0px_rgba(0,0,0,1)] hover:translate-x-[2px] hover:translate-y-[2px] hover:shadow-none ${hasErrors ? 'opacity-50 cursor-not-allowed' : ''}`}
263
+ className={`${th.button} ${hasErrors ? 'opacity-50 cursor-not-allowed' : ''}`}
326
264
  >
327
- {saveButtonText}
265
+ {buttonText}
328
266
  </button>
329
267
  </div>
330
268
  </div>
331
269
  );
332
270
  }
333
271
 
334
- export default StoreUI;
272
+ export default defineComponent({
273
+ name: 'StoreUI',
274
+ component: StoreUI,
275
+ csv: 'storeui',
276
+ simulate: ({ props, store }) => {
277
+ const values = buildFieldValues(props.fields || [], store);
278
+ return { recorded: values, storeUpdates: values };
279
+ },
280
+ });
@@ -1,117 +1,93 @@
1
1
  import React, { useEffect, useRef } from 'react';
2
- import { BaseComponentProps, now } from '../mod';
3
- import { registerSimulation } from '../utils/simulation';
4
- import { registerFlattener } from '../utils/upload';
2
+ import { BaseComponentProps } from '../core/component';
3
+ import { type ResponseKey, responseKey } from '../utils/keys';
4
+ import { now } from '../utils/time';
5
+ import { defineComponent } from '../core/component';
5
6
  import { uniform } from '../utils/distributions';
6
- import { useTheme, t } from '../utils/theme';
7
+ import { useTheme, t } from '../runner/theme';
7
8
 
8
- registerFlattener('Text', 'text');
9
-
10
- registerSimulation('Text', (trialProps, _experimentState, simulators, participant) => {
11
- if (trialProps.duration != null) {
12
- return { responseData: {}, participantState: participant, duration: trialProps.duration };
13
- }
14
- const result = simulators.respond(trialProps, participant);
15
- return { responseData: result.value, participantState: result.participantState, duration: result.value.reactionTime };
16
- }, {
17
- respond: (_input: any, participant: any) => ({
18
- value: { key: 'button', time: Date.now(), reactionTime: uniform(500, 2000) },
19
- participantState: participant,
20
- }),
21
- });
9
+ /** Which key or the button ended the screen. Screens with a duration record nothing. */
10
+ export type TextResponse = { key?: string; reactionTimeMs?: number };
22
11
 
23
12
  function Text({
24
13
  content,
25
- buttonText = 'Continue',
14
+ buttonText,
26
15
  className = '',
27
16
  containerClass,
28
17
  centered = false,
29
18
  next,
30
19
  animate = false,
31
- allowedKeys = false,
32
- duration,
20
+ allowedResponseKeys = false,
21
+ durationMs,
33
22
  }: {
34
- content: React.ReactNode;
23
+ content?: React.ReactNode;
24
+ /** The button that ends the screen: 'Continue' unless the screen has a duration; an empty text shows none. */
35
25
  buttonText?: string;
36
- onButtonClick?: () => void;
37
26
  className?: string;
38
27
  containerClass?: string;
39
28
  centered?: boolean;
40
29
  animate?: boolean;
41
- allowedKeys?: string[] | boolean;
42
- /** Auto-advance after N ms. When set, no button is shown and key presses are ignored. */
43
- duration?: number;
44
- } & BaseComponentProps) {
30
+ /** The keys that end the screen, letters in either case, or `true` for any key. */
31
+ allowedResponseKeys?: readonly ResponseKey[] | boolean;
32
+ /** Ends the screen after this many milliseconds, unless its button or keys end it first. */
33
+ durationMs?: number;
34
+ } & Pick<BaseComponentProps<TextResponse>, 'next'>) {
45
35
  const th = t(useTheme());
46
36
  const startTimeRef = useRef<number>(0);
47
- const timed = duration != null;
48
-
49
- useEffect(() => {
50
- window.scrollTo(0, 0);
51
- }, []);
37
+ const timed = durationMs != null;
38
+ const button = buttonText ?? (timed ? '' : 'Continue');
52
39
 
53
40
  useEffect(() => {
54
41
  if (!timed) return;
55
- const timer = setTimeout(() => next({}), duration);
42
+ const timer = setTimeout(() => next({}), durationMs);
56
43
  return () => clearTimeout(timer);
57
- }, [timed, duration, next]);
44
+ }, [timed, durationMs, next]);
58
45
 
59
46
  useEffect(() => {
60
- if (timed) return;
61
47
  startTimeRef.current = now();
62
48
 
63
49
  const handleKeyPress = (event: KeyboardEvent) => {
64
50
  const keypressTime = now();
65
51
 
66
- const isKeyAllowed =
67
- allowedKeys === true || (Array.isArray(allowedKeys) && allowedKeys.includes(event.key));
68
-
69
- if (isKeyAllowed) {
52
+ const key = responseKey(allowedResponseKeys, event.key);
53
+ if (key !== undefined) {
70
54
  event.preventDefault();
71
- const reactionTime = keypressTime - startTimeRef.current;
55
+ const reactionTimeMs = keypressTime - startTimeRef.current;
72
56
 
73
- next({
74
- key: event.key,
75
- time: keypressTime,
76
- reactionTime: reactionTime,
77
- });
57
+ next({ key, reactionTimeMs });
78
58
  }
79
59
  };
80
60
 
81
- if (allowedKeys) {
61
+ if (allowedResponseKeys) {
82
62
  window.addEventListener('keydown', handleKeyPress);
83
63
  }
84
64
 
85
65
  return () => {
86
- if (allowedKeys) {
66
+ if (allowedResponseKeys) {
87
67
  window.removeEventListener('keydown', handleKeyPress);
88
68
  }
89
69
  };
90
- }, [next, allowedKeys, timed]);
70
+ }, [next, allowedResponseKeys]);
91
71
 
92
72
  const handleClick = () => {
93
73
  const clickTime = now();
94
74
 
95
- const reactionTime = clickTime - startTimeRef.current;
75
+ const reactionTimeMs = clickTime - startTimeRef.current;
96
76
 
97
- next({
98
- key: 'button',
99
- time: clickTime,
100
- reactionTime: reactionTime,
101
- });
77
+ next({ key: 'button', reactionTimeMs });
102
78
  };
103
79
 
104
80
  return (
105
81
  <div className={`min-h-screen ${centered ? 'flex items-center justify-center' : ''} ${containerClass ?? th.containerBg}`}>
106
82
  <div className={`max-w-prose mx-auto ${className} pt-20 pb-20 px-4 `}>
107
83
  <article
108
- className={`prose prose-2xl ${th.prose} text-xl ${th.proseLink} prose-a:underline prose-h1:text-4xl prose-h1:mb-10 prose-h1:font-bold prose-p:mb-4 prose-strong:font-bold ${th.text} leading-relaxed
84
+ className={`${th.article}
109
85
  ${animate ? 'animate-slide-down opacity-0' : ''}`}
110
86
  >
111
87
  {content}
112
88
  </article>
113
89
 
114
- {!timed && buttonText && (
90
+ {button && (
115
91
  <div
116
92
  className={`mt-16 flex justify-center ${animate ? 'animate-fade-in opacity-0' : ''}`}
117
93
  style={animate ? { animationDelay: '1s' } : {}}
@@ -120,9 +96,9 @@ function Text({
120
96
  onClick={handleClick}
121
97
  tabIndex={-1}
122
98
  onKeyDown={(e) => { if (e.key === ' ' || e.key === 'Enter') e.preventDefault(); }}
123
- className={`${th.buttonBg} cursor-pointer px-8 py-3 border-2 ${th.buttonBorder} font-bold ${th.buttonText} text-lg rounded-xl ${th.buttonShadow} hover:translate-x-[2px] hover:translate-y-[2px] hover:shadow-none`}
99
+ className={th.button}
124
100
  >
125
- {buttonText}
101
+ {button}
126
102
  </button>
127
103
  </div>
128
104
  )}
@@ -131,4 +107,30 @@ function Text({
131
107
  );
132
108
  }
133
109
 
134
- export default Text;
110
+ export default defineComponent({
111
+ name: 'Text',
112
+ component: Text,
113
+ csv: 'text',
114
+ simulate: ({ props, simulators, participant }) => {
115
+ const { durationMs } = props;
116
+ if (durationMs !== undefined && !props.buttonText && !props.allowedResponseKeys) {
117
+ return { recorded: {}, durationMs };
118
+ }
119
+ const result = simulators.respond({ props, participant });
120
+ const reactionTimeMs = result.value.reactionTimeMs ?? 0;
121
+ // A timed screen that the participant does not end in time ends after its duration
122
+ if (durationMs !== undefined && reactionTimeMs >= durationMs) {
123
+ return { recorded: {}, participant: result.participant, durationMs };
124
+ }
125
+ return {
126
+ recorded: result.value,
127
+ participant: result.participant,
128
+ durationMs: reactionTimeMs,
129
+ };
130
+ },
131
+ defaultSimulators: {
132
+ respond: () => ({
133
+ value: { key: 'button', reactionTimeMs: uniform(500, 2000) },
134
+ }),
135
+ },
136
+ });
@@ -1,30 +1,9 @@
1
1
  import { useState, useRef, useEffect, useCallback, useContext, createContext, ReactNode } from 'react';
2
2
  import { motion, AnimatePresence, LayoutGroup } from 'motion/react';
3
- import { BaseComponentProps } from '../mod';
4
- import { registerSimulation } from '../utils/simulation';
5
- import { registerFlattener } from '../utils/upload';
6
- import { useTheme, t } from '../utils/theme';
7
-
8
- registerFlattener('Tutorial', null);
9
-
10
- registerSimulation('Tutorial', (trialProps, _experimentState, simulators, participant) => {
11
- const slideCount = trialProps.slides?.length ?? 0;
12
- const slideData: Record<number, Record<string, unknown>> = {};
13
- let totalDuration = 0;
14
- for (let i = 0; i < slideCount; i++) {
15
- const result = simulators.respondToSlide(i, trialProps, participant);
16
- participant = result.participantState;
17
- slideData[i] = result.value ?? {};
18
- totalDuration += result.duration ?? 500;
19
- }
20
- return { responseData: { slides: slideData }, participantState: participant, duration: totalDuration };
21
- }, {
22
- respondToSlide: (_slideIndex: number, _trialProps: any, participant: any) => ({
23
- value: {},
24
- participantState: participant,
25
- duration: 500,
26
- }),
27
- });
3
+ import { BaseComponentProps } from '../core/component';
4
+ import { defineComponent } from '../core/component';
5
+ import { useTheme, t } from '../runner/theme';
6
+ import { type ResponseKey, responseKey } from '../utils/keys';
28
7
 
29
8
  interface TutorialSlideContextValue {
30
9
  setCanProgress: (canProgress: boolean) => void;
@@ -60,39 +39,38 @@ export const useTutorialSlide = ({ locked = false } = {}) => {
60
39
  };
61
40
  };
62
41
 
63
- export interface TutorialProps extends BaseComponentProps {
42
+ export interface TutorialProps
43
+ extends BaseComponentProps<{ slides: Record<number, Record<string, unknown>> }> {
64
44
  slides: ReactNode[];
65
- /** Fade duration in seconds (default: 0.3) */
66
- fadeDuration?: number;
67
- finishText?: string;
45
+ /** Fade duration in milliseconds (default: 300) */
46
+ fadeDurationMs?: number;
47
+ /** The button on the last slide, which ends the screen. */
48
+ buttonText?: string;
49
+ className?: string;
68
50
  containerClass?: string;
69
- /** Key to go forward (default: 'ArrowRight', set to false to disable) */
70
- nextKey?: string | false;
71
- /** Key to go back (default: 'ArrowLeft', set to false to disable) */
72
- backKey?: string | false;
51
+ /** Key to go forward, a letter in either case (default: 'ArrowRight', set to false to disable) */
52
+ nextKey?: ResponseKey | false;
53
+ /** Key to go back, a letter in either case (default: 'ArrowLeft', set to false to disable) */
54
+ backKey?: ResponseKey | false;
73
55
  /** Slide-down + fade-in entrance animation (default: false) */
74
56
  animate?: boolean;
75
- /** Color mode for dot indicators (default: 'light') */
76
- theme?: 'light' | 'dark';
77
57
  }
78
58
 
79
59
  const NAV_BTN_BASE =
80
60
  'px-4 py-3 border-2 font-bold text-lg rounded-xl transition-all duration-100 outline-none focus:outline-none focus:ring-0';
81
61
 
82
- export const Tutorial = ({
62
+ const TutorialComponent = ({
83
63
  next,
84
64
  slides,
85
- fadeDuration = 0.3,
86
- finishText = 'Start',
65
+ fadeDurationMs = 300,
66
+ buttonText = 'Start',
67
+ className = '',
87
68
  containerClass,
88
69
  animate = false,
89
70
  nextKey = 'ArrowRight',
90
71
  backKey = 'ArrowLeft',
91
- theme,
92
72
  }: TutorialProps) => {
93
- const contextTheme = useTheme();
94
- const resolvedTheme = theme ?? contextTheme;
95
- const th = t(resolvedTheme);
73
+ const th = t(useTheme());
96
74
 
97
75
  const NAV_BTN_ACTIVE = `${NAV_BTN_BASE} ${th.buttonBg} ${th.buttonText} ${th.buttonBorder} ${th.buttonShadow} cursor-pointer hover:translate-x-[2px] hover:translate-y-[2px] hover:shadow-none`;
98
76
  const NAV_BTN_DISABLED = `${NAV_BTN_BASE} ${th.buttonDisabledBg} ${th.buttonDisabledText} ${th.buttonDisabledBorder} ${th.buttonDisabledShadow} cursor-default`;
@@ -156,8 +134,8 @@ export const Tutorial = ({
156
134
  useEffect(() => {
157
135
  if (nextKey === false && backKey === false) return;
158
136
  const onKey = (e: KeyboardEvent) => {
159
- if (nextKey && e.key === nextKey) { e.preventDefault(); goNextIfCan(); }
160
- if (backKey && e.key === backKey) { e.preventDefault(); goBack(); }
137
+ if (nextKey && responseKey([nextKey], e.key)) { e.preventDefault(); goNextIfCan(); }
138
+ if (backKey && responseKey([backKey], e.key)) { e.preventDefault(); goBack(); }
161
139
  };
162
140
  window.addEventListener('keydown', onKey);
163
141
  return () => window.removeEventListener('keydown', onKey);
@@ -175,14 +153,14 @@ export const Tutorial = ({
175
153
  overflow: 'hidden',
176
154
  }}
177
155
  >
178
- <div style={{ flex: 1, position: 'relative' }}>
156
+ <div className={className} style={{ flex: 1, position: 'relative' }}>
179
157
  <AnimatePresence mode='popLayout'>
180
158
  <motion.div
181
159
  key={page}
182
160
  initial={{ opacity: 0 }}
183
161
  animate={{ opacity: 1 }}
184
162
  exit={{ opacity: 0 }}
185
- transition={{ duration: fadeDuration }}
163
+ transition={{ duration: fadeDurationMs / 1000 }}
186
164
  style={{
187
165
  position: 'absolute',
188
166
  inset: 0,
@@ -242,7 +220,7 @@ export const Tutorial = ({
242
220
  transition={{ type: 'spring', stiffness: 500, damping: 15 }}
243
221
  className={(canProgress ? NAV_BTN_ACTIVE : NAV_BTN_DISABLED) + (page === slides.length - 1 ? ' px-8' : '')}
244
222
  >
245
- {page === slides.length - 1 ? finishText : '→'}
223
+ {page === slides.length - 1 ? buttonText : '→'}
246
224
  </motion.button>
247
225
  </div>
248
226
  </div>
@@ -250,3 +228,23 @@ export const Tutorial = ({
250
228
  </LayoutGroup>
251
229
  );
252
230
  };
231
+
232
+ export const Tutorial = defineComponent({
233
+ name: 'Tutorial',
234
+ component: TutorialComponent,
235
+ csv: null,
236
+ simulate: ({ props, simulators, participant }) => {
237
+ const slideData: Record<number, Record<string, unknown>> = {};
238
+ let totalDuration = 0;
239
+ for (let i = 0; i < (props.slides?.length ?? 0); i++) {
240
+ const result = simulators.respondToSlide({ props, participant, slideIndex: i });
241
+ participant = result.participant ?? participant;
242
+ slideData[i] = result.value.data;
243
+ totalDuration += result.value.durationMs;
244
+ }
245
+ return { recorded: { slides: slideData }, participant, durationMs: totalDuration };
246
+ },
247
+ defaultSimulators: {
248
+ respondToSlide: () => ({ value: { data: {}, durationMs: 500 } }),
249
+ },
250
+ });