forked from OpenDataEnsemble/ode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFormulusMessageHandlers.ts
More file actions
1196 lines (1105 loc) · 38.2 KB
/
FormulusMessageHandlers.ts
File metadata and controls
1196 lines (1105 loc) · 38.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
This is where the actual implementation of the methods happens on the React Native side.
It handles the messages received from the WebView and executes the corresponding native functionality.
*/
import { GeolocationService } from '../services/GeolocationService';
import { WebViewMessageEvent, WebView } from 'react-native-webview';
import RNFS from 'react-native-fs';
import * as Keychain from 'react-native-keychain';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { Alert, Platform } from 'react-native';
import * as ImagePicker from 'react-native-image-picker';
import {
check,
request,
PERMISSIONS,
RESULTS,
Permission,
} from 'react-native-permissions';
import {
pick,
types,
isErrorWithCode,
errorCodes,
} from '@react-native-documents/picker';
import {
FormInitData,
FormCompletionResult,
FormInfo,
} from './FormulusInterfaceDefinition';
import { FormulusMessageHandlers } from './FormulusMessageHandlers.types';
// NitroSound is disabled for emulator in react-native.config.js - do not load the module
// to avoid "Sound HybridObject not registered" console errors. Load lazily only when
// the native module is available (re-enable in react-native.config.js and rebuild).
let NitroSound: {
startRecorder: (path: string, opts: unknown) => Promise<void>;
stopRecorder: () => Promise<void>;
} | null = null;
type AudioSet = {
AudioSamplingRate: number;
AudioEncodingBitRate: number;
AudioChannels: number;
};
import { FormService } from '../services/FormService';
import { Observation, ObservationData } from '../database/models/Observation';
import {
getAttachmentsDirectoryFileUrl,
getCustomAppDirectoryFileUrl,
getFormSpecsDirectoryFileUrl,
resolveAttachmentFileUrl,
} from '../services/WebViewFileUrlResolver';
import { commitDraftAttachmentsAfterSave } from '../services/attachmentStorage';
export type HandlerArgs = {
data: unknown;
webViewRef: React.RefObject<WebView | null>;
event: WebViewMessageEvent;
};
export type Handler = (args: HandlerArgs) => void | Promise<void>;
// Simple event emitter for cross-component communication
export type Listener = (...args: unknown[]) => void;
class SimpleEventEmitter {
private listeners: Record<string, Listener[]> = {};
addListener(eventName: string, listener: Listener): void {
if (!this.listeners[eventName]) {
this.listeners[eventName] = [];
}
this.listeners[eventName].push(listener);
}
removeListener(eventName: string, listener: Listener): void {
if (!this.listeners[eventName]) return;
this.listeners[eventName] = this.listeners[eventName].filter(
l => l !== listener,
);
}
emit(eventName: string, ...args: unknown[]): void {
if (!this.listeners[eventName]) return;
this.listeners[eventName].forEach(listener => listener(...args));
}
}
export const appEvents = new SimpleEventEmitter();
async function ensureCameraPermission(): Promise<string> {
const wanted: Permission | undefined = Platform.select({
ios: PERMISSIONS.IOS.CAMERA,
android: PERMISSIONS.ANDROID.CAMERA,
});
if (!wanted) {
return RESULTS.GRANTED;
}
let status = await check(wanted);
if (status === RESULTS.DENIED) {
status = await request(wanted);
}
return status;
}
const pendingFormOperations = new Map<
string,
{
resolve: (result: FormCompletionResult) => void;
reject: (error: Error) => void;
formType: string;
startTime: number;
}
>();
const startFormplayerOperation = (
formType: string,
params: Record<string, unknown> = {},
savedData: Record<string, unknown> = {},
observationId: string | null = null,
): Promise<FormCompletionResult> => {
const operationId = `${formType}_${Date.now()}_${Math.random()
.toString(36)
.substr(2, 9)}`;
return new Promise<FormCompletionResult>((resolve, reject) => {
pendingFormOperations.set(operationId, {
resolve,
reject,
formType,
startTime: Date.now(),
});
appEvents.emit('openFormplayerRequested', {
formType,
params,
savedData,
observationId,
operationId,
});
setTimeout(
() => {
if (pendingFormOperations.has(operationId)) {
pendingFormOperations.delete(operationId);
reject(new Error('Form operation timed out'));
}
},
8 * 60 * 60 * 1000,
);
});
};
export const openFormplayerFromNative = (
formType: string,
params: Record<string, unknown> = {},
savedData: Record<string, unknown> = {},
observationId: string | null = null,
): Promise<FormCompletionResult> => {
return startFormplayerOperation(formType, params, savedData, observationId);
};
let activeFormplayerModalRef: {
handleSubmission: (data: {
formType: string;
finalData: Record<string, unknown>;
observationId?: string | null;
}) => Promise<string>;
} | null = null;
export const setActiveFormplayerModal = (
modalRef: {
handleSubmission: (data: {
formType: string;
finalData: Record<string, unknown>;
observationId?: string | null;
}) => Promise<string>;
} | null,
) => {
activeFormplayerModalRef = modalRef;
};
export const resolveFormOperation = (
operationId: string,
result: FormCompletionResult,
) => {
const operation = pendingFormOperations.get(operationId);
if (operation) {
operation.resolve(result);
pendingFormOperations.delete(operationId);
}
};
// Helper to resolve operation by form type (fallback when operationId is not available)
export const resolveFormOperationByType = (
formType: string,
result: FormCompletionResult,
) => {
// Find the most recent operation for this form type
let mostRecentOperation: string | null = null;
let mostRecentTime = 0;
for (const [operationId, operation] of pendingFormOperations.entries()) {
if (
operation.formType === formType &&
operation.startTime > mostRecentTime
) {
mostRecentOperation = operationId;
mostRecentTime = operation.startTime;
}
}
if (mostRecentOperation) {
resolveFormOperation(mostRecentOperation, result);
} else {
console.warn(`No pending operation found for form type: ${formType}`);
}
};
export const rejectFormOperation = (operationId: string, error: Error) => {
const operation = pendingFormOperations.get(operationId);
if (operation) {
operation.reject(error);
pendingFormOperations.delete(operationId);
}
};
const saveFormData = async (
formType: string,
data: ObservationData,
observationId: string | null,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
isPartial = true,
) => {
try {
const observation: Partial<Observation> = {
formType,
data,
};
if (observationId !== null) {
observation.observationId = observationId;
observation.updatedAt = new Date();
} else {
observation.createdAt = new Date();
}
const formService = await FormService.getInstance();
const id =
observationId !== null
? await formService.updateObservation(observationId, data)
: await formService.addNewObservation(formType, data);
if (id != null) {
const fixedData = await commitDraftAttachmentsAfterSave(
data as Record<string, unknown>,
);
await formService.updateObservation(id, fixedData);
}
return id;
} catch (error) {
console.error('Error saving form data:', error);
return null;
}
};
export function createFormulusMessageHandlers(): FormulusMessageHandlers {
return {
onInitForm: (payload: unknown) => {
// TODO: implement init form logic
console.log('FormulusMessageHandlers: onInitForm called', payload);
},
onGetVersion: async (): Promise<string> => {
console.log('FormulusMessageHandlers: onGetVersion handler invoked.');
// Replace with your actual version retrieval logic.
const version = '0.1.0-native'; // Example version
return version;
},
onSubmitObservation: async (data: {
formType: string;
finalData: Record<string, unknown>;
}) => {
const { formType, finalData } = data;
console.log(
'FormulusMessageHandlers: onSubmitObservation handler invoked.',
{ formType, finalData },
);
// Use the active FormplayerModal's handleSubmission method if available
if (activeFormplayerModalRef) {
console.log(
'FormulusMessageHandlers: Delegating to FormplayerModal.handleSubmission',
);
return await activeFormplayerModalRef.handleSubmission({
formType,
finalData,
});
} else {
// Fallback to the old method if no modal is active
console.warn(
'FormulusMessageHandlers: No active FormplayerModal, using fallback saveFormData',
);
return await saveFormData(formType, finalData, null, false);
}
},
onUpdateObservation: async (data: {
observationId: string;
formType: string;
finalData: Record<string, unknown>;
}) => {
// Formplayer uses updateObservation for existing rows; submitObservation for new.
// Route updates through the modal too so the operation promise resolves and the UI closes.
if (activeFormplayerModalRef) {
console.log(
'FormulusMessageHandlers: Delegating to FormplayerModal.handleSubmission (update)',
);
return await activeFormplayerModalRef.handleSubmission({
formType: data.formType,
finalData: data.finalData,
observationId: data.observationId,
});
}
return await saveFormData(
data.formType,
data.finalData,
data.observationId,
false,
);
},
onRequestCamera: async (fieldId: string): Promise<unknown> => {
console.log('Request camera handler called', fieldId);
return new Promise(resolve => {
try {
if (!ImagePicker || !ImagePicker.launchImageLibrary) {
console.error(
'react-native-image-picker not available or not properly linked',
);
resolve({
fieldId,
status: 'error',
message:
'Image picker functionality not available. Please ensure react-native-image-picker is properly installed and linked.',
});
return;
}
// Image picker options for react-native-image-picker
const options = {
mediaType: 'photo' as const,
quality: 0.8 as const,
includeBase64: true,
maxWidth: 1920,
maxHeight: 1080,
storageOptions: {
skipBackup: true,
path: 'images',
},
};
console.log(
'Launching image picker with camera and gallery options, options:',
options,
);
// Common response handler for both camera and gallery
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const handleImagePickerResponse = (response: any) => {
console.log('Camera response received:', response);
if (response.didCancel) {
console.log('User cancelled camera');
resolve({
fieldId,
status: 'cancelled',
message: 'Camera operation cancelled by user',
});
} else if (response.errorCode || response.errorMessage) {
console.error(
'Camera error:',
response.errorCode,
response.errorMessage,
);
resolve({
fieldId,
status: 'error',
message:
response.errorMessage ||
`Camera error: ${response.errorCode}`,
});
} else if (response.assets && response.assets.length > 0) {
// Photo captured successfully
const asset = response.assets[0];
// Generate GUID for the image
const generateGUID = () => {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(
/[xy]/g,
function (c) {
const r = Math.floor(Math.random() * 16);
const v = c === 'x' ? r : (r % 4) + 8;
return v.toString(16);
},
);
};
const imageGuid = generateGUID();
const guidFilename = `${imageGuid}.jpg`;
console.log(
'Photo captured, processing for persistent storage:',
{
imageGuid,
guidFilename,
tempUri: asset.uri,
size: asset.fileSize,
},
);
const attachmentsDirectory = `${RNFS.DocumentDirectoryPath}/attachments`;
const draftDirectory = `${attachmentsDirectory}/draft`;
const draftFilePath = `${draftDirectory}/${guidFilename}`;
console.log('Copying camera image to draft attachment storage:', {
source: asset.uri,
draftPath: draftFilePath,
});
Promise.all([
RNFS.mkdir(attachmentsDirectory),
RNFS.mkdir(draftDirectory),
])
.then(() => RNFS.copyFile(asset.uri, draftFilePath))
.then(() => {
console.log(
'Image saved to draft attachments:',
draftFilePath,
);
const webViewUrl = `file://${draftFilePath}`;
resolve({
fieldId,
status: 'success',
data: {
type: 'image',
id: imageGuid,
filename: guidFilename,
uri: draftFilePath,
url: webViewUrl,
timestamp: new Date().toISOString(),
metadata: {
width: asset.width || 1920,
height: asset.height || 1080,
size: asset.fileSize || 0,
mimeType: 'image/jpeg',
source: 'react-native-image-picker',
quality: 0.8,
originalFileName: asset.fileName || guidFilename,
persistentStorage: true,
storageLocation: 'draft_attachments',
syncReady: false,
},
},
});
})
.catch(error => {
console.error(
'Error copying image to attachment sync system:',
error,
);
resolve({
fieldId,
status: 'error',
message: `Failed to save image: ${error.message}`,
});
});
} else {
console.error('Unexpected camera response format:', response);
resolve({
fieldId,
status: 'error',
message: 'Unexpected camera response format',
});
}
};
// Show action sheet with camera and gallery options
Alert.alert('Select Image', 'Choose an option', [
{
text: 'Camera',
onPress: () => {
void (async () => {
const perm = await ensureCameraPermission();
if (perm !== RESULTS.GRANTED) {
resolve({
fieldId,
status: 'error',
message:
perm === RESULTS.BLOCKED
? 'Camera access is blocked. Enable camera permission in system settings.'
: 'Camera permission is required to take a photo.',
});
return;
}
ImagePicker.launchCamera(options, handleImagePickerResponse);
})();
},
},
{
text: 'Gallery',
onPress: () => {
ImagePicker.launchImageLibrary(
options,
handleImagePickerResponse,
);
},
},
{
text: 'Cancel',
style: 'cancel',
onPress: () => {
resolve({
fieldId,
status: 'cancelled',
message: 'Image selection cancelled by user',
});
},
},
]);
} catch (error) {
console.error('Error in native camera handler:', error);
const errorMessage =
error instanceof Error ? error.message : 'Unknown error';
resolve({
fieldId,
status: 'error',
message: `Camera error: ${errorMessage}`,
});
}
});
},
onRequestQrcode: async (fieldId: string): Promise<unknown> => {
console.log('Request QR code handler called', fieldId);
return new Promise(resolve => {
try {
// Emit event to open QR scanner modal
appEvents.emit('openQRScanner', {
fieldId,
onResult: (result: unknown) => {
console.log('QR scan result received:', result);
resolve(result);
},
});
} catch (error) {
console.error('Error in QR code handler:', error);
const errorMessage =
error instanceof Error ? error.message : 'Unknown error';
resolve({
fieldId,
status: 'error',
message: `QR code error: ${errorMessage}`,
});
}
});
},
onRequestSignature: async (fieldId: string): Promise<unknown> => {
console.log('Request signature handler called', fieldId);
return new Promise(resolve => {
try {
// Emit event to open signature capture modal
appEvents.emit('openSignatureCapture', {
fieldId,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
onResult: async (result: any) => {
console.log('Signature capture result received:', result);
try {
// If the result contains base64 data, save it to file and return URI
if (
result.status === 'success' &&
result.data &&
result.data.base64
) {
// Generate a unique filename
const timestamp = Date.now();
const filename = `signature_${timestamp}.png`;
// Create signatures directory path
const signaturesDir = `${RNFS.DocumentDirectoryPath}/signatures`;
const filePath = `${signaturesDir}/${filename}`;
// Ensure signatures directory exists
await RNFS.mkdir(signaturesDir);
// Write base64 data to file
await RNFS.writeFile(filePath, result.data.base64, 'base64');
// Get file stats for size
const fileStats = await RNFS.stat(filePath);
// Create updated result with URI instead of base64
const updatedResult = {
fieldId,
status: 'success' as const,
data: {
type: 'signature' as const,
filename,
uri: `file://${filePath}`,
timestamp:
result.data.timestamp || new Date().toISOString(),
metadata: {
width: result.data.metadata?.width || 400,
height: result.data.metadata?.height || 200,
size: fileStats.size,
strokeCount: result.data.metadata?.strokeCount || 1,
},
},
};
console.log('Signature saved to file:', filePath);
resolve(updatedResult);
} else {
// Return result as-is if no base64 data or if it's an error/cancellation
resolve(result);
}
} catch (fileError) {
console.error('Error saving signature file:', fileError);
resolve({
fieldId,
status: 'error',
message: `Error saving signature: ${fileError}`,
});
}
},
});
} catch (error) {
console.error('Error in signature handler:', error);
const errorMessage =
error instanceof Error ? error.message : 'Unknown error';
resolve({
fieldId,
status: 'error',
message: `Signature error: ${errorMessage}`,
});
}
});
},
onRequestLocation: async (fieldId: string): Promise<unknown> => {
console.log('Request location handler called', fieldId);
// eslint-disable-next-line no-async-promise-executor
return new Promise(async (resolve, reject) => {
try {
// Get current location using the existing GeolocationService
const geolocationService = GeolocationService.getInstance();
const position =
await geolocationService.getCurrentLocationForObservation();
if (position) {
// Convert ObservationGeolocation to LocationResultData format
const locationResult = {
fieldId,
status: 'success' as const,
data: {
type: 'location' as const,
latitude: position.latitude || 0,
longitude: position.longitude || 0,
accuracy: position.accuracy,
altitude: position.altitude,
altitudeAccuracy: position.altitude_accuracy,
timestamp: position.timestamp ?? new Date().toISOString(),
},
};
console.log('Location captured successfully:', locationResult);
resolve(locationResult);
} else {
throw new Error('Unable to get current location');
}
} catch (error) {
console.error('Location capture failed:', error);
const errorResult = {
fieldId,
status: 'error' as const,
message: 'Location capture failed',
};
reject(errorResult);
}
});
},
onRequestVideo: async (fieldId: string): Promise<unknown> => {
return new Promise((resolve, reject) => {
try {
const options = {
mediaType: 'video' as const,
videoQuality: 'high' as const,
durationLimit: 60, // 60 seconds max
storageOptions: {
skipBackup: true,
path: 'videos',
},
};
ImagePicker.launchCamera(options, async response => {
if (response.didCancel) {
console.log('Video recording cancelled');
reject({
fieldId,
status: 'cancelled',
message: 'Video recording was cancelled by user',
});
return;
}
if (response.errorMessage) {
console.error('Video recording error:', response.errorMessage);
reject({
fieldId,
status: 'error',
message: `Video recording error: ${response.errorMessage}`,
});
return;
}
if (response.assets && response.assets.length > 0) {
const asset = response.assets[0];
try {
// Generate a unique filename
const timestamp = Date.now();
const filename = `video_${timestamp}.${
asset.type?.split('/')[1] || 'mp4'
}`;
// Copy video to app storage directory
const destinationPath = `${RNFS.DocumentDirectoryPath}/videos/${filename}`;
// Ensure videos directory exists
await RNFS.mkdir(`${RNFS.DocumentDirectoryPath}/videos`);
// Copy the video file
if (asset.uri) {
await RNFS.copyFile(asset.uri, destinationPath);
} else {
console.error('Asset uri not available', asset);
}
const videoResult = {
fieldId,
status: 'success' as const,
data: {
type: 'video' as const,
filename,
uri: `file://${destinationPath}`,
timestamp: new Date().toISOString(),
metadata: {
duration: asset.duration || 0,
format: asset.type?.split('/')[1] || 'mp4',
size: asset.fileSize || 0,
width: asset.width,
height: asset.height,
},
},
};
console.log('Video recorded successfully:', videoResult);
resolve(videoResult);
} catch (fileError) {
console.error('Error saving video file:', fileError);
reject({
fieldId,
status: 'error',
message: `Error saving video: ${fileError}`,
});
}
} else {
reject({
fieldId,
status: 'error',
message: 'No video data received',
});
}
});
} catch (error) {
console.error('Error in video handler:', error);
const errorMessage =
error instanceof Error ? error.message : 'Unknown error';
reject({
fieldId,
status: 'error',
message: `Video error: ${errorMessage}`,
});
}
});
},
onRequestFile: async (fieldId: string) => {
console.log('Request file handler called (v12 API)', fieldId);
try {
const [result] = await pick({
type: [types.allFiles],
mode: 'import',
allowMultiSelection: false,
});
console.log('File selected:', result);
return {
fieldId,
status: 'success' as const,
data: {
filename: result.name,
uri: result.uri,
size: result.size || 0,
mimeType: result.type || 'application/octet-stream',
type: 'file' as const,
timestamp: new Date().toISOString(),
},
};
} catch (error) {
if (isErrorWithCode(error)) {
if (error.code === errorCodes.OPERATION_CANCELED) {
return {
fieldId,
status: 'cancelled' as const,
message: 'File selection was cancelled',
};
}
}
return {
fieldId,
status: 'error' as const,
message:
error instanceof Error ? error.message : 'Failed to select file',
};
}
},
onLaunchIntent: (fieldId: string, intentSpec: Record<string, unknown>) => {
// TODO: implement launch intent logic
console.log('Launch intent handler called', fieldId, intentSpec);
},
onCallSubform: (
fieldId: string,
formType: string,
options: Record<string, unknown>,
) => {
// TODO: implement call subform logic
console.log('Call subform handler called', fieldId, formType, options);
},
onRequestAudio: async (fieldId: string) => {
// Lazy-load NitroSound only when audio is requested (avoids console error on startup when disabled)
if (!NitroSound) {
try {
// eslint-disable-next-line @typescript-eslint/no-require-imports
const ns = require('react-native-nitro-sound');
NitroSound = ns.default;
} catch {
NitroSound = null;
}
}
if (!NitroSound) {
return {
fieldId,
status: 'error' as const,
message:
'Audio recording not available. Re-enable react-native-nitro-sound in react-native.config.js and rebuild.',
};
}
try {
const filename = `audio_${Date.now()}.m4a`;
const path = `${RNFS.DocumentDirectoryPath}/${filename}`;
const audioSet: AudioSet = {
// Common settings automatically applied to the appropriate platform
AudioSamplingRate: 44100,
AudioEncodingBitRate: 128000,
AudioChannels: 1,
};
await NitroSound.startRecorder(path, audioSet);
// For demo purposes, we'll record for a fixed duration
// In a real implementation, you'd want user controls for start/stop
await new Promise<void>(r => setTimeout(() => r(), 3000));
await NitroSound.stopRecorder();
const fileStats = await RNFS.stat(path);
return {
fieldId,
status: 'success' as const,
data: {
type: 'audio' as const,
filename: filename,
uri: `file://${path}`,
timestamp: new Date().toISOString(),
metadata: {
duration: 3.0,
format: 'm4a',
size: fileStats.size || 0,
},
},
};
} catch (error) {
console.log('Audio recording error:', error);
// Check if this is a user cancellation or permission error
console.log('Audio recording error:', error);
if (typeof error === 'object' && error !== null) {
const err = error as Record<string, unknown>;
if (
err.code === 'PERMISSION_DENIED' ||
(typeof err.message === 'string' &&
err.message.includes('permission'))
) {
return {
fieldId,
status: 'error' as const,
message:
'Microphone permission denied. Please enable microphone access in settings.',
};
}
if (err.code === 'USER_CANCELLED') {
return {
fieldId,
status: 'cancelled' as const,
message: 'Audio recording was cancelled',
};
}
return {
fieldId,
status: 'error' as const,
message:
typeof err.message === 'string'
? err.message
: 'Failed to record audio',
};
}
return {
fieldId,
status: 'error' as const,
message: String(error),
};
}
},
onRequestBiometric: (fieldId: string) => {
// TODO: implement biometric request logic
console.log('Request biometric handler called', fieldId);
},
onRequestConnectivityStatus: () => {
// TODO: implement connectivity status logic
console.log('Request connectivity status handler called');
},
onRequestSyncStatus: () => {
// TODO: implement sync status logic
console.log('Request sync status handler called');
},
onRunLocalModel: (
fieldId: string,
modelId: string,
input: Record<string, unknown>,
) => {
// TODO: implement run local model logic
console.log('Run local model handler called', fieldId, modelId, input);
},
onGetAvailableForms: async (): Promise<FormInfo[]> => {
try {
const formService = await FormService.getInstance();
const formSpecs = formService.getFormSpecs();
return formSpecs.map(spec => {
const schema = spec.schema || {};
const properties = schema.properties || {};
const coreFields: string[] = [];
const auxiliaryFields: string[] = [];
// Extract fields from schema properties
Object.keys(properties).forEach(fieldName => {
const field = properties[fieldName] || {};
const isCore =
field['x-core'] === true || fieldName.startsWith('core_');
if (isCore) {
coreFields.push(fieldName);
} else {
auxiliaryFields.push(fieldName);
}
});
return {