-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathApp.tsx
More file actions
1567 lines (1391 loc) · 50 KB
/
Copy pathApp.tsx
File metadata and controls
1567 lines (1391 loc) · 50 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
/**
* NativeBridge App - Production Android Testing Application
*
* Features:
* ✅ UI Components (buttons, inputs, switches, scrolling)
* ✅ Network Operations (GET, POST, download, upload)
* ✅ Performance Testing (CPU intensive, Memory intensive)
* ✅ Permissions (Camera, Location, Contacts, Storage)
* ✅ Device Access (Vibration, Linking, Clipboard)
* ✅ Storage (AsyncStorage simulation)
* ✅ File Operations (Upload, Save CSV, File Management)
* ✅ Biometric Authentication (optional testing)
* ✅ QR Code Scanning with Camera Injection Support
* ✅ Comprehensive Logging
*/
import React, { useState } from 'react';
import {
StatusBar,
StyleSheet,
Text,
View,
TouchableOpacity,
TextInput,
ScrollView,
Alert,
Switch,
Platform,
ToastAndroid,
PermissionsAndroid,
Linking,
Vibration,
SafeAreaView,
ActivityIndicator,
} from 'react-native';
import Clipboard from '@react-native-clipboard/clipboard';
import DocumentPicker from 'react-native-document-picker';
import RNFS from 'react-native-fs';
import ReactNativeBiometrics from 'react-native-biometrics';
import { RNCamera } from 'react-native-camera';
// Logging helper with timestamps and categories
const logEvent = (category: string, message: string) => {
const timestamp = new Date().toISOString();
const logMessage = `[NativeBridge][${category}] ${timestamp}: ${message}`;
console.log(logMessage);
if (Platform.OS === 'android') {
ToastAndroid.show(`${category}: ${message}`, ToastAndroid.SHORT);
}
};
function App() {
// ==================== AUTHENTICATION STATE ====================
// No longer required on app launch - app opens directly
// Tab state
const [activeTab, setActiveTab] = useState('ui');
// UI Tab state
const [textInput, setTextInput] = useState('');
const [buttonPressCount, setButtonPressCount] = useState(0);
const [switchValue, setSwitchValue] = useState(false);
// Network Tab state
const [networkStatus, setNetworkStatus] = useState('');
const [networkData, setNetworkData] = useState('');
// Performance Tab state
const [performanceResult, setPerformanceResult] = useState('');
const [isPerformanceLoading, setIsPerformanceLoading] = useState(false);
// Storage Tab state
const [storageData, setStorageData] = useState('');
const [clipboardText, setClipboardText] = useState('');
// Simple in-memory storage (simulating AsyncStorage)
const [inMemoryStorage, setInMemoryStorage] = useState<{[key: string]: string}>({});
// Files Tab state
const [uploadedFiles, setUploadedFiles] = useState<any[]>([]);
const [savedFiles, setSavedFiles] = useState<string[]>([]);
const [fileOperationStatus, setFileOperationStatus] = useState('');
// Biometric Tab state
const [biometricAvailable, setBiometricAvailable] = useState(false);
const [biometricType, setBiometricType] = useState('');
const [biometricStatus, setBiometricStatus] = useState('');
// Camera/QR Tab state
const [showCamera, setShowCamera] = useState(false);
const [qrData, setQrData] = useState('');
const [lastScannedQR, setLastScannedQR] = useState('');
// ==================== UI TAB HANDLERS ====================
const handleButtonPress = () => {
logEvent('UI', `Button pressed - count: ${buttonPressCount + 1}`);
setButtonPressCount(buttonPressCount + 1);
Alert.alert('Button Pressed', `Count: ${buttonPressCount + 1}`);
};
const handleLongPress = () => {
logEvent('UI', 'Long press detected');
Vibration.vibrate(100);
Alert.alert('Long Press', 'You performed a long press!');
};
const handleSwitchToggle = (value: boolean) => {
logEvent('UI', `Switch toggled to: ${value}`);
setSwitchValue(value);
};
// ==================== NETWORK TAB HANDLERS ====================
const handleNetworkGet = async () => {
try {
logEvent('NETWORK', 'Starting GET request to JSONPlaceholder');
setNetworkStatus('Downloading...');
const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
const data = await response.json();
setNetworkData(JSON.stringify(data, null, 2));
setNetworkStatus(`✓ Downloaded: ${data.title}`);
logEvent('NETWORK', `GET request successful. Title: ${data.title}`);
} catch (error) {
const errorMsg = error instanceof Error ? error.message : 'Unknown error';
setNetworkStatus(`✗ Error: ${errorMsg}`);
logEvent('NETWORK', `GET request failed: ${errorMsg}`);
}
};
const handleNetworkPost = async () => {
try {
logEvent('NETWORK', 'Starting POST request to JSONPlaceholder');
setNetworkStatus('Uploading...');
const postData = {
title: 'NativeBridge Test',
body: 'Test data from NativeBridge app',
userId: 1,
};
const response = await fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(postData),
});
const data = await response.json();
setNetworkData(JSON.stringify(data, null, 2));
setNetworkStatus(`✓ Uploaded: Created post ID ${data.id}`);
logEvent('NETWORK', `POST request successful. Created ID: ${data.id}`);
} catch (error) {
const errorMsg = error instanceof Error ? error.message : 'Unknown error';
setNetworkStatus(`✗ Error: ${errorMsg}`);
logEvent('NETWORK', `POST request failed: ${errorMsg}`);
}
};
// ==================== PERFORMANCE TAB HANDLERS ====================
// CPU intensive: Recursive Fibonacci
const fibonacci = (n: number): number => {
if (n <= 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
};
const handleCPUTest = () => {
logEvent('PERFORMANCE', 'Starting CPU intensive test (Fibonacci 40)');
setPerformanceResult('');
setIsPerformanceLoading(true);
setTimeout(() => {
const startTime = Date.now();
const result = fibonacci(40);
const endTime = Date.now();
const duration = endTime - startTime;
const resultText = `Fibonacci(40) = ${result}\nTime: ${duration}ms`;
setPerformanceResult(resultText);
setIsPerformanceLoading(false);
logEvent('PERFORMANCE', `CPU test completed in ${duration}ms`);
}, 100);
};
const handleMemoryTest = () => {
logEvent('PERFORMANCE', 'Starting Memory intensive test (sorting 1M elements)');
setPerformanceResult('');
setIsPerformanceLoading(true);
setTimeout(() => {
const startTime = Date.now();
const largeArray = Array.from({ length: 1000000 }, () => Math.random());
largeArray.sort((a, b) => a - b);
const endTime = Date.now();
const duration = endTime - startTime;
const resultText = `Sorted 1,000,000 elements\nTime: ${duration}ms\nMemory used: ~${(largeArray.length * 8 / 1024 / 1024).toFixed(2)}MB`;
setPerformanceResult(resultText);
setIsPerformanceLoading(false);
logEvent('PERFORMANCE', `Memory test completed in ${duration}ms`);
}, 100);
};
// ==================== PERMISSIONS TAB HANDLERS ====================
const requestCameraPermission = async () => {
try {
logEvent('PERMISSION', 'Requesting camera permission');
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.CAMERA,
{
title: 'Camera Permission',
message: 'NativeBridge needs access to your camera',
buttonNeutral: 'Ask Me Later',
buttonNegative: 'Cancel',
buttonPositive: 'OK',
}
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
logEvent('PERMISSION', 'Camera permission granted');
Alert.alert('Permission Granted', 'Camera access granted');
} else {
logEvent('PERMISSION', 'Camera permission denied');
Alert.alert('Permission Denied', 'Camera access denied');
}
} catch (error) {
logEvent('PERMISSION', `Camera permission error: ${error}`);
}
};
const requestLocationPermission = async () => {
try {
logEvent('PERMISSION', 'Requesting location permission');
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{
title: 'Location Permission',
message: 'NativeBridge needs access to your location',
buttonNeutral: 'Ask Me Later',
buttonNegative: 'Cancel',
buttonPositive: 'OK',
}
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
logEvent('PERMISSION', 'Location permission granted');
Alert.alert('Permission Granted', 'Location access granted');
} else {
logEvent('PERMISSION', 'Location permission denied');
Alert.alert('Permission Denied', 'Location access denied');
}
} catch (error) {
logEvent('PERMISSION', `Location permission error: ${error}`);
}
};
const requestStoragePermission = async () => {
try {
logEvent('PERMISSION', 'Requesting storage permission');
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
{
title: 'Storage Permission',
message: 'NativeBridge needs access to your storage',
buttonNeutral: 'Ask Me Later',
buttonNegative: 'Cancel',
buttonPositive: 'OK',
}
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
logEvent('PERMISSION', 'Storage permission granted');
Alert.alert('Permission Granted', 'Storage access granted');
} else {
logEvent('PERMISSION', 'Storage permission denied');
Alert.alert('Permission Denied', 'Storage access denied');
}
} catch (error) {
logEvent('PERMISSION', `Storage permission error: ${error}`);
}
};
const requestContactsPermission = async () => {
try {
logEvent('PERMISSION', 'Requesting contacts permission');
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.READ_CONTACTS,
{
title: 'Contacts Permission',
message: 'NativeBridge needs access to your contacts',
buttonNeutral: 'Ask Me Later',
buttonNegative: 'Cancel',
buttonPositive: 'OK',
}
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
logEvent('PERMISSION', 'Contacts permission granted');
Alert.alert('Permission Granted', 'Contacts access granted');
} else {
logEvent('PERMISSION', 'Contacts permission denied');
Alert.alert('Permission Denied', 'Contacts access denied');
}
} catch (error) {
logEvent('PERMISSION', `Contacts permission error: ${error}`);
}
};
// System Feature Handlers
const handleVibration = () => {
logEvent('SYSTEM', 'Triggering vibration pattern');
Vibration.vibrate([0, 100, 200, 100, 200]);
Alert.alert('Vibration', 'Device vibrating with pattern');
};
const handleOpenBrowser = () => {
const url = 'https://www.google.com';
logEvent('SYSTEM', `Opening browser: ${url}`);
Linking.openURL(url).catch((err) => {
logEvent('SYSTEM', `Failed to open URL: ${err}`);
});
};
const handleMakePhoneCall = () => {
const phoneNumber = 'tel:1234567890';
logEvent('SYSTEM', `Initiating phone call to: ${phoneNumber}`);
Linking.openURL(phoneNumber).catch((err) => {
logEvent('SYSTEM', `Failed to make call: ${err}`);
});
};
const handleSendEmail = () => {
const email = 'mailto:test@example.com?subject=Test&body=Hello';
logEvent('SYSTEM', `Opening email client: ${email}`);
Linking.openURL(email).catch((err) => {
logEvent('SYSTEM', `Failed to open email: ${err}`);
});
};
// ==================== STORAGE TAB HANDLERS ====================
const handleCopyToClipboard = () => {
const textToCopy = textInput || 'NativeBridge Test Data';
Clipboard.setString(textToCopy);
logEvent('CLIPBOARD', `Copied to clipboard: ${textToCopy}`);
Alert.alert('Copied', `"${textToCopy}" copied to clipboard`);
};
const handlePasteFromClipboard = async () => {
try {
const text = await Clipboard.getString();
setClipboardText(text);
logEvent('CLIPBOARD', `Pasted from clipboard: ${text}`);
Alert.alert('Pasted', `Clipboard content: "${text}"`);
} catch (error) {
logEvent('CLIPBOARD', `Failed to read clipboard: ${error}`);
Alert.alert('Error', 'Failed to read from clipboard');
}
};
const handleSaveToStorage = () => {
const key = 'testData';
const value = textInput || 'Default test data';
setInMemoryStorage({ ...inMemoryStorage, [key]: value });
logEvent('STORAGE', `Saved to storage - Key: ${key}, Value: ${value}`);
Alert.alert('Saved', `Data saved: "${value}"`);
};
const handleLoadFromStorage = () => {
const key = 'testData';
const value = inMemoryStorage[key] || 'No data found';
setStorageData(value);
logEvent('STORAGE', `Loaded from storage - Key: ${key}, Value: ${value}`);
Alert.alert('Loaded', `Data loaded: "${value}"`);
};
const handleClearStorage = () => {
setInMemoryStorage({});
setStorageData('');
logEvent('STORAGE', 'Storage cleared');
Alert.alert('Cleared', 'All storage data cleared');
};
// ==================== FILES TAB HANDLERS ====================
const handleFilePicker = async () => {
try {
logEvent('FILES', 'Opening file picker');
setFileOperationStatus('Opening file picker...');
const result = await DocumentPicker.pick({
type: [DocumentPicker.types.allFiles],
allowMultiSelection: false,
});
if (result && result.length > 0) {
const file = result[0];
setUploadedFiles([...uploadedFiles, file]);
setFileOperationStatus(`✓ File uploaded: ${file.name}`);
logEvent('FILES', `File picked: ${file.name}, Size: ${file.size} bytes, Type: ${file.type}`);
Alert.alert('File Uploaded', `${file.name}\nSize: ${(file.size! / 1024).toFixed(2)} KB`);
}
} catch (error) {
if (DocumentPicker.isCancel(error)) {
logEvent('FILES', 'File picker cancelled');
setFileOperationStatus('File picker cancelled');
} else {
const errorMsg = error instanceof Error ? error.message : 'Unknown error';
logEvent('FILES', `File picker error: ${errorMsg}`);
setFileOperationStatus(`✗ Error: ${errorMsg}`);
Alert.alert('Error', `Failed to pick file: ${errorMsg}`);
}
}
};
const handleSaveCSV = async () => {
try {
logEvent('FILES', 'Generating and saving CSV file');
setFileOperationStatus('Generating CSV...');
// Request storage permissions
if (Platform.OS === 'android') {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE
);
if (granted !== PermissionsAndroid.RESULTS.GRANTED) {
Alert.alert('Permission Denied', 'Storage permission is required to save files');
return;
}
}
// Generate sample CSV data
const csvData = `Name,Value,Timestamp
Test Data 1,${Math.random().toFixed(2)},${new Date().toISOString()}
Test Data 2,${Math.random().toFixed(2)},${new Date().toISOString()}
Test Data 3,${Math.random().toFixed(2)},${new Date().toISOString()}
Test Data 4,${Math.random().toFixed(2)},${new Date().toISOString()}
Test Data 5,${Math.random().toFixed(2)},${new Date().toISOString()}`;
// Create filename with timestamp
const timestamp = new Date().getTime();
const filename = `nativebridge_data_${timestamp}.csv`;
const path = `${RNFS.DownloadDirectoryPath}/${filename}`;
// Write file
await RNFS.writeFile(path, csvData, 'utf8');
setSavedFiles([...savedFiles, filename]);
setFileOperationStatus(`✓ CSV saved: ${filename}`);
logEvent('FILES', `CSV file saved: ${path}`);
Alert.alert('File Saved', `CSV file saved to:\n${path}`);
} catch (error) {
const errorMsg = error instanceof Error ? error.message : 'Unknown error';
logEvent('FILES', `Save CSV error: ${errorMsg}`);
setFileOperationStatus(`✗ Error: ${errorMsg}`);
Alert.alert('Error', `Failed to save CSV: ${errorMsg}`);
}
};
const handleListSavedFiles = async () => {
try {
logEvent('FILES', 'Listing saved files in Downloads');
setFileOperationStatus('Reading files...');
const downloadPath = RNFS.DownloadDirectoryPath;
const files = await RNFS.readDir(downloadPath);
// Filter for CSV files created by this app
const csvFiles = files
.filter(file => file.name.startsWith('nativebridge_') && file.name.endsWith('.csv'))
.map(file => file.name);
setSavedFiles(csvFiles);
setFileOperationStatus(`✓ Found ${csvFiles.length} saved file(s)`);
logEvent('FILES', `Found ${csvFiles.length} saved CSV files`);
if (csvFiles.length === 0) {
Alert.alert('No Files', 'No saved CSV files found in Downloads folder');
} else {
Alert.alert('Saved Files', `Found ${csvFiles.length} file(s):\n${csvFiles.slice(0, 5).join('\n')}`);
}
} catch (error) {
const errorMsg = error instanceof Error ? error.message : 'Unknown error';
logEvent('FILES', `List files error: ${errorMsg}`);
setFileOperationStatus(`✗ Error: ${errorMsg}`);
Alert.alert('Error', `Failed to list files: ${errorMsg}`);
}
};
const handleClearUploadedFiles = () => {
setUploadedFiles([]);
setFileOperationStatus('Uploaded files list cleared');
logEvent('FILES', 'Cleared uploaded files list');
Alert.alert('Cleared', 'Uploaded files list cleared');
};
const handleDeleteSavedFile = async (filename: string) => {
try {
const path = `${RNFS.DownloadDirectoryPath}/${filename}`;
await RNFS.unlink(path);
setSavedFiles(savedFiles.filter(f => f !== filename));
setFileOperationStatus(`✓ Deleted: ${filename}`);
logEvent('FILES', `Deleted file: ${filename}`);
Alert.alert('Deleted', `File deleted: ${filename}`);
} catch (error) {
const errorMsg = error instanceof Error ? error.message : 'Unknown error';
logEvent('FILES', `Delete file error: ${errorMsg}`);
Alert.alert('Error', `Failed to delete file: ${errorMsg}`);
}
};
// ==================== BIOMETRIC TAB HANDLERS ====================
const checkBiometricAvailability = async () => {
try {
logEvent('BIOMETRIC', 'Checking biometric sensor availability');
setBiometricStatus('Checking...');
// Try with allowDeviceCredentials option for broader compatibility
const rnBiometrics = new ReactNativeBiometrics({
allowDeviceCredentials: true
});
const result = await rnBiometrics.isSensorAvailable();
const { available, biometryType } = result;
// Log to both app events and console (visible in adb logcat)
console.log('[BIOMETRIC DEBUG] Full result:', JSON.stringify(result));
console.log('[BIOMETRIC DEBUG] available:', available);
console.log('[BIOMETRIC DEBUG] biometryType:', biometryType);
logEvent('BIOMETRIC', `Full result: ${JSON.stringify(result)}`);
setBiometricAvailable(available);
let typeStr = 'None';
// Handle all possible biometry types
if (biometryType === 'Biometrics') {
typeStr = 'Fingerprint/Biometrics';
} else if (biometryType === 'FaceID') {
typeStr = 'Face ID';
} else if (biometryType === 'TouchID' || biometryType === 'Fingerprint') {
typeStr = 'Touch ID/Fingerprint';
} else if (biometryType) {
// If we get any other non-null value, show it
typeStr = biometryType;
}
setBiometricType(typeStr);
logEvent('BIOMETRIC', `Raw biometryType: ${biometryType}, available: ${available}`);
if (available) {
setBiometricStatus(`✓ Available: ${typeStr}`);
logEvent('BIOMETRIC', `Biometric available: ${typeStr}`);
Alert.alert('Biometric Available', `Type: ${typeStr}\n\nYou can now use the authentication button below.`);
} else {
setBiometricStatus('✗ No biometric sensor available');
logEvent('BIOMETRIC', `No biometric sensor available (biometryType: ${biometryType})`);
// More detailed error message
let errorDetail = 'No biometric sensor found on this device.';
if (biometryType === null || biometryType === undefined) {
errorDetail += '\n\nPossible reasons:\n1. No fingerprint enrolled in device Settings > Security > Fingerprint\n2. Biometric hardware not detected\n3. Device security not set up (PIN/Pattern/Password required first)';
}
Alert.alert('Not Available', errorDetail);
}
} catch (error) {
const errorMsg = error instanceof Error ? error.message : 'Unknown error';
setBiometricStatus(`✗ Error: ${errorMsg}`);
logEvent('BIOMETRIC', `Check availability error: ${errorMsg}`);
// Check if it's a common error
let userMessage = `Failed to check biometric: ${errorMsg}`;
if (errorMsg.includes('not available')) {
userMessage = 'Biometric authentication is not available on this device.\n\nPlease check:\n1. Set up a screen lock (PIN/Pattern/Password) in Settings\n2. Enroll at least one fingerprint in Settings > Security\n3. Restart the app after enrollment';
}
Alert.alert('Error', userMessage);
}
};
const handleBiometricAuth = async () => {
try {
logEvent('BIOMETRIC', 'Starting biometric authentication');
setBiometricStatus('Authenticating...');
const rnBiometrics = new ReactNativeBiometrics();
const { success } = await rnBiometrics.simplePrompt({
promptMessage: 'Authenticate with Biometrics',
cancelButtonText: 'Cancel',
});
if (success) {
setBiometricStatus('✓ Authentication successful!');
logEvent('BIOMETRIC', 'Authentication successful');
Alert.alert('Success', 'Biometric authentication successful!');
} else {
setBiometricStatus('✗ Authentication failed');
logEvent('BIOMETRIC', 'Authentication failed or cancelled');
Alert.alert('Failed', 'Biometric authentication failed or cancelled');
}
} catch (error) {
const errorMsg = error instanceof Error ? error.message : 'Unknown error';
setBiometricStatus(`✗ Error: ${errorMsg}`);
logEvent('BIOMETRIC', `Authentication error: ${errorMsg}`);
Alert.alert('Error', `Failed to authenticate: ${errorMsg}`);
}
};
const createBiometricKeys = async () => {
try {
logEvent('BIOMETRIC', 'Creating biometric keys');
setBiometricStatus('Creating keys...');
const rnBiometrics = new ReactNativeBiometrics();
const { publicKey } = await rnBiometrics.createKeys();
setBiometricStatus('✓ Keys created successfully');
logEvent('BIOMETRIC', `Keys created. Public key: ${publicKey.substring(0, 50)}...`);
Alert.alert('Keys Created', `Public Key (truncated):\n${publicKey.substring(0, 100)}...`);
} catch (error) {
const errorMsg = error instanceof Error ? error.message : 'Unknown error';
setBiometricStatus(`✗ Error: ${errorMsg}`);
logEvent('BIOMETRIC', `Create keys error: ${errorMsg}`);
Alert.alert('Error', `Failed to create keys: ${errorMsg}`);
}
};
const deleteBiometricKeys = async () => {
try {
logEvent('BIOMETRIC', 'Deleting biometric keys');
setBiometricStatus('Deleting keys...');
const rnBiometrics = new ReactNativeBiometrics();
const { keysDeleted } = await rnBiometrics.deleteKeys();
if (keysDeleted) {
setBiometricStatus('✓ Keys deleted successfully');
logEvent('BIOMETRIC', 'Keys deleted');
Alert.alert('Success', 'Biometric keys deleted');
} else {
setBiometricStatus('✗ No keys to delete');
logEvent('BIOMETRIC', 'No keys found to delete');
Alert.alert('Info', 'No biometric keys found');
}
} catch (error) {
const errorMsg = error instanceof Error ? error.message : 'Unknown error';
setBiometricStatus(`✗ Error: ${errorMsg}`);
logEvent('BIOMETRIC', `Delete keys error: ${errorMsg}`);
Alert.alert('Error', `Failed to delete keys: ${errorMsg}`);
}
};
// ==================== CAMERA/QR TAB HANDLERS ====================
const handleOpenCamera = async () => {
try {
logEvent('CAMERA', 'Opening camera for QR scanning');
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.CAMERA
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
setShowCamera(true);
setQrData('');
logEvent('CAMERA', 'Camera opened successfully');
} else {
logEvent('CAMERA', 'Camera permission denied');
Alert.alert('Permission Denied', 'Camera permission is required for QR scanning');
}
} catch (error) {
logEvent('CAMERA', `Camera open error: ${error}`);
Alert.alert('Error', 'Failed to open camera');
}
};
const handleCloseCamera = () => {
setShowCamera(false);
logEvent('CAMERA', 'Camera closed');
};
const onBarCodeRead = (scanResult: any) => {
if (scanResult.data && scanResult.data !== lastScannedQR) {
setLastScannedQR(scanResult.data);
setQrData(scanResult.data);
logEvent('QR_SCAN', `QR Code scanned: ${scanResult.data}`);
Alert.alert(
'QR Code Scanned',
`Data: ${scanResult.data}\nType: ${scanResult.type}`,
[
{
text: 'OK',
onPress: () => {
// Reset after a delay to allow scanning again
setTimeout(() => setLastScannedQR(''), 2000);
},
},
]
);
Vibration.vibrate(200);
}
};
// ==================== RENDER FUNCTIONS ====================
const renderTabBar = () => (
<View style={styles.tabBar}>
<TouchableOpacity
style={[styles.tab, activeTab === 'ui' && styles.activeTab]}
onPress={() => setActiveTab('ui')}
testID="tab-ui"
>
<Text style={[styles.tabText, activeTab === 'ui' && styles.activeTabText]}>
UI
</Text>
</TouchableOpacity>
<TouchableOpacity
style={[styles.tab, activeTab === 'network' && styles.activeTab]}
onPress={() => setActiveTab('network')}
testID="tab-network"
>
<Text style={[styles.tabText, activeTab === 'network' && styles.activeTabText]}>
Network
</Text>
</TouchableOpacity>
<TouchableOpacity
style={[styles.tab, activeTab === 'performance' && styles.activeTab]}
onPress={() => setActiveTab('performance')}
testID="tab-performance"
>
<Text style={[styles.tabText, activeTab === 'performance' && styles.activeTabText]}>
Perf
</Text>
</TouchableOpacity>
<TouchableOpacity
style={[styles.tab, activeTab === 'permissions' && styles.activeTab]}
onPress={() => setActiveTab('permissions')}
testID="tab-permissions"
>
<Text style={[styles.tabText, activeTab === 'permissions' && styles.activeTabText]}>
Perms
</Text>
</TouchableOpacity>
<TouchableOpacity
style={[styles.tab, activeTab === 'storage' && styles.activeTab]}
onPress={() => setActiveTab('storage')}
testID="tab-storage"
>
<Text style={[styles.tabText, activeTab === 'storage' && styles.activeTabText]}>
Storage
</Text>
</TouchableOpacity>
<TouchableOpacity
style={[styles.tab, activeTab === 'files' && styles.activeTab]}
onPress={() => setActiveTab('files')}
testID="tab-files"
>
<Text style={[styles.tabText, activeTab === 'files' && styles.activeTabText]}>
Files
</Text>
</TouchableOpacity>
<TouchableOpacity
style={[styles.tab, activeTab === 'biometric' && styles.activeTab]}
onPress={() => setActiveTab('biometric')}
testID="tab-biometric"
>
<Text style={[styles.tabText, activeTab === 'biometric' && styles.activeTabText]}>
Bio
</Text>
</TouchableOpacity>
<TouchableOpacity
style={[styles.tab, activeTab === 'camera' && styles.activeTab]}
onPress={() => setActiveTab('camera')}
testID="tab-camera"
>
<Text style={[styles.tabText, activeTab === 'camera' && styles.activeTabText]}>
QR
</Text>
</TouchableOpacity>
</View>
);
const renderUITab = () => (
<ScrollView style={styles.tabContent}>
{/* Button Testing */}
<View style={styles.section}>
<Text style={styles.sectionTitle}>Button Testing</Text>
<TouchableOpacity
style={styles.button}
onPress={handleButtonPress}
onLongPress={handleLongPress}
testID="test-button"
>
<Text style={styles.buttonText}>Tap Me (or Long Press)!</Text>
</TouchableOpacity>
<Text style={styles.infoText} testID="button-counter">
Button pressed: {buttonPressCount} times
</Text>
</View>
{/* Text Input Testing */}
<View style={styles.section}>
<Text style={styles.sectionTitle}>Text Input</Text>
<TextInput
style={styles.textInput}
placeholder="Enter some text"
value={textInput}
onChangeText={setTextInput}
testID="text-input"
/>
<Text style={styles.infoText} testID="input-display">
Current text: {textInput}
</Text>
</View>
{/* Switch Testing */}
<View style={styles.section}>
<Text style={styles.sectionTitle}>Switch Testing</Text>
<View style={styles.switchContainer}>
<Text style={styles.label}>Toggle Switch:</Text>
<Switch
value={switchValue}
onValueChange={handleSwitchToggle}
testID="test-switch"
/>
</View>
<Text style={styles.infoText} testID="switch-status">
Switch is: {switchValue ? 'ON' : 'OFF'}
</Text>
</View>
{/* Scrollable Area */}
<View style={styles.section}>
<Text style={styles.sectionTitle}>Scrollable Area</Text>
<ScrollView
style={styles.scrollView}
testID="scrollable-area"
showsVerticalScrollIndicator={true}
>
{Array.from({ length: 20 }, (_, i) => (
<View key={i} style={styles.scrollItem} testID={`scroll-item-${i}`}>
<Text>Scrollable Item {i + 1}</Text>
</View>
))}
</ScrollView>
</View>
</ScrollView>
);
const renderNetworkTab = () => (
<ScrollView style={styles.tabContent}>
<View style={styles.section}>
<Text style={styles.sectionTitle}>Network Operations</Text>
<TouchableOpacity
style={styles.button}
onPress={handleNetworkGet}
testID="network-get-button"
>
<Text style={styles.buttonText}>GET Request (Download)</Text>
</TouchableOpacity>
<TouchableOpacity
style={[styles.button, {marginTop: 10}]}
onPress={handleNetworkPost}
testID="network-post-button"
>
<Text style={styles.buttonText}>POST Request (Upload)</Text>
</TouchableOpacity>
<Text style={[styles.sectionTitle, {marginTop: 20}]} testID="network-status">
Status: {networkStatus || 'Ready'}
</Text>
{networkData ? (
<ScrollView style={styles.dataDisplay}>
<Text style={styles.dataText} testID="network-data">
{networkData}
</Text>
</ScrollView>
) : null}
</View>
</ScrollView>
);
const renderPerformanceTab = () => (
<ScrollView style={styles.tabContent}>
<View style={styles.section}>
<Text style={styles.sectionTitle}>Performance Testing</Text>
<TouchableOpacity
style={styles.button}
onPress={handleCPUTest}
testID="cpu-test-button"
disabled={isPerformanceLoading}
>
<Text style={styles.buttonText}>Run CPU Test (Fibonacci 40)</Text>
</TouchableOpacity>
<TouchableOpacity
style={[styles.button, {marginTop: 10}]}
onPress={handleMemoryTest}
testID="memory-test-button"
disabled={isPerformanceLoading}
>
<Text style={styles.buttonText}>Run Memory Test (Sort 1M)</Text>
</TouchableOpacity>
{isPerformanceLoading ? (
<View style={styles.loaderBox}>
<ActivityIndicator size="large" color="#007AFF" />
<Text style={styles.loaderText}>Running test...</Text>
</View>
) : null}
{performanceResult && !isPerformanceLoading ? (
<View style={styles.resultBox}>
<Text style={styles.resultText} testID="performance-result">
{performanceResult}
</Text>
</View>
) : null}
</View>
</ScrollView>
);
const renderPermissionsTab = () => (
<ScrollView style={styles.tabContent}>
{/* Permission Requests */}
<View style={styles.section}>
<Text style={styles.sectionTitle}>Permission Requests</Text>
<TouchableOpacity
style={styles.button}
onPress={requestCameraPermission}
testID="request-camera-button"
>
<Text style={styles.buttonText}>Request Camera</Text>
</TouchableOpacity>
<TouchableOpacity
style={[styles.button, {marginTop: 10}]}
onPress={requestLocationPermission}
testID="request-location-button"
>
<Text style={styles.buttonText}>Request Location</Text>
</TouchableOpacity>
<TouchableOpacity
style={[styles.button, {marginTop: 10}]}
onPress={requestStoragePermission}
testID="request-storage-button"
>
<Text style={styles.buttonText}>Request Storage</Text>
</TouchableOpacity>
<TouchableOpacity
style={[styles.button, {marginTop: 10}]}
onPress={requestContactsPermission}
testID="request-contacts-button"
>
<Text style={styles.buttonText}>Request Contacts</Text>
</TouchableOpacity>
</View>
{/* System Features */}
<View style={styles.section}>
<Text style={styles.sectionTitle}>System Features</Text>
<TouchableOpacity
style={styles.button}
onPress={handleVibration}
testID="vibrate-button"
>
<Text style={styles.buttonText}>Vibrate Device</Text>
</TouchableOpacity>
<TouchableOpacity
style={[styles.button, {marginTop: 10}]}
onPress={handleOpenBrowser}
testID="open-browser-button"
>
<Text style={styles.buttonText}>Open Browser</Text>
</TouchableOpacity>