@adriansteffan/reactive 0.2.6 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (156) 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 +48 -41
  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/.prettierrc +0 -5
  99. package/Dockerfile +0 -20
  100. package/dist/mod-HDegGPrf.js +0 -87434
  101. package/dist/mod.d.ts +0 -946
  102. package/dist/reactive.es.js +0 -87
  103. package/dist/reactive.umd.js +0 -10255
  104. package/dist/style.css +0 -5
  105. package/dist/web-7BbR1Ad7.js +0 -435
  106. package/dist/web-CATfZO1Q.js +0 -12
  107. package/planned.md +0 -103
  108. package/postcss.config.js +0 -6
  109. package/raw-loader-hooks.mjs +0 -25
  110. package/raw-loader.mjs +0 -5
  111. package/rdk_doc.md +0 -341
  112. package/src/components/enterfullscreen.tsx +0 -230
  113. package/src/components/exitfullscreen.tsx +0 -113
  114. package/src/components/experimentprovider.tsx +0 -69
  115. package/src/components/experimentrunner.tsx +0 -497
  116. package/src/components/mobilefilepermission.tsx +0 -68
  117. package/src/components/settingsscreen.tsx +0 -770
  118. package/src/types/array.d.ts +0 -6
  119. package/src/utils/audiodevice.ts +0 -4
  120. package/src/utils/bytecode.ts +0 -261
  121. package/src/utils/common.ts +0 -291
  122. package/src/utils/ddm.test.ts +0 -233
  123. package/src/utils/distributions.test.ts +0 -209
  124. package/src/utils/nodecompat.ts +0 -11
  125. package/src/utils/overlays.ts +0 -19
  126. package/src/utils/request.ts +0 -25
  127. package/src/utils/simulation.ts +0 -299
  128. package/src/utils/upload.ts +0 -275
  129. package/src/vite-env.d.ts +0 -1
  130. package/template/.env.template +0 -2
  131. package/template/.eslintrc.cjs +0 -18
  132. package/template/.prettierrc +0 -5
  133. package/template/backend/package-lock.json +0 -2544
  134. package/template/backend/package.json +0 -31
  135. package/template/backend/src/backend.ts +0 -131
  136. package/template/backend/tsconfig.json +0 -110
  137. package/template/capacitor.config.ts +0 -15
  138. package/template/electron/main.js +0 -131
  139. package/template/electron/preload.js +0 -9
  140. package/template/electron.vite.config.js +0 -45
  141. package/template/package-lock.json +0 -12467
  142. package/template/postcss.config.js +0 -5
  143. package/template/public/Atkinson_Hyperlegible/AtkinsonHyperlegible-Bold.ttf +0 -0
  144. package/template/public/Atkinson_Hyperlegible/AtkinsonHyperlegible-BoldItalic.ttf +0 -0
  145. package/template/public/Atkinson_Hyperlegible/AtkinsonHyperlegible-Italic.ttf +0 -0
  146. package/template/public/Atkinson_Hyperlegible/AtkinsonHyperlegible-Regular.ttf +0 -0
  147. package/template/shared.vite.config.js +0 -39
  148. package/template/src/vite-env.d.ts +0 -2
  149. package/template/tsconfig.node.json +0 -12
  150. package/template/vite.config.js +0 -11
  151. package/tsconfig.json +0 -30
  152. package/tsconfig.node.json +0 -12
  153. package/vite.config.ts +0 -39
  154. /package/{template → extras}/transcription/Dockerfile.cpu +0 -0
  155. /package/{template → extras}/transcription/Dockerfile.gpu +0 -0
  156. /package/{template/public/Atkinson_Hyperlegible → src/fonts}/OFL.txt +0 -0
