@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,69 +0,0 @@
1
- import 'react-toastify/dist/ReactToastify.min.css';
2
- import { ToastContainer } from 'react-toastify';
3
-
4
- const queryClient = new QueryClient();
5
- import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
6
- import { createContext, ReactNode, useContext, useEffect } from 'react';
7
- import { SettingsScreen } from './settingsscreen';
8
- import { Param } from '../utils/common';
9
-
10
- const HybridSimulationContext = createContext(false);
11
- export const useHybridSimulationDisabled = () => useContext(HybridSimulationContext);
12
-
13
- function parseBooleanProp(value: unknown): boolean {
14
- if (typeof value === 'boolean') return value;
15
- if (typeof value === 'string') {
16
- const lower = value.trim().toLowerCase();
17
- return lower !== '' && lower !== 'false' && lower !== '0';
18
- }
19
- return !!value;
20
- }
21
-
22
- export default function ExperimentProvider({ children, disableSettings, disableHybridSimulation }: { children: ReactNode, disableSettings?: boolean, disableHybridSimulation?: boolean }) {
23
-
24
- useEffect(() => {
25
- const preventSpaceScroll = (e: KeyboardEvent) => {
26
- if (e.key === ' ' &&
27
- !(e.target instanceof HTMLInputElement) &&
28
- !(e.target instanceof HTMLTextAreaElement) &&
29
- !(e.target as HTMLElement).isContentEditable) {
30
- e.preventDefault();
31
- }
32
- };
33
- window.addEventListener('keydown', preventSpaceScroll);
34
- return () => window.removeEventListener('keydown', preventSpaceScroll);
35
- }, []);
36
-
37
- if (window.location.pathname.endsWith('/settings') && !parseBooleanProp(disableSettings)) {
38
- return (
39
- <SettingsScreen
40
- paramRegistry={Param.getRegistry()}
41
- timelineRepresentation={Param.getTimelineRepresentation()}
42
- />
43
- );
44
- }
45
-
46
- return (
47
- <QueryClientProvider client={queryClient}>
48
- <HybridSimulationContext.Provider value={parseBooleanProp(disableHybridSimulation)}>
49
- {children}
50
- </HybridSimulationContext.Provider>
51
- <ToastContainer
52
- position='top-center'
53
- autoClose={3000}
54
- hideProgressBar
55
- newestOnTop={false}
56
- closeOnClick
57
- rtl={false}
58
- pauseOnFocusLoss
59
- draggable={false}
60
- pauseOnHover
61
- theme='light'
62
- toastClassName={() =>
63
- 'relative flex p-4 min-h-10 rounded-none justify-between overflow-hidden cursor-pointer border-2 border-black shadow-[2px_2px_0px_rgba(0,0,0,1)] bg-white'
64
- }
65
- bodyClassName='text-black font-sans'
66
- />
67
- </QueryClientProvider>
68
- );
69
- }
@@ -1,497 +0,0 @@
1
- /* eslint-disable @typescript-eslint/no-explicit-any */
2
-
3
- import '../index.css';
4
- import { ExperimentConfig, Store, Param, now, getParam } from '../utils/common';
5
- import { useCallback, useEffect, useMemo, useRef, useState, ComponentType } from 'react';
6
- import {
7
- compileTimeline,
8
- advanceToNextContent,
9
- applyMetadata,
10
- TimelineItem,
11
- TrialResult,
12
- ComponentResultData,
13
- } from '../utils/bytecode';
14
- import {
15
- ParticipantState,
16
- SimulateFunction,
17
- resolveSimulation,
18
- } from '../utils/simulation';
19
- import { useHybridSimulationDisabled } from './experimentprovider';
20
- import { ThemeContext, t } from '../utils/theme';
21
- import { AudioDeviceContext } from '../utils/audiodevice';
22
- import { getOverlays } from '../utils/overlays';
23
- import { v4 as uuidv4 } from 'uuid';
24
-
25
- import Upload from './upload';
26
- import Text from './text';
27
- import PlainInput from './plaininput';
28
- import ProlificEnding from './prolificending';
29
- import Quest from './quest';
30
- import EnterFullscreen from './enterfullscreen';
31
- import ExitFullscreen from './exitfullscreen';
32
- import MicrophoneCheck from './microphonecheck';
33
- import RequestFilePermission from './mobilefilepermission';
34
- import CanvasBlock from './canvasblock';
35
- import CheckDevice from './checkdevice';
36
-
37
- import VoicerecorderQuestionComponent from './voicerecorder';
38
- import React from 'react';
39
- import StoreUI from './storeui';
40
- import { Tutorial } from './tutorial';
41
- import { RandomDotKinematogram } from './randomdotkinetogram';
42
- import VoiceRecording from './voicerecording';
43
-
44
- type ComponentsMap = {
45
- [key: string]: ComponentType<any>;
46
- };
47
-
48
- const defaultComponents: ComponentsMap = {
49
- Text,
50
- ProlificEnding,
51
- EnterFullscreen,
52
- ExitFullscreen,
53
- Quest,
54
- Upload,
55
- MicrophoneCheck,
56
- PlainInput,
57
- RequestFilePermission,
58
- CanvasBlock,
59
- CheckDevice,
60
- StoreUI,
61
- Tutorial,
62
- RandomDotKinematogram,
63
- VoiceRecording,
64
- };
65
-
66
- const defaultCustomQuestions: ComponentsMap = {
67
- voicerecorder: VoicerecorderQuestionComponent,
68
- };
69
-
70
- interface RuntimeComponentContent {
71
- name?: string;
72
- type: string;
73
- csv?: string | string[];
74
- collectRefreshRate?: boolean;
75
- hideSettings?: string[] | boolean;
76
- metadata?:
77
- | Record<string, any>
78
- | ((data: TrialResult[], store: Store) => Record<string, any>);
79
- nestMetadata?: boolean;
80
- props?: Record<string, any> | ((data: TrialResult[], store: Store) => Record<string, any>);
81
- simulate?: SimulateFunction | boolean;
82
- simulators?: Record<string, any>;
83
- }
84
-
85
- // Register dev param globally so it appears in the settings screen
86
- getParam('dev', false, 'boolean', 'Enable the developer inspector panel');
87
-
88
- function isRuntimeComponentContent(content: any): content is RuntimeComponentContent {
89
- return typeof content === 'object' && content !== null && typeof content.type === 'string';
90
- }
91
-
92
- export default function ExperimentRunner({
93
- timeline,
94
- config = {
95
- showProgressBar: false,
96
- },
97
- components = {},
98
- questions = {},
99
- hybridParticipant,
100
- disableDev = false,
101
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
102
- simulationConfig: _simulationConfig,
103
- }: {
104
- timeline: TimelineItem[];
105
- config?: ExperimentConfig;
106
- components?: ComponentsMap;
107
- questions?: ComponentsMap;
108
- hybridParticipant?: ParticipantState;
109
- /** Disable the ?dev=true inspector panel. Set to true for production. */
110
- disableDev?: boolean;
111
- /** Simulation config — not used at runtime, extracted by simulate.ts via createElement. */
112
- simulationConfig?: any;
113
- }) {
114
- const disableHybridSimulation = useHybridSimulationDisabled();
115
- const trialByteCode = useMemo(() => {
116
- return compileTimeline(timeline);
117
- }, [timeline]);
118
-
119
- const dataRef = useRef<TrialResult[]>((() => {
120
- const urlParams: Record<string, any> = {};
121
- const searchParams = new URLSearchParams(window.location.search);
122
- for (const [key, value] of searchParams.entries()) {
123
- urlParams[key] = value;
124
- }
125
-
126
- const registry = Param.getRegistry() || [];
127
-
128
- const params: Record<string, any> = {};
129
-
130
- // First add URL params (these will be overwritten by registry entries if there are name collisions)
131
- for (const [key, value] of Object.entries(urlParams)) {
132
- params[key] = {
133
- value,
134
- registered: false,
135
- defaultValue: undefined,
136
- type: undefined,
137
- description: undefined,
138
- };
139
- }
140
-
141
- // Then add/overwrite with registry entries
142
- for (const param of registry) {
143
- params[param.name] = {
144
- value: param.value !== undefined ? param.value : urlParams[param.name],
145
- registered: true,
146
- defaultValue: param.defaultValue,
147
- type: param.type,
148
- description: param.description,
149
- };
150
- }
151
-
152
- const initialData: ComponentResultData = {
153
- index: -1,
154
- trialNumber: -1,
155
- start: now(),
156
- end: now(),
157
- duration: 0,
158
- type: '',
159
- name: '',
160
- responseData: {
161
- userAgent: navigator.userAgent,
162
- params,
163
- },
164
- };
165
-
166
- return [initialData];
167
- })());
168
-
169
- const [totalTrialsCompleted, setTotalTrialsCompleted] = useState(0);
170
- const lastTrialEndTimeRef = useRef(now());
171
- const experimentStoreRef = useRef<Store>({ _uploadId: uuidv4() });
172
-
173
- const [instructionPointer, setInstructionPointer] = useState(() =>
174
- advanceToNextContent(
175
- trialByteCode,
176
- 0,
177
- () => experimentStoreRef.current,
178
- () => dataRef.current,
179
- (s) => { experimentStoreRef.current = { ...experimentStoreRef.current, ...s }; },
180
- )
181
- );
182
-
183
- const simulationMode =
184
- (!disableHybridSimulation && getParam('hybridSimulation', false, 'boolean'))
185
- ? 'hybrid' as const
186
- : 'none' as const;
187
-
188
- const participantRef = useRef<ParticipantState>(hybridParticipant || {});
189
- // Guards against duplicate simulation in React strict mode
190
- const lastSimulatedPointerRef = useRef(-1);
191
-
192
- const componentsMap = { ...defaultComponents, ...components };
193
- const customQuestionsMap: ComponentsMap = { ...defaultCustomQuestions, ...questions };
194
-
195
- const progress = useMemo(() => {
196
- const totalInstructions = trialByteCode.instructions.length;
197
- return totalInstructions > 0 ? instructionPointer / totalInstructions : 0;
198
- }, [instructionPointer, trialByteCode.instructions]);
199
-
200
- useEffect(() => {
201
- window.scrollTo(0, 0);
202
- }, [instructionPointer]);
203
-
204
- function updateStore(update: Partial<Store>) {
205
- experimentStoreRef.current = { ...experimentStoreRef.current, ...update };
206
- }
207
-
208
- function next(
209
- componentResponseData?: object,
210
- actualStartTime?: number,
211
- actualEndTime?: number,
212
- ): void {
213
- const currentTime = now();
214
- const currentInstruction = trialByteCode.instructions[instructionPointer];
215
-
216
- // Use the provided startTime if available, otherwise use the lastTrialEndTimeRef
217
- const startTime = actualStartTime !== undefined ? actualStartTime : lastTrialEndTimeRef.current;
218
-
219
- const endTime = actualEndTime !== undefined ? actualEndTime : currentTime;
220
-
221
- if (currentInstruction?.type === 'ExecuteContent') {
222
- const content = currentInstruction.content;
223
- if (isRuntimeComponentContent(content)) {
224
- let trialData: ComponentResultData = {
225
- index: instructionPointer,
226
- trialNumber: totalTrialsCompleted + 1,
227
- start: startTime,
228
- end: endTime,
229
- duration: endTime - startTime,
230
- type: content.type,
231
- name: content.name ?? '',
232
- ...(content.csv !== undefined ? { csv: content.csv } : {}),
233
- responseData: componentResponseData,
234
- };
235
-
236
- trialData = applyMetadata(trialData, content, dataRef.current, experimentStoreRef.current);
237
-
238
- dataRef.current = [...dataRef.current, trialData];
239
- setTotalTrialsCompleted((prevCount) => prevCount + 1);
240
- } else {
241
- console.log(
242
- "ExecuteContent finished, but content wasn't standard component format:",
243
- content,
244
- );
245
- }
246
- }
247
-
248
- const nextPointer = advanceToNextContent(
249
- trialByteCode,
250
- instructionPointer + 1,
251
- () => experimentStoreRef.current,
252
- () => dataRef.current,
253
- (s) => updateStore(s),
254
- );
255
- if (nextPointer < trialByteCode.instructions.length) {
256
- lastTrialEndTimeRef.current = now();
257
- }
258
- setInstructionPointer(nextPointer);
259
- }
260
-
261
- const collectRefreshRate = useCallback((callback: (refreshRate: number | null) => void) => {
262
- let frameCount = 0;
263
- const startTime = now();
264
- const maxDuration = 20000;
265
- let rafId: number;
266
- let lastUpdateTime = startTime;
267
- const updateInterval = 1000;
268
-
269
- const calculateRefreshRate = () => {
270
- const currentTime = now();
271
- const elapsedTime = currentTime - startTime;
272
- if (elapsedTime > 0) {
273
- const refreshRate = Math.round((frameCount * 1000) / elapsedTime);
274
- return refreshRate;
275
- }
276
- return null;
277
- };
278
-
279
- const cleanup = () => {
280
- if (rafId) {
281
- cancelAnimationFrame(rafId);
282
- }
283
- };
284
-
285
- const countFrames = (timestamp: number) => {
286
- frameCount++;
287
- const elapsedTime = timestamp - startTime;
288
-
289
- // Check if it's time for an update (once per second)
290
- if (timestamp - lastUpdateTime >= updateInterval) {
291
- callback(calculateRefreshRate());
292
- lastUpdateTime = timestamp;
293
- }
294
-
295
- if (elapsedTime < maxDuration) {
296
- rafId = requestAnimationFrame(countFrames);
297
- } else {
298
- cleanup();
299
- callback(calculateRefreshRate());
300
- }
301
- };
302
-
303
- rafId = requestAnimationFrame(countFrames);
304
-
305
- return cleanup;
306
- }, []);
307
-
308
- const TimingWrapper: React.FC<{
309
- children: React.ReactNode;
310
- collectRefreshRate?: boolean;
311
- }> = ({ children, collectRefreshRate: shouldcollect }) => {
312
- const wrapperStartTimeRef = useRef<number | null>(null);
313
- const refreshRateRef = useRef<number | null>(null);
314
-
315
- useEffect(() => {
316
- wrapperStartTimeRef.current = now();
317
-
318
- if (shouldcollect) {
319
- const cleanup = collectRefreshRate((rate) => {
320
- refreshRateRef.current = rate;
321
- updateStore({ _reactiveScreenRefreshRate: rate });
322
- });
323
-
324
- return cleanup;
325
- }
326
- }, []);
327
-
328
- const childWithTimingProps = React.Children.map(children, (child) => {
329
- if (React.isValidElement(child)) {
330
- const interceptedNext = (
331
- responseData?: object,
332
- actualStartTime?: number,
333
- actualEndTime?: number,
334
- ) => {
335
- const currentTimeWrapper = now();
336
-
337
- // Use the timings provided by the component if available, otherwise use the one by the wrapper
338
- const startTime =
339
- actualStartTime !== undefined ? actualStartTime : wrapperStartTimeRef.current;
340
- const endTime = actualEndTime !== undefined ? actualEndTime : currentTimeWrapper;
341
-
342
- next(responseData, startTime ?? undefined, endTime ?? undefined);
343
- };
344
-
345
- return React.cloneElement(child, {
346
- ...child.props,
347
- next: interceptedNext,
348
- });
349
- }
350
- return child;
351
- });
352
-
353
- return <>{childWithTimingProps}</>;
354
- };
355
-
356
- const currentInstruction = trialByteCode.instructions[instructionPointer];
357
-
358
- const shouldSimulate = useMemo(() => {
359
- if (simulationMode === 'none') return false;
360
- if (currentInstruction?.type !== 'ExecuteContent') return false;
361
- const content = currentInstruction.content;
362
- if (!isRuntimeComponentContent(content)) return false;
363
- if (content.simulate === false) return false;
364
- return !!content.simulate || !!content.simulators;
365
- }, [instructionPointer, simulationMode, currentInstruction]);
366
-
367
- useEffect(() => {
368
- if (!shouldSimulate) return;
369
- if (lastSimulatedPointerRef.current === instructionPointer) return;
370
- lastSimulatedPointerRef.current = instructionPointer;
371
-
372
- (async () => {
373
- const content = (currentInstruction as any).content;
374
- const { trialProps, simulateFn, simulators } = resolveSimulation(content, dataRef.current, experimentStoreRef.current);
375
-
376
- const result = await simulateFn(
377
- trialProps,
378
- { data: dataRef.current, store: experimentStoreRef.current },
379
- simulators,
380
- participantRef.current,
381
- );
382
-
383
- participantRef.current = result.participantState;
384
- if (result.storeUpdates) updateStore(result.storeUpdates);
385
- next(result.responseData);
386
- })();
387
- }, [shouldSimulate, instructionPointer]);
388
-
389
- let componentToRender = null;
390
- if (currentInstruction?.type === 'ExecuteContent' && !shouldSimulate) {
391
- const content = currentInstruction.content;
392
- if (isRuntimeComponentContent(content)) {
393
- const Component = componentsMap[content.type];
394
-
395
- if (Component) {
396
- const componentProps =
397
- typeof content.props === 'function'
398
- ? content.props(dataRef.current, experimentStoreRef.current)
399
- : content.props || {};
400
-
401
- componentToRender = (
402
- <TimingWrapper key={instructionPointer} collectRefreshRate={content.collectRefreshRate}>
403
- <Component
404
- next={next}
405
- updateStore={updateStore}
406
- store={experimentStoreRef.current}
407
- data={dataRef.current}
408
- name={content.name}
409
- {...(content.type === 'Quest' ? { customQuestions: customQuestionsMap } : {})}
410
- {...componentProps}
411
- />
412
- </TimingWrapper>
413
- );
414
- } else {
415
- console.error(`No component found for type: ${content.type}`);
416
- componentToRender = <div>Error: Component type "{content.type}" not found.</div>;
417
- }
418
- } else {
419
- console.warn('ExecuteContent instruction does not contain standard component data:', content);
420
- componentToRender = <div>Non-component content encountered.</div>;
421
- }
422
- } else if (instructionPointer >= trialByteCode.instructions.length) {
423
- componentToRender = <></>;
424
- }
425
-
426
- const themeValue = config.theme ?? 'light';
427
- const th = t(themeValue);
428
-
429
- const showDev = !disableDev && getParam('dev', false, 'boolean');
430
- const devPanelRef = useRef<HTMLDivElement>(null);
431
- const devContent = currentInstruction?.type === 'ExecuteContent' ? currentInstruction.content : null;
432
-
433
- return (
434
- <ThemeContext.Provider value={themeValue}>
435
- <AudioDeviceContext.Provider value={experimentStoreRef.current.audioInputId}>
436
- <div className='w-full h-full'>
437
- <div
438
- className={` ${
439
- config.showProgressBar ? '' : 'hidden '
440
- } px-4 mt-4 sm:mt-12 max-w-2xl mx-auto`}
441
- >
442
- <div className={`flex-1 h-6 ${th.progressBg} rounded-full overflow-hidden`}>
443
- <div
444
- className={`h-full ${th.progressBg} rounded-full duration-300 ${
445
- progress > 0 ? ` border-black border-2` : ''
446
- }`}
447
- style={{
448
- width: `${progress * 100}%`,
449
- backgroundImage: `repeating-linear-gradient(
450
- -45deg, ${th.progressStripe1}, ${th.progressStripe1} 10px, ${th.progressStripe2} 10px, ${th.progressStripe2} 20px
451
- )`,
452
- transition: 'width 300ms ease-in-out',
453
- }}
454
- />
455
- </div>
456
- </div>
457
- {componentToRender}
458
- {getOverlays().map((O, i) => (
459
- <O key={i} store={experimentStoreRef.current} updateStore={updateStore} data={dataRef.current} />
460
- ))}
461
- {showDev && (
462
- <>
463
- <button
464
- onClick={(e) => {
465
- const panel = devPanelRef.current;
466
- if (panel) {
467
- const open = panel.style.display === 'none';
468
- panel.style.display = open ? 'block' : 'none';
469
- (e.currentTarget as HTMLButtonElement).textContent = open ? '\u2715' : 'DEV';
470
- }
471
- }}
472
- className='fixed top-2 right-2 z-50 px-3 py-1 bg-white text-black text-xs font-bold border-2 border-black shadow-[2px_2px_0px_rgba(0,0,0,1)] hover:translate-x-[1px] hover:translate-y-[1px] hover:shadow-none cursor-pointer'
473
- >
474
- DEV
475
- </button>
476
- <div ref={devPanelRef} style={{ display: 'none' }} className='fixed top-10 right-2 z-50 w-96 max-h-[80vh] overflow-auto bg-white text-black text-xs font-mono border-2 border-black shadow-[4px_4px_0px_rgba(0,0,0,1)] p-3'>
477
- {devContent && <>
478
- <div className='font-bold mb-2 text-sm'>{(devContent as any).type} {(devContent as any).name ? `(${(devContent as any).name})` : ''}</div>
479
- <div className='mb-2'><span className='font-bold'>Props:</span><pre className='mt-1 whitespace-pre-wrap break-all'>{JSON.stringify(typeof (devContent as any).props === 'function' ? '(dynamic)' : (devContent as any).props, null, 2)}</pre></div>
480
- {(devContent as any).metadata && <div className='mb-2'><span className='font-bold'>Metadata:</span><pre className='mt-1 whitespace-pre-wrap break-all'>{JSON.stringify((devContent as any).metadata, null, 2)}</pre></div>}
481
- <div className='mb-2'><span className='font-bold'>Store:</span><pre className='mt-1 whitespace-pre-wrap break-all'>{JSON.stringify(experimentStoreRef.current, null, 2)}</pre></div>
482
- <div>
483
- <span className='font-bold cursor-pointer' onClick={(e) => {
484
- const el = (e.currentTarget as HTMLElement).nextElementSibling as HTMLElement;
485
- if (el) el.style.display = el.style.display === 'none' ? 'block' : 'none';
486
- }}>Data ({dataRef.current.length}) ▸</span>
487
- <pre style={{ display: 'none' }} className='mt-1 whitespace-pre-wrap break-all'>{JSON.stringify(dataRef.current, null, 2)}</pre>
488
- </div>
489
- </>}
490
- </div>
491
- </>
492
- )}
493
- </div>
494
- </AudioDeviceContext.Provider>
495
- </ThemeContext.Provider>
496
- );
497
- }
@@ -1,68 +0,0 @@
1
- import { BaseComponentProps, getPlatform } from '../utils/common';
2
- import { useEffect, useState } from 'react';
3
- import { registerSimulation, noopSimulate } from '../utils/simulation';
4
- import { registerFlattener } from '../utils/upload';
5
- import { Filesystem, Directory, Encoding } from '@capacitor/filesystem';
6
- import { Capacitor } from '@capacitor/core';
7
-
8
- registerFlattener('RequestFilePermission', null);
9
- registerSimulation('RequestFilePermission', noopSimulate, {});
10
-
11
- export default function RequestFilePermission({ next }: BaseComponentProps) {
12
- const [permissionStatus, setPermissionStatus] = useState('checking');
13
-
14
- useEffect(() => {
15
- if (permissionStatus !== 'checking') return;
16
-
17
- const checkPermission = async () => {
18
- if (getPlatform() !== 'mobile' || Capacitor.getPlatform() !== 'android') {
19
- next({});
20
- return;
21
- }
22
-
23
- try {
24
- await Filesystem.writeFile({
25
- path: 'permission_check.txt',
26
- data: 'Testing permissions',
27
- directory: Directory.Documents,
28
- encoding: Encoding.UTF8
29
- });
30
-
31
- try {
32
- await Filesystem.deleteFile({
33
- path: 'permission_check.txt',
34
- directory: Directory.Documents
35
- });
36
- } catch (e) {
37
- console.log('Cleanup error:', e);
38
- }
39
-
40
- setPermissionStatus('granted');
41
- next({});
42
- } catch (error) {
43
- console.error('Permission denied or error:', error);
44
- setPermissionStatus('denied');
45
- }
46
- };
47
-
48
- checkPermission();
49
- }, [next, permissionStatus]);
50
-
51
- if (permissionStatus === 'checking') {
52
- return null;
53
- }
54
-
55
- return (
56
- <div className="flex flex-col items-center justify-center gap-4 p-6 text-xl mt-16 px-10">
57
- <p>Storage permission is required to save your data.</p>
58
- <p>Please grant permission when prompted.</p>
59
- <p>If there is no popup, go to "Settings" {">"} "Apps" {">"} "Name of the App" {">"} "Permissions" {">"} "Storage" {">"} "Allow"</p>
60
- <button
61
- onClick={() => setPermissionStatus('checking')}
62
- className="mt-8 bg-white 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"
63
- >
64
- Try Again
65
- </button>
66
- </div>
67
- );
68
- }