-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtext.txt
2169 lines (2034 loc) · 71 KB
/
text.txt
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
I am developing a simple mobile application that allows people to share their live location with others. I am currently trying to develop the part of it that will send regular location updates to the Firestone Database, and have it be fully functional on Android and iOS. I have it coded it in Native Expo React. When Radar detects a new location in the trip, it triggers a Webhook that calls my server.
I want to have my app work as efficiently as possible, with great accuracy and low battery usage. I am currently using Radar Labs' package to configure and setup location updates. I want to replicate the services of other apps like Google Maps sharing or WhatsApp sharing, but better.
Here is the current setup.
App.js
```javascript
// App.js
import React, { useEffect, useState } from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import { onAuthStateChanged } from 'firebase/auth';
import { ref, update } from 'firebase/database';
import { auth, db } from './firebaseConfig';
import Radar from 'react-native-radar';
import * as Location from 'expo-location';
import * as IntentLauncher from 'expo-intent-launcher';
import { Linking, Platform } from 'react-native';
// Screens
import PermissionScreen from './screens/PermissionScreen';
import LoadingScreen from './screens/LoadingScreen';
import LoginScreen from './screens/LoginScreen';
import SignupScreen from './screens/SignupScreen';
import HomeScreen from './screens/HomeScreen';
const Stack = createStackNavigator();
export default function App() {
// ----------------------------
// 1) State for Location Perms
// ----------------------------
const [isCheckingPermissions, setIsCheckingPermissions] = useState(true);
const [hasLocationPermissions, setHasLocationPermissions] = useState(false);
const [permissionErrorMessage, setPermissionErrorMessage] = useState('');
// ----------------------------
// 2) State for Auth
// ----------------------------
const [user, setUser] = useState(null);
const [initializing, setInitializing] = useState(true);
// ----------------------------
// 3) Check Location Perms
// On First Mount
// ----------------------------
useEffect(() => {
(async () => {
try {
// 1) Request Foreground
let fg = await Location.getForegroundPermissionsAsync();
if (fg.status !== 'granted') {
fg = await Location.requestForegroundPermissionsAsync();
if (fg.status !== 'granted') {
setPermissionErrorMessage(
'App needs "While Using" location to function.'
);
setHasLocationPermissions(false);
setIsCheckingPermissions(false);
return;
}
}
// 2) Request Background
let bg = await Location.getBackgroundPermissionsAsync();
if (bg.status !== 'granted') {
bg = await Location.requestBackgroundPermissionsAsync();
}
if (bg.status !== 'granted') {
// iOS may not grant 'Always' automatically. The user may have to manually enable it in Settings.
setPermissionErrorMessage(
'Please grant "Allow All the Time" location in Settings.'
);
setHasLocationPermissions(false);
} else {
setPermissionErrorMessage('');
setHasLocationPermissions(true);
}
} catch (err) {
console.log('Error checking permissions =>', err);
setPermissionErrorMessage(
'Error checking permissions. Please enable them in Settings.'
);
setHasLocationPermissions(false);
} finally {
setIsCheckingPermissions(false);
}
})();
}, []);
// ----------------------------
// 4) Radar Setup
// But Only If We Have Perms
// ----------------------------
useEffect(() => {
if (!hasLocationPermissions) return;
// Initialize Radar
Radar.initialize('prj_live_pk_2bb1459eda8faeaf64aa70990ca689ee231f5b42');
Radar.setLogLevel('debug'); // Remove or set to 'none' in production
Radar.on('error', (err) => {
console.error('Radar error =>', err);
});
// Cleanup
return () => {
Radar.off('location');
Radar.off('error');
};
}, [hasLocationPermissions]);
// ----------------------------
// 5) Auth Listener
// ----------------------------
useEffect(() => {
const unsubscribe = onAuthStateChanged(auth, async (currentUser) => {
setUser(currentUser);
setInitializing(false);
if (currentUser) {
Radar.setUserId(currentUser.uid);
Radar.setDescription(currentUser.email || 'Radar User');
Radar.setMetadata({ role: 'tester' });
// Request location permissions in two stages (foreground, then background)
try {
const fgStatus = await Radar.requestPermissions(false);
console.log('Foreground perms =>', fgStatus);
if (fgStatus === 'GRANTED_FOREGROUND') {
const bgStatus = await Radar.requestPermissions(true);
console.log('Background perms =>', bgStatus);
}
} catch (err) {
console.error('Error requesting Radar permissions =>', err);
}
// Start custom tracking (only if we have perms)
if (hasLocationPermissions) {
// Configure the foreground notification on Android
Radar.setForegroundServiceOptions({
text: 'Location tracking is active',
title: 'Tracking in background',
updatesOnly: false,
importance: 2,
});
// Radar.startTrackingCustom({
// desiredStoppedUpdateInterval: 60, // every 60s when "stopped"
// fastestStoppedUpdateInterval: 60,
// desiredMovingUpdateInterval: 60, // every 60s when "moving"
// fastestMovingUpdateInterval: 30, // won't go faster than 30s
// desiredSyncInterval: 20, // sync to Radar server every 20s
// desiredAccuracy: 'high',
// stopDuration: 140, // how long before considered "stopped"
// stopDistance: 70, // how far to move before "moving"
// replay: 'none', // do not replay offline updates
// sync: 'all', // sync all location updates
// useStoppedGeofence: false,
// showBlueBar: false, // iOS: if true, user sees blue bar
// foregroundServiceEnabled: true, // Android: show a persistent notif
// });
Radar.startTrip({
tripOptions: {
externalId: currentUser.uid,
// mode: 'car'
},
trackingOptions: {
desiredStoppedUpdateInterval: 60,
fastestStoppedUpdateInterval: 60,
desiredMovingUpdateInterval: 60,
fastestMovingUpdateInterval: 30,
desiredSyncInterval: 20,
desiredAccuracy: "high",
stopDuration: 140,
stopDistance: 140,
replay: "none",
sync: "all",
useStoppedGeofence: false,
showBlueBar: false,
syncGeofences: false,
syncGeofencesLimit: 0,
beacons: false,
foregroundServiceEnabled: true
}
}).then((result) => {
console.log('Radar trip started =>', result);
});
}
} else {
Radar.stopTracking();
}
});
return () => unsubscribe();
}, [hasLocationPermissions]);
// ----------------------------
// 6) Conditional Rendering
// ----------------------------
// 6a) If still checking perms, show spinner
if (isCheckingPermissions) {
return <LoadingScreen />;
}
// 6b) If we do NOT have location perms, block with a custom screen
if (!hasLocationPermissions) {
return (
<PermissionBlockedScreen
errorMessage={permissionErrorMessage}
onOpenSettings={openAppSettings}
/>
);
}
// 6c) If still initializing auth, show spinner
if (initializing) {
return <LoadingScreen />;
}
// 6d) If we have perms and have done auth check, show normal navigation
return (
<NavigationContainer>
<Stack.Navigator>
{user ? (
<Stack.Screen
name="Home"
component={HomeScreen}
options={{ headerShown: false }}
/>
) : (
<>
<Stack.Screen
name="Login"
component={LoginScreen}
options={{ headerShown: false }}
/>
<Stack.Screen
name="Signup"
component={SignupScreen}
options={{ headerShown: false }}
/>
</>
)}
</Stack.Navigator>
</NavigationContainer>
);
}
// Helper function to open App Settings:
function openAppSettings() {
if (Platform.OS === 'ios') {
Linking.openURL('app-settings:');
} else {
// Replace "com.yourcompany.yourapp" with your actual Android package name
IntentLauncher.startActivityAsync(
IntentLauncher.ActivityAction.APPLICATION_DETAILS_SETTINGS,
{ data: 'package:com.antoninbeliard.loco' }
);
}
}
// Minimal “blocked permissions” screen:
function PermissionBlockedScreen({ errorMessage, onOpenSettings }) {
return (
<PermissionScreen
title="Location Needed"
message={errorMessage}
buttonText="Open Settings"
onPressButton={onOpenSettings}
/>
);
}
```
screens/HomeScreen.js
```javascript
// screens/HomeScreen.js
import React, { useState, useEffect, useRef, useMemo } from 'react';
import {
View,
Text,
StyleSheet,
TouchableOpacity,
Modal,
Button,
TextInput,
SafeAreaView,
ScrollView,
Alert,
ActivityIndicator
} from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { signOut } from 'firebase/auth';
import { auth, db } from '../firebaseConfig';
import { ref, onValue, off, update, get } from 'firebase/database';
import Radar from 'react-native-radar';
import Mapbox, { MapView, LocationPuck, MarkerView, Camera, UserTrackingMode } from '@rnmapbox/maps';
import { MaterialIcons } from '@expo/vector-icons';
import { FontAwesome5 } from '@expo/vector-icons';
import { SearchBar, ListItem, Divider, Avatar } from '@rneui/themed';
import * as ImagePicker from 'expo-image-picker';
import * as ImageManipulator from 'expo-image-manipulator';
import BottomSheet, { BottomSheetScrollView, BottomSheetModal, BottomSheetModalProvider, BottomSheetView } from '@gorhom/bottom-sheet';
import { GestureHandlerRootView } from 'react-native-gesture-handler';
import {
shareLocation,
stopSharingLocation,
stopReceivingLocation,
} from '../sharingUtils';
import { COLORS } from '../colors';
/* -------------------------
Utility Functions
------------------------- */
function getTimeAgo(timestamp) {
const now = Date.now();
const diffInSeconds = Math.floor((now - timestamp) / 1000);
if (diffInSeconds < 60) return `${diffInSeconds} sec. ago`;
const diffInMinutes = Math.floor(diffInSeconds / 60);
if (diffInMinutes < 60) return `${diffInMinutes} min. ago`;
const diffInHours = Math.floor(diffInMinutes / 60);
if (diffInHours < 24) return `${diffInHours} hr. ago`;
const diffInDays = Math.floor(diffInHours / 24);
if (diffInDays < 7) return `${diffInDays} day${diffInDays > 1 ? 's' : ''} ago`;
const diffInWeeks = Math.floor(diffInDays / 7);
if (diffInWeeks < 52) return `${diffInWeeks} week${diffInWeeks > 1 ? 's' : ''} ago`;
const diffInYears = Math.floor(diffInWeeks / 52);
return `${diffInYears} year${diffInYears > 1 ? 's' : ''} ago`;
}
function getDistanceFromLatLonInMiles(lat1, lon1, lat2, lon2) {
const R = 3958.8; // Earth radius in miles
const deg2rad = (deg) => deg * (Math.PI / 180);
const dLat = deg2rad(lat2 - lat1);
const dLon = deg2rad(lon2 - lon1);
const a =
Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(deg2rad(lat1)) *
Math.cos(deg2rad(lat2)) *
Math.sin(dLon / 2) *
Math.sin(dLon / 2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return R * c;
}
/* -------------------------
Small live components
------------------------- */
const LiveTimeAgo = ({ timestamp }) => {
const [timeAgo, setTimeAgo] = useState(getTimeAgo(timestamp));
useEffect(() => {
const interval = setInterval(() => {
setTimeAgo(getTimeAgo(timestamp));
}, 2000);
return () => clearInterval(interval);
}, [timestamp]);
return <Text>{timeAgo}</Text>;
};
const LiveDistance = ({ currentLocation, userLocation }) => {
const [distanceText, setDistanceText] = useState("");
useEffect(() => {
const calculateDistance = () => {
if (currentLocation && userLocation) {
const distance = getDistanceFromLatLonInMiles(
currentLocation.latitude,
currentLocation.longitude,
userLocation.latitude,
userLocation.longitude
);
setDistanceText(distance.toFixed(1) + ' mi');
} else {
setDistanceText("");
}
};
calculateDistance();
const interval = setInterval(calculateDistance, 2000);
return () => clearInterval(interval);
}, [currentLocation, userLocation]);
return <Text style={styles.distanceText}>{distanceText}</Text>;
};
/* -------------------------
Marker component (map)
------------------------- */
const UserMarker = ({ user, onPress }) => {
return (
<TouchableOpacity activeOpacity={0.8} onPress={onPress}>
<View style={markerStyles.container}>
<Avatar
rounded
source={
user.avatar && user.avatar.link
? { uri: user.avatar.link }
: { uri: "data:image/png" }
}
icon={
!user.avatar || !user.avatar.link
? { name: 'person-outline', type: 'material', size: 24 }
: undefined
}
size={30}
containerStyle={
!user.avatar || !user.avatar.link
? { backgroundColor: '#c2c2c2' }
: {}
}
/>
<Text style={markerStyles.nameText}>{user.firstName}</Text>
</View>
</TouchableOpacity>
);
};
const markerStyles = StyleSheet.create({
container: {
flexDirection: 'row',
alignItems: 'center',
backgroundColor: 'white',
padding: 5,
borderRadius: 20,
borderWidth: 1,
borderColor: 'gray',
},
nameText: {
color: 'black',
marginLeft: 5,
fontSize: 16,
},
});
/* -------------------------
Bottom Sheet User Item
(for map’s people list)
------------------------- */
const BottomSheetUserItem = ({ user, currentLocation, onPress }) => {
return (
<ListItem bottomDivider containerStyle={{ backgroundColor: 'transparent' }} onPress={onPress}>
<Avatar
rounded
source={
user.avatar && user.avatar.link
? { uri: user.avatar.link }
: { uri: "data:image/png" }
}
icon={
!user.avatar || !user.avatar.link
? { name: 'person-outline', type: 'material', size: 24 }
: undefined
}
size={30}
containerStyle={
!user.avatar || !user.avatar.link
? { backgroundColor: '#c2c2c2' }
: {}
}
/>
<ListItem.Content>
<View style={styles.userItemHeader}>
<ListItem.Title>
{(`${user.firstName || ''} ${user.lastName || ''}`).trim()}
</ListItem.Title>
<LiveDistance currentLocation={currentLocation} userLocation={user.location} />
</View>
<ListItem.Subtitle>
<LiveTimeAgo timestamp={user.locationTimestamp} />
</ListItem.Subtitle>
</ListItem.Content>
</ListItem>
);
};
/* -------------------------
Social User Item
(for People modal – with sharing status text)
------------------------- */
const SocialUserItem = ({ user, sharingWithIds, receivingFromIds, onPress }) => {
const [statusText, setStatusText] = useState('');
useEffect(() => {
const amSharing = sharingWithIds.includes(user.uid);
const amReceiving = receivingFromIds.includes(user.uid);
let text = '';
if (amSharing && amReceiving) {
text = 'Both of you are sharing';
} else if (amSharing && !amReceiving) {
text = 'Receiving your location';
} else if (!amSharing && amReceiving) {
text = 'Is sharing with you';
} else {
text = 'Neither of you are sharing';
}
setStatusText(text);
}, [user, sharingWithIds, receivingFromIds]);
return (
<ListItem bottomDivider onPress={() => onPress(user)}>
<Avatar
rounded
source={
user.avatar && user.avatar.link
? { uri: user.avatar.link }
: { uri: "data:image/png" }
}
icon={
!user.avatar || !user.avatar.link
? { name: 'person-outline', type: 'material', size: 26 }
: undefined
}
size={30}
containerStyle={
!user.avatar || !user.avatar.link
? { backgroundColor: '#c2c2c2' }
: {}
}
/>
<ListItem.Content>
<ListItem.Title>
{(`${user.firstName || ''} ${user.lastName || ''}`).trim()}
</ListItem.Title>
<ListItem.Subtitle>{statusText}</ListItem.Subtitle>
</ListItem.Content>
</ListItem>
);
};
/* -------------------------
Sharing Options Dialog
(for People modal items only)
------------------------- */
function SharingDialog({ targetUser, sharingStatus, onShare, onStopSharing, onStopReceiving, onClose }) {
let message = '';
let actions = [];
if (sharingStatus.amSharing && !sharingStatus.amReceiving) {
message = `You are sharing your location with ${targetUser.firstName}`;
actions.push({ title: 'Stop Sharing My Location', onPress: onStopSharing });
} else if (!sharingStatus.amSharing && sharingStatus.amReceiving) {
message = `${targetUser.firstName} is sharing their location`;
actions.push({ title: 'Share My Location', onPress: onShare });
actions.push({ title: `Remove ${targetUser.firstName}`, onPress: onStopReceiving });
} else if (sharingStatus.amSharing && sharingStatus.amReceiving) {
message = 'You are both sharing';
actions.push({ title: 'Stop Sharing My Location', onPress: onStopSharing });
actions.push({ title: `Remove ${targetUser.firstName}`, onPress: onStopReceiving });
} else {
message = 'Neither of you are sharing';
actions.push({ title: 'Share My Location', onPress: onShare });
}
return (
<View style={SharingStyles.dialogContainer}>
<Text style={SharingStyles.dialogMessage}>{message}</Text>
{actions.map((action, index) => (
<View key={index} style={SharingStyles.buttonContainer}>
<Button
title={action.title}
onPress={() => {
action.onPress();
onClose();
}}
/>
</View>
))}
<View style={SharingStyles.buttonContainer}>
<Button title="Cancel" onPress={onClose} />
</View>
</View>
);
}
/* -------------------------
Main HomeScreen Component
------------------------- */
export default function HomeScreen() {
const insets = useSafeAreaInsets();
/* --- Map & location state --- */
const [currentLocation, setCurrentLocation] = useState(null);
const cameraRef = useRef(null);
const initialCameraCentered = useRef(false);
const [tracking, setTracking] = useState(false);
/* --- Modal & UI state --- */
const [showSettings, setShowSettings] = useState(false);
const [settingsFirstName, setSettingsFirstName] = useState('');
const [settingsLastName, setSettingsLastName] = useState('');
const [firstNameError, setFirstNameError] = useState(false);
const [lastNameError, setLastNameError] = useState(false);
const [avatarUri, setAvatarUri] = useState(null);
const [avatarData, setAvatarData] = useState(null);
const [uploading, setUploading] = useState(false);
const [showSocial, setShowSocial] = useState(false);
const [expanded1, setExpanded1] = useState(false);
const [expanded2, setExpanded2] = useState(true);
const [search, setSearch] = useState('');
const [searchResults, setSearchResults] = useState([]);
/* --- Real‑time sharing list states --- */
const [sharingWithIds, setSharingWithIds] = useState([]);
const [receivingFromIds, setReceivingFromIds] = useState([]);
const [sharingWithData, setSharingWithData] = useState({}); // keyed by uid
const [receivingFromData, setReceivingFromData] = useState({}); // keyed by uid
/* --- Selected user states --- */
// For main bottom sheet (user info modal on map)
const [selectedUserInfo, setSelectedUserInfo] = useState(null);
// For People modal (sharing options)
const [selectedSocialUser, setSelectedSocialUser] = useState(null);
const [selectedUserLocationName, setSelectedUserLocationName] = useState("");
// These sharing status objects are computed in real time
const [userSharingStatus, setUserSharingStatus] = useState({ amSharing: false, amReceiving: false });
/* --- Mapbox setup --- */
useEffect(() => {
Mapbox.setAccessToken('pk.eyJ1IjoidG90b2IxMjE3IiwiYSI6ImNsbXo4NHdocjA4dnEya215cjY0aWJ1cGkifQ.OMzA6Q8VnHLHZP-P8ACBRw');
Mapbox.setTelemetryEnabled(false);
}, []);
/* --- Radar foreground tracking --- */
useEffect(() => {
const trackLocation = () => {
Radar.trackOnce({ desiredAccuracy: 'high' })
.then((result) => {
if (result.location) {
setCurrentLocation(result.location);
}
})
.catch((err) => {
console.log('Radar trackOnce error =>', err);
});
};
trackLocation();
const intervalId = setInterval(trackLocation, 10000);
return () => clearInterval(intervalId);
}, []);
useEffect(() => {
if (currentLocation && !initialCameraCentered.current) {
cameraRef.current?.setCamera({
centerCoordinate: [currentLocation.longitude, currentLocation.latitude],
zoomLevel: 16,
animationMode: 'none',
animationDuration: 0,
});
initialCameraCentered.current = true;
}
}, [currentLocation]);
/* --- Real‑time sharing lists subscriptions --- */
// "sharingWith" list (users you are sharing your location with)
useEffect(() => {
const currentUser = auth.currentUser;
if (!currentUser) return;
const sharingWithRef = ref(db, `users/${currentUser.uid}/sharingWith`);
const unsubscribe = onValue(sharingWithRef, (snapshot) => {
const data = snapshot.val() || {};
// Always force a new array reference so the dependent effect fires
setSharingWithIds(Object.keys(data));
});
return () => unsubscribe();
}, []);
// "receivingFrom" list (users sharing with you)
useEffect(() => {
const currentUser = auth.currentUser;
if (!currentUser) return;
const receivingFromRef = ref(db, `users/${currentUser.uid}/receivingFrom`);
const unsubscribe = onValue(receivingFromRef, (snapshot) => {
const data = snapshot.val() || {};
setReceivingFromIds(Object.keys(data));
});
return () => unsubscribe();
}, []);
// Subscribe to each user in "sharingWith"
const sharingWithListenersRef = useRef({});
useEffect(() => {
// Unsubscribe from any uid no longer in sharingWithIds.
Object.keys(sharingWithListenersRef.current).forEach((uid) => {
if (!sharingWithIds.includes(uid)) {
// Unsubscribe from this user’s listener
sharingWithListenersRef.current[uid]();
delete sharingWithListenersRef.current[uid];
// Remove the user's data from state
setSharingWithData((prev) => {
const newData = { ...prev };
delete newData[uid];
return newData;
});
}
});
// For each uid in sharingWithIds, attach a listener if not already attached.
sharingWithIds.forEach((uid) => {
if (!sharingWithListenersRef.current[uid]) {
const userRef = ref(db, `users/${uid}`);
const unsubscribe = onValue(userRef, (snapshot) => {
const userData = snapshot.val();
setSharingWithData((prev) => ({ ...prev, [uid]: { uid, ...userData } }));
});
sharingWithListenersRef.current[uid] = unsubscribe;
}
});
// No cleanup here so we don't remove listeners unnecessarily.
}, [sharingWithIds]);
// Cleanup all sharingWith listeners when the component unmounts
useEffect(() => {
return () => {
Object.values(sharingWithListenersRef.current).forEach((unsubscribe) => unsubscribe());
sharingWithListenersRef.current = {};
};
}, []);
// Subscribe to each user in "receivingFrom"
const receivingFromListenersRef = useRef({});
useEffect(() => {
Object.keys(receivingFromListenersRef.current).forEach((uid) => {
if (!receivingFromIds.includes(uid)) {
receivingFromListenersRef.current[uid]();
delete receivingFromListenersRef.current[uid];
setReceivingFromData((prev) => {
const newData = { ...prev };
delete newData[uid];
return newData;
});
}
});
receivingFromIds.forEach((uid) => {
if (!receivingFromListenersRef.current[uid]) {
const userRef = ref(db, `users/${uid}`);
const unsubscribe = onValue(userRef, (snapshot) => {
const userData = snapshot.val();
setReceivingFromData((prev) => ({ ...prev, [uid]: { uid, ...userData } }));
});
receivingFromListenersRef.current[uid] = unsubscribe;
}
});
}, [receivingFromIds]);
useEffect(() => {
return () => {
Object.values(receivingFromListenersRef.current).forEach((unsubscribe) => unsubscribe());
receivingFromListenersRef.current = {};
};
}, []);
/* --- Compute markers from receivingFrom users --- */
const markers = useMemo(() => {
return Object.values(receivingFromData).filter((user) => user.location);
}, [receivingFromData]);
/* --- Search Users (excluding self) --- */
useEffect(() => {
if (search.trim().length > 0) {
const currentUser = auth.currentUser;
const usersRef = ref(db, 'users');
get(usersRef)
.then((snapshot) => {
if (snapshot.exists()) {
const usersData = snapshot.val();
const searchLower = search.toLowerCase();
let results = [];
for (const uid in usersData) {
if (currentUser && uid === currentUser.uid) continue;
const user = usersData[uid];
const fullName = ((user.firstName || '') + ' ' + (user.lastName || '')).trim().toLowerCase();
const email = (user.email || '').toLowerCase();
if (fullName.includes(searchLower) || email.includes(searchLower)) {
results.push({ uid, ...user });
}
}
setSearchResults(results);
} else {
setSearchResults([]);
}
})
.catch((err) => {
console.error('Error fetching users:', err);
setSearchResults([]);
});
} else {
setSearchResults([]);
}
}, [search]);
/* --- Settings modal: fetch current profile data --- */
useEffect(() => {
if (showSettings) {
setFirstNameError(false);
setLastNameError(false);
const user = auth.currentUser;
if (user) {
get(ref(db, 'users/' + user.uid))
.then((snapshot) => {
if (snapshot.exists()) {
const data = snapshot.val();
setSettingsFirstName(data.firstName || '');
setSettingsLastName(data.lastName || '');
if (data.avatar) {
setAvatarData(data.avatar);
setAvatarUri(data.avatar.link || null);
} else {
setAvatarData(null);
setAvatarUri(null);
}
}
})
.catch((err) => {
console.log('Error fetching settings data:', err);
});
}
}
}, [showSettings]);
/* --- Update sharing status for the main user info modal --- */
useEffect(() => {
if (selectedUserInfo) {
setUserSharingStatus({
amSharing: sharingWithIds.includes(selectedUserInfo.uid),
amReceiving: receivingFromIds.includes(selectedUserInfo.uid)
});
}
}, [selectedUserInfo, sharingWithIds, receivingFromIds]);
/* --- Handlers for People modal (social user items) --- */
const handleSocialUserPress = (user) => {
// When a People modal user item is tapped, only open the sharing options modal.
setSelectedSocialUser(user);
};
/* --- Handlers for main bottom sheet user items --- */
const bottomSheetRef = useRef(null);
const userInfoModalRef = useRef(null);
const snapPoints = useMemo(() => ['10%', '32%', '80%'], []);
const openUserInfo = (user) => {
// Center map on user’s location and open the user info modal.
if (tracking) {
setTracking(false);
setTimeout(() => {
cameraRef.current?.setCamera({
centerCoordinate: [user.location.longitude, user.location.latitude],
animationMode: 'flyTo',
animationDuration: 1000,
});
}, 150);
} else {
cameraRef.current?.setCamera({
centerCoordinate: [user.location.longitude, user.location.latitude],
animationMode: 'flyTo',
animationDuration: 1000,
});
}
bottomSheetRef.current?.close();
setSelectedUserInfo(user);
};
const closeUserInfo = () => {
userInfoModalRef.current?.dismiss();
setSelectedUserInfo(null);
bottomSheetRef.current?.snapToIndex(1);
};
useEffect(() => {
if (selectedUserInfo && userInfoModalRef.current) {
userInfoModalRef.current.present();
}
}, [selectedUserInfo]);
/* --- Toggle tracking --- */
const toggleTracking = () => {
if (!tracking) {
setTracking(true);
if (currentLocation) {
cameraRef.current?.setCamera({
centerCoordinate: [currentLocation.longitude, currentLocation.latitude],
zoomLevel: 16,
animationMode: 'flyTo',
animationDuration: 1000,
});
}
} else {
setTracking(false);
}
};
/* --- Name validation and update --- */
const validateName = (name) => {
const regex = /^[A-Za-z]+$/;
return name.trim().length > 0 && name.length <= 20 && regex.test(name);
};
const handleFirstNameChange = (text) => {
setSettingsFirstName(text);
if (validateName(text)) {
setFirstNameError(false);
const user = auth.currentUser;
if (user) {
update(ref(db, 'users/' + user.uid), { firstName: text }).catch((err) =>
console.log('Error updating first name:', err)
);
}
} else {
setFirstNameError(true);
}
};
const handleLastNameChange = (text) => {
setSettingsLastName(text);
if (validateName(text)) {
setLastNameError(false);
const user = auth.currentUser;
if (user) {
update(ref(db, 'users/' + user.uid), { lastName: text }).catch((err) =>
console.log('Error updating last name:', err)
);
}
} else {
setLastNameError(true);
}
};
/* --- Sign out --- */
const handleSignOut = async () => {
try {
await signOut(auth);
} catch (error) {
console.log('Error signing out:', error);
}
};
/* --- Image upload handlers (unchanged) --- */
const IMGUR_CLIENT_ID = '4916641447bc9f6';
const deleteImgurImage = async (deleteHash) => {
try {
const authHeader = 'Client-ID ' + IMGUR_CLIENT_ID;
const response = await fetch(`https://api.imgur.com/3/image/${deleteHash}`, {
method: 'DELETE',
headers: {
Authorization: authHeader,
Accept: 'application/json',
},
});
const result = await response.json();
if (result.success) {
console.log('Old avatar deleted successfully from Imgur');
} else {
console.error('Failed to delete old avatar from Imgur:', result);
}
} catch (error) {
console.error('Error deleting old avatar:', error);
}
};
const resizeImageIfNeeded = async (uri, width, height) => {
if (width <= 500 && height <= 500) {
return uri;
}
const maxDimension = 1000;
const scaleFactor = Math.min(maxDimension / width, maxDimension / height);
const newWidth = Math.round(width * scaleFactor);
const newHeight = Math.round(height * scaleFactor);
const manipResult = await ImageManipulator.manipulateAsync(
uri,
[{ resize: { width: newWidth, height: newHeight } }],
{ compress: 0.8, format: ImageManipulator.SaveFormat.JPEG }
);
return manipResult.uri;
};
const uploadImage = async (uri) => {
try {
setUploading(true);
let formData = new FormData();
const uriParts = uri.split('.');
const fileType = uriParts[uriParts.length - 1];
formData.append('image', {
uri: uri,
name: `avatar.${fileType}`,
type: `image/${fileType}`,
});
const authHeader = 'Client-ID ' + IMGUR_CLIENT_ID;
const response = await fetch('https://api.imgur.com/3/image', {
method: 'POST',
headers: {
Authorization: authHeader,
Accept: 'application/json',
},
body: formData,
});
const result = await response.json();
if (result.success) {