@@ -1,306 +1,104 @@
1
- import React, { useCallback, useEffect, useRef, useState } from 'react';
2
- import { useMutation } from '@tanstack/react-query';
3
- import { v4 as uuidv4 } from 'uuid';
4
- import { post } from '../utils/request';
5
- import {
6
- BaseComponentProps,
7
- FileUpload,
8
- getParam,
9
- getPlatform,
10
- Platform,
11
- registerComponentParams,
12
- Store,
13
- TrialData,
14
- } from '../utils/common';
15
- import { BlobReader, BlobWriter, TextReader, ZipWriter } from '@zip.js/zip.js';
16
- import { Filesystem, Directory, Encoding } from '@capacitor/filesystem';
17
- import { buildUploadFiles, convertArrayOfObjectsToCSV } from '../utils/upload';
18
- import { registerSimulation, getBackendUrl, getInitialParticipant } from '../utils/simulation';
1
+ import React, { useCallback, useContext, useEffect, useRef, useState } from 'react';
2
+ import { uuidv4 } from '../utils/ids';
3
+ import { post } from '../core/backend';
4
+ import { BaseComponentProps } from '../core/component';
5
+ import type { FileUpload } from '../core/files';
6
+ import type { ExperimentData } from '../core/rows';
7
+ import { CompiledTimelineContext, useParams } from '../runner/contexts';
8
+ import { strToU8, zipSync, type Zippable } from 'fflate';
9
+ import { FileBackend, getNative } from '../core/platform';
10
+ import { buildUploadFiles, convertArrayOfObjectsToCSV } from '../core/files';
11
+ import { type Store } from '../core/store';
12
+ import { defineComponent } from '../core/component';
19
13
  import { uniform } from '../utils/distributions';
20
- import { useTheme, t } from '../utils/theme';
21
-
22
- registerSimulation('Upload', async (trialProps, experimentState, _simulators, participant) => {
23
- const sessionID = trialProps.sessionID || `sim_${Date.now()}_${Math.floor(uniform(0, 36 ** 6)).toString(36)}`;
24
- const files = buildUploadFiles({
25
- sessionID,
26
- data: experimentState.data || [],
27
- store: experimentState.store,
28
- generateFiles: trialProps.generateFiles,
29
- sessionData: trialProps.sessionData,
30
- uploadRaw: trialProps.uploadRaw ?? true,
31
- });
32
-
33
- const initialParticipant = getInitialParticipant();
34
- if (initialParticipant) {
35
- files.push({
36
- filename: `${sessionID}_participant_initial.csv`,
37
- content: convertArrayOfObjectsToCSV([initialParticipant]),
38
- encoding: 'utf8',
39
- });
40
- files.push({
41
- filename: `${sessionID}_participant_final.csv`,
42
- content: convertArrayOfObjectsToCSV([participant]),
43
- encoding: 'utf8',
44
- });
45
- }
46
-
47
- const backendUrl = getBackendUrl();
48
- if (backendUrl) {
49
- const payload = {
50
- sessionId: sessionID,
51
- files: files.map((f) => ({ ...f, encoding: f.encoding ?? 'utf8' })),
52
- };
53
- const res = await fetch(`${backendUrl}/data`, {
54
- method: 'POST',
55
- headers: { 'Content-Type': 'application/json' },
56
- body: JSON.stringify(payload),
57
- });
58
- if (!res.ok) {
59
- console.error(`Simulation upload failed: ${res.status} ${res.statusText}`);
60
- }
61
- }
62
-
63
- return { responseData: { files }, participantState: participant };
64
- }, {});
14
+ import { useTheme, t } from '../runner/theme';
65
15
 
66
16
  interface UploadPayload {
67
17
  sessionId: string;
68
- _uploadId?: string;
18
+ uploadId?: string;
19
+ parentFolder?: string;
69
20
  files: FileUpload[];
70
21
  }
71
22
 
