-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathFormplayerModal.tsx
More file actions
862 lines (783 loc) · 28.4 KB
/
Copy pathFormplayerModal.tsx
File metadata and controls
862 lines (783 loc) · 28.4 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
import React, {
useRef,
useEffect,
useState,
useCallback,
useImperativeHandle,
forwardRef,
} from 'react';
import {
StyleSheet,
View,
Modal,
TouchableOpacity,
Text,
Platform,
ActivityIndicator,
} from 'react-native';
import CustomAppWebView, {
CustomAppWebViewHandle,
} from '../components/CustomAppWebView';
import { useScreenShellStyle } from '../hooks/useScreenShellStyle';
import Icon from '@react-native-vector-icons/material-icons';
import {
resolveFormOperation,
resolveFormOperationByType,
setActiveFormplayerModal,
clearActiveFormplayerModalIfMatches,
} from '../webview/FormulusMessageHandlers';
import {
FormCompletionResult,
FormInitData,
} from '../webview/FormulusInterfaceDefinition';
import { databaseService } from '../database';
import colors from '../theme/colors';
import {
odeSpacing,
odeTypography,
odeBorderWidth,
odeFormplayerHeaderHeight,
} from '../theme/odeDesign';
import { FormSpec, FormService } from '../services';
import { collectLinkedFormIds } from '../utils/collectLinkedFormIds';
import { ExtensionService } from '../services/ExtensionService';
import RNFS from 'react-native-fs';
import { useAppTheme } from '../contexts/AppThemeContext';
import { useConfirmModal } from '../contexts/ConfirmModalContext';
import { geolocationService } from '../services/GeolocationService';
import { persistObservationWithAttachments } from '../services/attachmentStorage';
import { localeSettingsService } from '../services/LocaleSettingsService';
import { formLocaleSettingsService } from '../services/FormLocaleSettingsService';
import { useTranslation } from 'react-i18next';
async function buildLinkedFormSpecs(
schema: unknown,
): Promise<FormInitData['linkedFormSpecs']> {
const linkedIds = collectLinkedFormIds(schema);
if (linkedIds.size === 0) return undefined;
try {
const formService = await FormService.getInstance();
const specs: NonNullable<FormInitData['linkedFormSpecs']> = {};
for (const id of linkedIds) {
const spec = formService.getFormSpecById(id);
if (!spec?.schema) continue;
specs[id] = {
schema: spec.schema,
uiSchema: spec.uiSchema ?? {},
};
}
return Object.keys(specs).length > 0 ? specs : undefined;
} catch (error) {
console.warn('[FormplayerModal] Failed to load linked form specs:', error);
return undefined;
}
}
interface FormplayerModalProps {
visible: boolean;
isActive?: boolean;
onClose: () => void;
}
export interface FormplayerModalHandle {
initializeForm: (
formType: FormSpec,
params: Record<string, unknown> | null,
observationId: string | null,
existingObservationData: Record<string, unknown> | null,
operationId: string | null,
subObservationMode?: boolean,
skipFinalize?: boolean,
skipDraftSelection?: boolean,
) => void;
handleSubmission: (data: {
formType: string;
finalData: Record<string, unknown>;
observationId?: string | null;
}) => Promise<string>;
}
const FormplayerModal = forwardRef<FormplayerModalHandle, FormplayerModalProps>(
({ visible, isActive = true, onClose }, ref) => {
const webViewRef = useRef<CustomAppWebViewHandle>(null);
const [isSubmitting, setIsSubmitting] = useState(false);
const { showConfirm } = useConfirmModal();
const { t } = useTranslation();
// Theme colors & resolved mode from AppThemeContext.
const { themeColors, resolvedMode } = useAppTheme();
const shellStyle = useScreenShellStyle();
// Internal state to track current form and observation data
const [currentFormType, setCurrentFormType] = useState<string | null>(null);
const [currentObservationId, setCurrentObservationId] = useState<
string | null
>(null);
const [_currentObservationData, setCurrentObservationData] =
useState<Record<string, unknown> | null>(null);
const [_currentParams, setCurrentParams] = useState<Record<
string,
unknown
> | null>(null);
const [currentOperationId, setCurrentOperationId] = useState<string | null>(
null,
);
// Track if form has been successfully submitted to avoid double resolution
const [formSubmitted, setFormSubmitted] = useState(false);
// Sub-observation (embedded child) forms: return JSON only; do not persist as top-level observations.
// Ref updates synchronously in initializeForm so submit cannot run before flag is set.
const subObservationModeRef = useRef(false);
const skipFinalizeRef = useRef(false);
// Author-configurable display name shown in the native header bar
const [currentFormDisplayName, setCurrentFormDisplayName] = useState<
string | null
>(null);
// Add state to track closing process and prevent multiple close attempts
const [isClosing, setIsClosing] = useState(false);
const closeTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
// Path to the formplayer dist folder in assets
const formplayerUri =
Platform.OS === 'android'
? 'file:///android_asset/formplayer_dist/index.html'
: `file://${RNFS.MainBundlePath}/formplayer_dist/index.html`;
// Create a debounced close handler to prevent multiple rapid close attempts
const performClose = useCallback(() => {
// Prevent multiple close attempts
if (isClosing || isSubmitting) return;
setIsClosing(true);
// Clear any existing timeout
if (closeTimeoutRef.current) {
clearTimeout(closeTimeoutRef.current);
}
// Only resolve with cancelled status if form hasn't been successfully submitted AND we have a valid operation
if (!formSubmitted && currentOperationId) {
const completionResult: FormCompletionResult = {
status: 'cancelled',
formType: currentFormType || 'unknown',
message: 'Form was closed without submission',
};
resolveFormOperation(currentOperationId, completionResult);
// Clear the operation ID immediately to prevent double resolution
setCurrentOperationId(null);
} else if (!formSubmitted && currentFormType) {
const completionResult: FormCompletionResult = {
status: 'cancelled',
formType: currentFormType,
message: 'Form was closed without submission',
};
resolveFormOperationByType(currentFormType, completionResult);
}
geolocationService.endObservationSession();
onClose();
// Reset closing state after a short delay to prevent rapid re-opening issues
closeTimeoutRef.current = setTimeout(() => {
setIsClosing(false);
}, 500);
}, [
isClosing,
isSubmitting,
onClose,
currentOperationId,
currentFormType,
formSubmitted,
]);
const handleClose = useCallback(() => {
if (isClosing || isSubmitting) return;
if (webViewRef.current?.canGoBack?.()) {
webViewRef.current.goBack();
return;
}
showConfirm({
title: t('formplayer.closeTitle'),
message: t('formplayer.closeMessage'),
buttons: [
{ text: t('common.cancel'), variant: 'tertiary', onPress: () => {} },
{ text: t('common.close'), variant: 'danger', onPress: performClose },
],
});
}, [isClosing, isSubmitting, performClose, showConfirm, t]);
// Removed closeFormplayer event listener - now using direct promise-based submission handling
// Cleanup timeout on unmount
useEffect(() => {
return () => {
if (closeTimeoutRef.current) {
clearTimeout(closeTimeoutRef.current);
}
geolocationService.endObservationSession();
};
}, []);
// Track WebView ready state
const [webViewReady, setWebViewReady] = useState(false);
const previousIsActiveRef = useRef(isActive);
// Handle WebView load complete
const handleWebViewLoad = () => {
console.log('[FormplayerModal] WebView finished loading');
setWebViewReady(true);
// WebView is now ready to receive form initialization
};
// Initialize a form with the given form type and optional existing data
const initializeForm = async (
formType: FormSpec,
params: Record<string, unknown> | null,
observationId: string | null,
existingObservationData: Record<string, unknown> | null,
operationId: string | null,
subObservationMode: boolean = false,
skipFinalize: boolean = false,
skipDraftSelection: boolean = false,
) => {
// Check if WebView is ready, if not log a warning (retry logic will handle it)
if (!webViewReady) {
console.warn(
'[FormplayerModal] WebView not ready yet, form init will be queued by message handler',
);
}
subObservationModeRef.current = subObservationMode;
skipFinalizeRef.current = skipFinalize;
// GPS session: skip for sub-observations (data is not persisted with geo).
if (!subObservationMode) {
geolocationService.beginObservationSession();
}
setCurrentFormType(formType.id);
setCurrentObservationId(observationId);
// Resolve display name: ui schema headerTitle > schema title > form spec name
const uiSchemaObj = formType.uiSchema as
| Record<string, unknown>
| undefined;
const schemaObj = formType.schema as Record<string, unknown> | undefined;
const uiOptions = uiSchemaObj?.options as
| Record<string, unknown>
| undefined;
const displayName =
(uiOptions?.headerTitle as string) ||
(schemaObj?.title as string) ||
formType.name;
setCurrentFormDisplayName(displayName);
setCurrentObservationData(existingObservationData);
setCurrentParams(params);
setCurrentOperationId(operationId);
setFormSubmitted(false); // Reset submission flag for new form
// Forward the custom app's theme colors to the Formplayer WebView so
// that form UI elements (buttons, inputs, headers) match the branding.
const isDark = resolvedMode === 'dark';
const sessionLocale =
params && typeof params.locale === 'string' ? params.locale : null;
const resolvedLocale =
await localeSettingsService.resolveActiveLocale(sessionLocale);
const sessionFormLocale =
params && typeof params.formLocale === 'string'
? params.formLocale
: null;
const savedFormLocale =
existingObservationData &&
typeof existingObservationData.formLocale === 'string'
? existingObservationData.formLocale
: null;
const resolvedFormLocale =
await formLocaleSettingsService.resolveActiveFormLocale(
sessionFormLocale,
savedFormLocale,
);
const formParams = {
theme: 'default',
darkMode: isDark,
themeColors, // ← custom app palette forwarded to Formplayer
...params,
locale: resolvedLocale,
formLocale: resolvedFormLocale,
};
// Load extensions for this form
const customAppPath = RNFS.DocumentDirectoryPath + '/app';
let extensions = undefined;
try {
const extensionService = ExtensionService.getInstance();
const mergedExtensions = await extensionService.getCustomAppExtensions(
customAppPath,
formType.id,
);
// Note: getDynamicChoiceList is provided by formplayer's builtinExtensions.
// Do NOT add a fallback pointing to queryHelpers.js - that file may not exist
// in the app bundle, and dynamic import of file:// in WebView often fails.
if (!mergedExtensions.functions) {
mergedExtensions.functions = {};
}
// Convert to formplayer format
if (
mergedExtensions.definitions ||
mergedExtensions.functions ||
mergedExtensions.renderers
) {
extensions = {
definitions: mergedExtensions.definitions,
functions: Object.entries(mergedExtensions.functions).reduce(
(acc, [key, func]) => {
// Remove leading slash from module path to avoid double-slash in URL
const modulePath = (func.module || '').replace(/^\/+/, '');
acc[key] = {
name: func.name,
module: modulePath,
export: func.export,
};
return acc;
},
{} as Record<string, unknown>,
),
renderers: Object.entries(mergedExtensions.renderers).reduce(
(acc, [key, renderer]) => {
// Remove leading slash from module path to avoid double-slash in URL
const modulePath = (renderer.module || '').replace(/^\/+/, '');
acc[key] = {
name: renderer.name,
format: renderer.format,
module: modulePath,
tester: renderer.tester,
renderer: renderer.renderer,
};
return acc;
},
{} as Record<string, unknown>,
),
// Base path for loading modules (file:// URL for WebView)
// Extensions are in the /forms directory
basePath: `file://${customAppPath}/forms`,
};
}
} catch (error) {
console.warn('Failed to load extensions:', error);
// Continue without extensions - not a fatal error
}
if (!formType.schema) {
console.error(
'FormplayerModal: formType.schema is null/undefined for form:',
formType.id,
);
showConfirm({
title: t('formplayer.formErrorTitle'),
message: t('formplayer.noSchemaMessage', { name: formType.name }),
buttons: [
{ text: t('common.ok'), variant: 'primary', onPress: () => {} },
],
});
return;
}
// Scan custom question types and validators, read their source code
// Check app/question_types and app/validators (bundle root) and app/forms/question_types, app/forms/validators (legacy)
let customQuestionTypes = undefined;
try {
const qtDirs = [
`${customAppPath}/question_types`,
`${customAppPath}/forms/question_types`,
RNFS.DocumentDirectoryPath + '/forms/question_types',
];
const validatorDirs = [
`${customAppPath}/validators`,
`${customAppPath}/forms/validators`,
RNFS.DocumentDirectoryPath + '/forms/validators',
];
const custom_types: Record<string, { source: string }> = {};
const validators: Record<string, { source: string }> = {};
// Scan custom question types
for (const qtDir of qtDirs) {
const qtDirExists = await RNFS.exists(qtDir);
if (!qtDirExists) {
continue;
}
const folders = await RNFS.readDir(qtDir);
for (const folder of folders) {
if (folder.isDirectory() && !custom_types[folder.name]) {
// Try renderer.js first, then index.js as fallback
const rendererPath = `${folder.path}/renderer.js`;
const indexPath = `${folder.path}/index.js`;
const hasRenderer = await RNFS.exists(rendererPath);
const hasIndex = !hasRenderer && (await RNFS.exists(indexPath));
const jsPath = hasRenderer
? rendererPath
: hasIndex
? indexPath
: null;
if (jsPath) {
// Read the source code so the WebView can evaluate it directly
const source = await RNFS.readFile(jsPath, 'utf8');
custom_types[folder.name] = { source };
console.log(
`[FormplayerModal] Custom question type: "${folder.name}" (${source.length} bytes from ${jsPath})`,
);
} else {
console.warn(
`[FormplayerModal] Skipping "${folder.name}": no renderer.js or index.js found`,
);
}
}
}
}
// Scan custom validators
for (const validatorDir of validatorDirs) {
const validatorDirExists = await RNFS.exists(validatorDir);
if (!validatorDirExists) {
continue;
}
const folders = await RNFS.readDir(validatorDir);
for (const folder of folders) {
if (folder.isDirectory() && !validators[folder.name]) {
// Validators use index.js (standard convention)
const indexPath = `${folder.path}/index.js`;
const hasIndex = await RNFS.exists(indexPath);
if (hasIndex) {
// Read the source code so the WebView can evaluate it directly
const source = await RNFS.readFile(indexPath, 'utf8');
validators[folder.name] = { source };
console.log(
`[FormplayerModal] Custom validator: "${folder.name}" (${source.length} bytes from ${indexPath})`,
);
} else {
console.warn(
`[FormplayerModal] Skipping validator "${folder.name}": no index.js found`,
);
}
}
}
}
// Build manifest with both question types and validators
if (
Object.keys(custom_types).length > 0 ||
Object.keys(validators).length > 0
) {
customQuestionTypes = {
custom_types:
Object.keys(custom_types).length > 0 ? custom_types : undefined,
validators:
Object.keys(validators).length > 0 ? validators : undefined,
};
} else {
console.warn(
'[FormplayerModal] No custom question types or validators found in any path',
);
}
} catch (error) {
console.warn(
'Failed to scan custom question types and validators:',
error,
);
}
const formInitData = {
formType: formType.id,
observationId: observationId,
params: formParams,
savedData: existingObservationData || {},
formSchema: formType.schema,
uiSchema: formType.uiSchema ?? {},
extensions,
customQuestionTypes,
subObservationMode,
skipFinalize,
skipDraftSelection,
linkedFormSpecs: await buildLinkedFormSpecs(formType.schema),
} as FormInitData;
if (!webViewRef.current) {
console.warn(
'FormplayerModal: WebView ref is not available when trying to initialize form',
);
return;
}
try {
await webViewRef.current.sendFormInit(formInitData);
} catch (error) {
console.error('FormplayerModal: Error sending form init data:', error);
showConfirm({
title: t('common.error'),
message: t('formplayer.initFailed'),
buttons: [
{ text: t('common.ok'), variant: 'primary', onPress: () => {} },
],
});
}
};
// Handle form submission directly (called by WebView message handler)
const handleSubmission = useCallback(
async (data: {
formType: string;
finalData: Record<string, unknown>;
observationId?: string | null;
}): Promise<string> => {
const {
formType,
finalData,
observationId: observationIdFromBridge,
} = data;
const effectiveObservationId =
observationIdFromBridge ?? currentObservationId;
// Set submitting state
setIsSubmitting(true);
try {
const subObservationMode = subObservationModeRef.current;
const localRepo = subObservationMode
? null
: databaseService.getLocalRepo();
if (!subObservationMode && !localRepo) {
throw new Error('Database repository not available');
}
const persistResult = await persistObservationWithAttachments(
{
formType,
finalData,
observationId: effectiveObservationId,
subObservationMode,
},
{
saveObservation: args =>
localRepo
? localRepo.saveObservation(args)
: Promise.resolve(null),
updateObservation: args =>
localRepo
? localRepo.updateObservation(args)
: Promise.resolve(false),
},
);
const resultObservationId = persistResult.observationId;
const resultFormData = persistResult.formData;
// Mark form as successfully submitted
setFormSubmitted(true);
// Resolve the form operation with success result
const completionResult: FormCompletionResult = {
status: effectiveObservationId ? 'form_updated' : 'form_submitted',
observationId: resultObservationId,
formData: resultFormData,
formType: formType,
};
if (currentOperationId) {
resolveFormOperation(currentOperationId, completionResult);
setCurrentOperationId(null);
} else {
resolveFormOperationByType(formType, completionResult);
}
if (subObservationModeRef.current && skipFinalizeRef.current) {
setIsSubmitting(false);
onClose();
return resultObservationId;
}
const successMessage = effectiveObservationId
? t('formplayer.submitSuccessUpdated')
: t('formplayer.submitSuccessSubmitted');
showConfirm({
title: t('common.success'),
message: successMessage,
buttons: [
{
text: t('common.ok'),
variant: 'primary',
onPress: () => {
setIsSubmitting(false);
onClose();
},
},
],
});
return resultObservationId;
} catch (error) {
console.error('FormplayerModal: Error in handleSubmission:', error);
setIsSubmitting(false);
// Resolve the form operation with error result
const errorResult: FormCompletionResult = {
status: 'error',
formType: formType,
message:
error instanceof Error ? error.message : 'Unknown error occurred',
};
if (currentOperationId) {
resolveFormOperation(currentOperationId, errorResult);
} else {
resolveFormOperationByType(formType, errorResult);
}
showConfirm({
title: t('common.error'),
message: t('formplayer.saveFailed'),
buttons: [
{ text: t('common.ok'), variant: 'primary', onPress: () => {} },
],
});
throw error;
}
},
[currentObservationId, currentOperationId, onClose, showConfirm, t],
);
// Register/unregister modal with message handlers and reset form state.
// Stacked modals (e.g. sub-observation child): parent stays visible but inactive — it must NOT
// clear the global ref, or the child's submit would miss the active modal and fail or persist wrongly.
useEffect(() => {
if (visible && isActive) {
setActiveFormplayerModal({ handleSubmission });
return () => {
clearActiveFormplayerModalIfMatches(handleSubmission);
};
}
if (!visible) {
const timeoutId = setTimeout(() => {
setCurrentFormType(null);
setCurrentFormDisplayName(null);
setCurrentObservationId(null);
setCurrentObservationData(null);
setIsClosing(false); // Reset closing state when modal is fully closed
setFormSubmitted(false); // Reset submission flag
setWebViewReady(false); // Reset WebView ready state
subObservationModeRef.current = false;
}, 300); // Small delay to ensure modal is fully closed
return () => clearTimeout(timeoutId);
}
return undefined;
}, [visible, isActive, handleSubmission]);
useEffect(() => {
if (
visible &&
isActive &&
webViewReady &&
currentFormType &&
previousIsActiveRef.current === false
) {
webViewRef.current?.notifyReceiveFocus();
}
previousIsActiveRef.current = isActive;
}, [visible, isActive, webViewReady, currentFormType]);
useImperativeHandle(ref, () => ({ initializeForm, handleSubmission }));
return (
<Modal
animationType="slide"
transparent={false}
visible={visible}
onRequestClose={handleClose}
presentationStyle="fullScreen"
statusBarTranslucent={false}>
<View style={shellStyle}>
<View
style={[
styles.container,
{ backgroundColor: themeColors.background as string },
]}>
<View
style={[
styles.header,
{
backgroundColor:
resolvedMode === 'dark'
? (colors.neutral[900] as string)
: (colors.neutral[50] as string),
borderBottomColor: themeColors.divider as string,
},
]}>
<TouchableOpacity
onPress={handleClose}
style={[
styles.closeButton,
(isSubmitting || isClosing) && styles.disabledButton,
]}
disabled={isSubmitting || isClosing}>
<Icon
name="close"
size={24}
color={
isSubmitting || isClosing
? colors.neutral[400]
: themeColors.onBackground
}
/>
</TouchableOpacity>
<Text
style={[
styles.headerTitle,
{ color: themeColors.onBackground },
]}
numberOfLines={1}
ellipsizeMode="tail">
{currentFormDisplayName ||
(currentObservationId
? 'Edit Observation'
: 'New Observation')}
</Text>
</View>
<CustomAppWebView
ref={webViewRef}
appUrl={formplayerUri}
appName="Formplayer"
backgroundColor={themeColors.background as string}
onLoadEndProp={handleWebViewLoad}
/>
{/* Loading overlay */}
{isSubmitting && (
<View style={styles.loadingOverlay}>
<View style={styles.loadingContainer}>
<ActivityIndicator
size="large"
color={colors.semantic.info.ios}
/>
<Text style={styles.loadingText}>
{t('formplayer.saving')}
</Text>
</View>
</View>
)}
</View>
</View>
</Modal>
);
},
);
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: colors.neutral.transparent,
},
header: {
flexDirection: 'row',
justifyContent: 'flex-start',
alignItems: 'center',
width: '100%',
paddingLeft: 6,
paddingRight: odeSpacing.sm,
paddingVertical: 2,
borderBottomWidth: odeBorderWidth.hairline,
minHeight: odeFormplayerHeaderHeight,
borderTopWidth: 0,
borderLeftWidth: 0,
borderRightWidth: 0,
borderRadius: 0,
overflow: 'visible',
},
headerTitle: {
fontSize: odeTypography.bodySm,
fontWeight: 'normal',
marginLeft: 8,
flex: 1,
flexShrink: 1,
},
closeButton: {
paddingVertical: 2,
paddingHorizontal: 2,
},
disabledButton: {
opacity: 0.5,
},
webview: {
flex: 1,
},
loadingOverlay: {
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0,
backgroundColor: colors.ui.background,
justifyContent: 'center',
alignItems: 'center',
},
loadingContainer: {
backgroundColor: colors.neutral.white,
padding: 20,
borderRadius: 10,
alignItems: 'center',
shadowColor: colors.neutral.black,
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.25,
shadowRadius: 3.84,
elevation: 5,
},
loadingText: {
marginTop: 10,
fontSize: 16,
color: colors.neutral[800],
},
});
export default FormplayerModal;