72
- interface UploadResponse {
73
- status: number;
74
- message?: string;
75
- }
76
-
77
- const UPLOAD_PARAMS = [
78
- {
79
- name: 'upload',
80
- defaultValue: true,
81
- type: 'boolean' as const,
82
- description: 'Upload the data at the end of the experiment?',
83
- },
84
- {
85
- name: 'download',
86
- defaultValue: false,
87
- type: 'boolean' as const,
88
- description: 'Locally download the data at the end of the experiment?',
89
- },
90
- ];
91
- registerComponentParams('Upload', UPLOAD_PARAMS);
92
-
93
-
94
- interface FileBackend {
95
- directoryExists(path: string): Promise<boolean>;
96
- createDirectory(path: string): Promise<void>;
97
- saveFile(filename: string, content: string, directory: string): Promise<void>;
98
- }
99
-
100
- const createElectronFileBackend = (): FileBackend => {
101
- const electronAPI = (window as any).electronAPI;
102
-
103
- return {
104
- directoryExists: async (path: string): Promise<boolean> => {
105
- const result = await electronAPI.directoryExists(path);
106
- return result.success && result.exists;
107
- },
108
- createDirectory: async (path: string): Promise<void> => {
109
- await electronAPI.createDirectory(path);
110
- },
111
- saveFile: async (filename: string, content: string, directory: string): Promise<void> => {
112
- await electronAPI.saveFile(filename, content, directory);
113
- },
114
- };
23
+ const params = {
24
+ upload: { default: true, description: 'Upload the data at the end of the experiment?' },
25
+ download: { default: false, description: 'Locally download the data at the end of the experiment?' },
115
26
  };
116
27
 
117
- const createCapacitorFileBackend = (parentFolder?: string): FileBackend => {
118
- const getPath = (path: string): string => {
119
- if (!parentFolder) {
120
- return path;
121
- }
122
- return path ? `${parentFolder}/${path}` : parentFolder;
123
- };
124
-
125
- return {
126
- directoryExists: async (path: string): Promise<boolean> => {
127
- try {
128
- if (parentFolder) {
129
- try {
130
- await Filesystem.readdir({
131
- path: parentFolder,
132
- directory: Directory.Documents,
133
- });
134
- } catch {
135
- // Parent folder doesn't exist, so subpath doesn't exist either
136
- return false;
137
- }
138
- }
139
-
140
- const fullPath = getPath(path);
141
- const result = await Filesystem.readdir({
142
- path: fullPath,
143
- directory: Directory.Documents,
144
- });
145
- return result.files.length >= 0;
146
- } catch {
147
- return false;
148
- }
149
- },
150
-
151
- createDirectory: async (path: string): Promise<void> => {
152
- try {
153
- if (parentFolder) {
154
- try {
155
- await Filesystem.mkdir({
156
- path: parentFolder,
157
- directory: Directory.Documents,
158
- recursive: false,
159
- });
160
- } catch (e) {
161
- // Parent directory might already exist, that's fine
162
- }
163
- }
164
-
165
- const fullPath = getPath(path);
166
- await Filesystem.mkdir({
167
- path: fullPath,
168
- directory: Directory.Documents,
169
- recursive: true,
170
- });
171
- } catch (e) {
172
- console.error('Error creating directory:', e);
173
- throw e;
174
- }
175
- },
176
-
177
- saveFile: async (filename: string, content: string, directory: string): Promise<void> => {
178
- const fullDirectory = getPath(directory);
179
-
180
- await Filesystem.writeFile({
181
- path: `${fullDirectory}/${filename}`,
182
- data: content,
183
- directory: Directory.Documents,
184
- encoding: 'utf8' as Encoding,
185
- });
186
- },
187
- };
188
- };
189
-
190
- const getFileBackend = (parentDir?: string): { backend: FileBackend | null; type: Platform } => {
191
- const platform = getPlatform();
192
-
193
- switch (platform) {
194
- case 'desktop':
195
- return { backend: createElectronFileBackend(), type: platform };
196
- case 'mobile':
197
- return { backend: createCapacitorFileBackend(parentDir), type: platform };
198
- case 'web':
199
- return { backend: null, type: platform };
200
- }
201
- };
202
-
203
- // Function to generate a unique directory name
204
- const getUniqueDirectoryName = async (
205
- backend: FileBackend,
206
- baseSessionId: string,
207
- ): Promise<string> => {
208
- let uniqueSessionID = baseSessionId;
209
-
210
- if (await backend.directoryExists(uniqueSessionID)) {
211
- let counter = 1;
212
- uniqueSessionID = `${baseSessionId}_${counter}`;
28
+ // The session's id, numbered if the app already has a folder of that name
29
+ async function uniqueDirectoryName(backend: FileBackend, sessionId: string): Promise<string> {
30
+ let name = sessionId;
31
+ for (let i = 1; await backend.directoryExists(name); i++) name = `${sessionId}_${i}`;
32
+ return name;
33
+ }
213
34
 
214
- while (await backend.directoryExists(uniqueSessionID)) {
215
- counter++;
216
- uniqueSessionID = `${baseSessionId}_${counter}`;
35
+ // Saves the files on the participant's computer, as one zip
36
+ function downloadZip(files: FileUpload[]) {
37
+ const entries: Zippable = {};
38
+ for (const file of files) {
39
+ if (file.encoding === 'base64') {
40
+ // Recordings are already compressed, so they are stored as they are
41
+ const binary = Uint8Array.from(atob(file.content), (c) => c.charCodeAt(0));
42
+ entries[file.filename] = [binary, { level: 0 }];
43
+ } else {
44
+ entries[file.filename] = strToU8(file.content);
217
45
  }
218
46
  }
219
47
 
220
- return uniqueSessionID;
221
- };
48
+ const blob = new Blob([zipSync(entries)], { type: 'application/zip' });
49
+ const url = URL.createObjectURL(blob);
50
+ const a = document.createElement('a');
51
+ a.href = url;
52
+ a.download = 'study-data.zip';
53
+ document.body.appendChild(a);
54
+ a.click();
55
+ document.body.removeChild(a);
56
+ URL.revokeObjectURL(url);
57
+ }
222
58
 
223
- export default function Upload({
59
+ function Upload({
224
60
  data,
225
61
  next,
226
62
  store,
227
- sessionID,
63
+ sessionId,
228
64
  generateFiles,
229
65
  sessionData,
230
66
  uploadRaw = true,
231
- autoUpload = false,
232
- androidFolderName,
67
+ autoUpload = true,
68
+ parentFolder,
233
69
  className,
234
70
  containerClass,
235
71
  centered,
236
72
  content,
237
73
  uploadingContent,
238
74
  errorContent,
75
+ buttonText = 'Submit Data',
76
+ retryButtonText = 'Try Again',
239
77
  }: BaseComponentProps & {
240
- sessionID?: string | null;
241
- generateFiles?: (sessionID: string, data: TrialData[], store?: Store) => FileUpload[];
78
+ sessionId?: string | null;
79
+ generateFiles?: (input: { sessionId: string; data: ExperimentData; store: Store }) => FileUpload[];
242
80
  sessionData?: Record<string, any>;
243
81
  uploadRaw?: boolean;
82
+ /** Uploads as soon as the screen appears. With `false`, participants submit with a button first. */
244
83
  autoUpload?: boolean;
245
- androidFolderName?: string;
84
+ /** The folder the session's folder goes into, on the server and on the device. */
85
+ parentFolder?: string;
246
86
  className?: string;
247
87
  containerClass?: string;
248
88
  centered?: boolean;
249
89
  content?: React.ReactNode;
250
90
  uploadingContent?: React.ReactNode;
251
91
  errorContent?: React.ReactNode;
92
+ buttonText?: string;
93
+ retryButtonText?: string;
252
94
  }) {
253
95
  const [uploadState, setUploadState] = useState<'initial' | 'uploading' | 'success' | 'error'>(
254
96
  'initial',
255
97
  );
256
98
  const uploadInitiatedRef = useRef(false);
257
99
 
258
- const uploadParam = UPLOAD_PARAMS.find(p => p.name === 'upload')!;
259
- const downloadParam = UPLOAD_PARAMS.find(p => p.name === 'download')!;
260
- const shouldUpload = getParam(uploadParam.name, uploadParam.defaultValue, uploadParam.type);
261
- const shouldDownload = getParam(downloadParam.name, downloadParam.defaultValue, downloadParam.type);
262
-
263
- const uploadData = useMutation({
264
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
265
- mutationFn: async (body: any) => {
266
- const response = await post('/data', body);
267
- return response as UploadResponse;
268
- },
269
- onSuccess: (res: UploadResponse) => {
270
- if (res.status === 200) {
271
- setUploadState('success');
272
- next({});
273
- } else {
274
- setUploadState('error');
275
- }
276
- },
277
- onError: () => {
278
- setUploadState('error');
279
- },
280
- });
281
-
282
- const downloadFiles = useCallback(async (files: FileUpload[]) => {
283
- const zipWriter = new ZipWriter(new BlobWriter());
284
-
285
- for (const file of files) {
286
- if (file.encoding === 'base64') {
287
- const binary = Uint8Array.from(atob(file.content), (c) => c.charCodeAt(0));
288
- await zipWriter.add(file.filename, new BlobReader(new Blob([binary])));
289
- } else {
290
- await zipWriter.add(file.filename, new TextReader(file.content));
291
- }
292
- }
293
-
294
- const blob = await zipWriter.close();
295
- const url = URL.createObjectURL(blob);
296
- const a = document.createElement('a');
297
- a.href = url;
298
- a.download = 'study-data.zip';
299
- document.body.appendChild(a);
300
- a.click();
301
- document.body.removeChild(a);
302
- URL.revokeObjectURL(url);
303
- }, []);
100
+ const { upload: shouldUpload, download: shouldDownload } = useParams(params);
101
+ const { components } = useContext(CompiledTimelineContext);
304
102
 
305
103
  const handleUpload = useCallback(async () => {
306
104
  setUploadState('uploading');
@@ -311,27 +109,27 @@ export default function Upload({
311
109
 
312
110
  uploadInitiatedRef.current = true;
313
111
 
314
- const sessionIDUpload = sessionID ?? store?._uploadId ?? uuidv4();
112
+ const sessionIdUpload = sessionId ?? store.__uploadId ?? uuidv4();
315
113
 
316
114
  const files = buildUploadFiles({
317
- sessionID: sessionIDUpload,
115
+ sessionId: sessionIdUpload,
318
116
  data,
319
117
  store,
118
+ components,
320
119
  generateFiles,
321
120
  sessionData,
322
121
  uploadRaw,
323
122
  });
324
123
 
325
124
  try {
326
- if (shouldDownload) {
327
- await downloadFiles(files);
328
- }
125
+ if (shouldDownload) downloadZip(files);
329
126
 
330
127
  // Filter out eagerly uploaded files for the server upload (they're already there)
331
128
  const filesToUpload = files.filter((f) => !f._alreadyUploaded);
332
129
  const payload: UploadPayload = {
333
- sessionId: sessionIDUpload,
334
- ...(store?._uploadId && store._uploadId !== sessionIDUpload ? { _uploadId: store._uploadId } : {}),
130
+ sessionId: sessionIdUpload,
131
+ ...(store.__uploadId && store.__uploadId !== sessionIdUpload ? { uploadId: store.__uploadId } : {}),
132
+ ...(parentFolder ? { parentFolder } : {}),
335
133
  files: filesToUpload.map((file) => ({ ...file, encoding: file.encoding ?? 'utf8' })),
336
134
  };
337
135
 
@@ -340,42 +138,37 @@ export default function Upload({
340
138
  return;
341
139
  }
342
140
 
343
- // Get the current platform and appropriate file backend
344
- const { backend, type } = getFileBackend(androidFolderName);
345
-
346
- if (type === 'web') {
347
- uploadData.mutate(payload);
348
- } else if (backend) {
349
- try {
350
- const uniqueSessionID = await getUniqueDirectoryName(backend, sessionIDUpload);
351
-
352
- await backend.createDirectory(uniqueSessionID);
353
-
354
- for (const file of files) {
355
- await backend.saveFile(file.filename, file.content, uniqueSessionID);
356
- }
357
-
358
- setUploadState('success');
359
- next({});
360
- } catch (error) {
361
- console.error(`Error saving files with ${type}:`, error);
362
- setUploadState('error');
363
- }
141
+ // The apps save the files on the device, and the browser sends them to the server
142
+ const native = getNative();
143
+ if (native) {
144
+ const backend = native.createFileBackend(parentFolder);
145
+ const directory = await uniqueDirectoryName(backend, sessionIdUpload);
146
+ await backend.createDirectory(directory);
147
+ for (const file of files) await backend.saveFile(file.filename, file.content, directory);
148
+ } else {
149
+ const response = await post('/data', payload);
150
+ if (!response.ok) throw new Error(`The server answered ${response.status} ${response.statusText}.`);
364
151
  }
152
+ setUploadState('success');
153
+ next({});
365
154
  } catch (error) {
366
155
  console.error('Error uploading:', error);
156
+ // The participant can try again
157
+ uploadInitiatedRef.current = false;
367
158
  setUploadState('error');
368
159
  }
369
160
  }, [
370
- sessionID,
161
+ sessionId,
371
162
  generateFiles,
372
163
  data,
373
164
  uploadRaw,
374
165
  shouldDownload,
375
166
  shouldUpload,
376
- downloadFiles,
377
167
  next,
378
- uploadData,
168
+ store,
169
+ components,
170
+ sessionData,
171
+ parentFolder,
379
172
  ]);
380
173
 
381
174
  useEffect(() => {
@@ -384,28 +177,20 @@ export default function Upload({
384
177
  }
385
178
  }, [autoUpload, handleUpload]);
386
179
 
387
- // reset the duplicate prevention if there was an error uploading
388
- useEffect(() => {
389
- if (uploadState === 'error') {
390
- uploadInitiatedRef.current = false;
391
- }
392
- }, [uploadState]);
393
-
394
180
  const th = t(useTheme());
395
- const btnClass = `cursor-pointer ${th.buttonBg} 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`;
396
181
 
397
182
  return (
398
183
  <div className={`${centered ? 'flex items-center justify-center' : ''} ${containerClass ?? th.containerBg}`} style={{ position: 'fixed', inset: 0 }}>
399
184
  <div className={`flex flex-col items-center justify-center gap-4 p-6 text-xl mt-16 px-10 h-full ${th.text} ${className ?? ''}`}>
400
- {uploadState == 'initial' && !autoUpload && (
185
+ {uploadState === 'initial' && !autoUpload && (
401
186
  <>
402
187
  {content ?? <p>Thank you for participating! Please click the button below to submit your data.</p>}
403
- <button onClick={handleUpload} className={`mt-8 ${btnClass}`}>
404
- Submit Data
188
+ <button onClick={handleUpload} className={`mt-8 ${th.button}`}>
189
+ {buttonText}
405
190
  </button>
406
191
  </>
407
192
  )}
408
- {uploadState == 'uploading' && (
193
+ {uploadState === 'uploading' && (
409
194
  <>
410
195
  {uploadingContent ?? <>
411
196
  <div className='w-8 h-8 border-4 border-blue-500 border-t-transparent rounded-full animate-spin'></div>
@@ -413,16 +198,14 @@ export default function Upload({
413
198
  </>}
414
199
  </>
415
200
  )}
416
- {uploadState == 'success' && <></>}
417
-
418
- {uploadState == 'error' && (
201
+ {uploadState === 'error' && (
419
202
  <>
420
203
  {errorContent ?? <div className={`${th.error} mb-4`}>
421
204
  <p>Sorry, there was an error uploading your data.</p>
422
205
  <p>Please try again or contact the researcher.</p>
423
206
  </div>}
424
- <button onClick={handleUpload} className={btnClass}>
425
- Try Again
207
+ <button onClick={handleUpload} className={th.button}>
208
+ {retryButtonText}
426
209
  </button>
427
210
  </>
428
211
  )}
@@ -430,3 +213,44 @@ export default function Upload({
430
213
  </div>
431
214
  );
432
215
  }
216
+
217
+ export default defineComponent({
218
+ name: 'Upload',
219
+ component: Upload,
220
+ csv: null,
221
+ params,
222
+ simulate: async ({ props, data, store, components, participant, initialParticipant }) => {
223
+ const sessionId = props.sessionId || `sim_${Date.now()}_${Math.floor(uniform(0, 36 ** 6)).toString(36)}`;
224
+ const files = buildUploadFiles({
225
+ sessionId,
226
+ data,
227
+ store,
228
+ components,
229
+ generateFiles: props.generateFiles,
230
+ sessionData: props.sessionData,
231
+ uploadRaw: props.uploadRaw,
232
+ });
233
+
234
+ files.push({
235
+ filename: `${sessionId}_participant_initial.csv`,
236
+ content: convertArrayOfObjectsToCSV([initialParticipant]),
237
+ encoding: 'utf8',
238
+ });
239
+ files.push({
240
+ filename: `${sessionId}_participant_final.csv`,
241
+ content: convertArrayOfObjectsToCSV([participant]),
242
+ encoding: 'utf8',
243
+ });
244
+
245
+ const res = await post('/data', {
246
+ sessionId,
247
+ ...(props.parentFolder ? { parentFolder: props.parentFolder } : {}),
248
+ files: files.map((f) => ({ ...f, encoding: f.encoding ?? 'utf8' })),
249
+ });
250
+ if (!res.ok) {
251
+ console.error(`Simulation upload failed: ${res.status} ${res.statusText}`);
252
+ }
253
+
254
+ return { recorded: { files } };
255
+ },
256
+ });