-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
MapView.website.tsx
303 lines (272 loc) · 12.4 KB
/
MapView.website.tsx
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
// Explanation: Different Mapbox libraries are required for web and native mobile platforms.
// This is why we have separate components for web and native to handle the specific implementations.
// For the web version, we use the Mapbox Web library called react-map-gl, while for the native mobile version,
// we utilize a different Mapbox library @rnmapbox/maps tailored for mobile development.
import {useFocusEffect} from '@react-navigation/native';
import mapboxgl from 'mapbox-gl';
import 'mapbox-gl/dist/mapbox-gl.css';
import React, {forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState} from 'react';
import type {MapRef, ViewState} from 'react-map-gl';
import Map, {Marker} from 'react-map-gl';
import {View} from 'react-native';
import {withOnyx} from 'react-native-onyx';
import Button from '@components/Button';
import * as Expensicons from '@components/Icon/Expensicons';
import usePrevious from '@hooks/usePrevious';
import useStyleUtils from '@hooks/useStyleUtils';
import useTheme from '@hooks/useTheme';
import useThemeStyles from '@hooks/useThemeStyles';
import type {GeolocationErrorCallback} from '@libs/getCurrentPosition/getCurrentPosition.types';
import {GeolocationErrorCode} from '@libs/getCurrentPosition/getCurrentPosition.types';
import * as UserLocation from '@userActions/UserLocation';
import CONST from '@src/CONST';
import useLocalize from '@src/hooks/useLocalize';
import useNetwork from '@src/hooks/useNetwork';
import getCurrentPosition from '@src/libs/getCurrentPosition';
import ONYXKEYS from '@src/ONYXKEYS';
import Direction from './Direction';
import './mapbox.css';
import type {MapViewHandle} from './MapViewTypes';
import PendingMapView from './PendingMapView';
import responder from './responder';
import type {ComponentProps, MapViewOnyxProps} from './types';
import utils from './utils';
const MapView = forwardRef<MapViewHandle, ComponentProps>(
(
{
style,
styleURL,
waypoints,
mapPadding,
accessToken,
userLocation,
directionCoordinates,
initialState = {location: CONST.MAPBOX.DEFAULT_COORDINATE, zoom: CONST.MAPBOX.DEFAULT_ZOOM},
interactive = true,
},
ref,
) => {
const {isOffline} = useNetwork();
const {translate} = useLocalize();
const theme = useTheme();
const styles = useThemeStyles();
const StyleUtils = useStyleUtils();
const [mapRef, setMapRef] = useState<MapRef | null>(null);
const initialLocation = useMemo(() => ({longitude: initialState.location[0], latitude: initialState.location[1]}), [initialState]);
const currentPosition = userLocation ?? initialLocation;
const prevUserPosition = usePrevious(currentPosition);
const [userInteractedWithMap, setUserInteractedWithMap] = useState(false);
const [shouldResetBoundaries, setShouldResetBoundaries] = useState<boolean>(false);
const setRef = useCallback((newRef: MapRef | null) => setMapRef(newRef), []);
const shouldInitializeCurrentPosition = useRef(true);
// Determines if map can be panned to user's detected
// location without bothering the user. It will return
// false if user has already started dragging the map or
// if there are one or more waypoints present.
const shouldPanMapToCurrentPosition = useCallback(() => !userInteractedWithMap && (!waypoints || waypoints.length === 0), [userInteractedWithMap, waypoints]);
const setCurrentPositionToInitialState: GeolocationErrorCallback = useCallback(
(error) => {
if (error?.code !== GeolocationErrorCode.PERMISSION_DENIED || !initialLocation) {
return;
}
UserLocation.clearUserLocation();
},
[initialLocation],
);
useFocusEffect(
useCallback(() => {
if (isOffline) {
return;
}
if (!shouldInitializeCurrentPosition.current) {
return;
}
shouldInitializeCurrentPosition.current = false;
if (!shouldPanMapToCurrentPosition()) {
setCurrentPositionToInitialState();
return;
}
getCurrentPosition((params) => {
const currentCoords = {longitude: params.coords.longitude, latitude: params.coords.latitude};
UserLocation.setUserLocation(currentCoords);
}, setCurrentPositionToInitialState);
}, [isOffline, shouldPanMapToCurrentPosition, setCurrentPositionToInitialState]),
);
useEffect(() => {
if (!currentPosition || !mapRef) {
return;
}
if (!shouldPanMapToCurrentPosition()) {
return;
}
// Avoid animating the naviagtion to the same location
const shouldAnimate = prevUserPosition.longitude !== currentPosition.longitude || prevUserPosition.latitude !== currentPosition.latitude;
mapRef.flyTo({
center: [currentPosition.longitude, currentPosition.latitude],
zoom: CONST.MAPBOX.DEFAULT_ZOOM,
animate: shouldAnimate,
});
}, [currentPosition, mapRef, prevUserPosition, shouldPanMapToCurrentPosition]);
const resetBoundaries = useCallback(() => {
if (!waypoints || waypoints.length === 0) {
return;
}
if (!mapRef) {
return;
}
if (waypoints.length === 1) {
mapRef.flyTo({
center: waypoints[0].coordinate,
zoom: CONST.MAPBOX.SINGLE_MARKER_ZOOM,
});
return;
}
const map = mapRef.getMap();
const {northEast, southWest} = utils.getBounds(
waypoints.map((waypoint) => waypoint.coordinate),
directionCoordinates,
);
map.fitBounds([northEast, southWest], {padding: mapPadding});
}, [waypoints, mapRef, mapPadding, directionCoordinates]);
useEffect(resetBoundaries, [resetBoundaries]);
useEffect(() => {
if (!shouldResetBoundaries) {
return;
}
resetBoundaries();
setShouldResetBoundaries(false);
// eslint-disable-next-line react-compiler/react-compiler, react-hooks/exhaustive-deps -- this effect only needs to run when the boundaries reset is forced
}, [shouldResetBoundaries]);
useEffect(() => {
if (!mapRef) {
return;
}
const resizeObserver = new ResizeObserver(() => {
mapRef.resize();
setShouldResetBoundaries(true);
});
resizeObserver.observe(mapRef.getContainer());
return () => {
resizeObserver?.disconnect();
};
}, [mapRef]);
useImperativeHandle(
ref,
() => ({
flyTo: (location: [number, number], zoomLevel: number = CONST.MAPBOX.DEFAULT_ZOOM, animationDuration?: number) =>
mapRef?.flyTo({
center: location,
zoom: zoomLevel,
duration: animationDuration,
}),
fitBounds: (northEast: [number, number], southWest: [number, number]) => mapRef?.fitBounds([northEast, southWest]),
}),
[mapRef],
);
const centerMap = useCallback(() => {
if (!mapRef) {
return;
}
const waypointCoordinates = waypoints?.map((waypoint) => waypoint.coordinate) ?? [];
if (waypointCoordinates.length > 1 || (directionCoordinates ?? []).length > 1) {
const {northEast, southWest} = utils.getBounds(waypoints?.map((waypoint) => waypoint.coordinate) ?? [], directionCoordinates);
const map = mapRef?.getMap();
map?.fitBounds([southWest, northEast], {padding: mapPadding, animate: true, duration: CONST.MAPBOX.ANIMATION_DURATION_ON_CENTER_ME});
return;
}
mapRef.flyTo({
center: [currentPosition?.longitude ?? 0, currentPosition?.latitude ?? 0],
zoom: CONST.MAPBOX.SINGLE_MARKER_ZOOM,
bearing: 0,
animate: true,
duration: CONST.MAPBOX.ANIMATION_DURATION_ON_CENTER_ME,
});
}, [directionCoordinates, currentPosition, mapRef, waypoints, mapPadding]);
const initialViewState: Partial<ViewState> | undefined = useMemo(() => {
if (!interactive) {
if (!waypoints) {
return undefined;
}
const {northEast, southWest} = utils.getBounds(
waypoints.map((waypoint) => waypoint.coordinate),
directionCoordinates,
);
return {
zoom: initialState.zoom,
bounds: [northEast, southWest],
};
}
return {
longitude: currentPosition?.longitude,
latitude: currentPosition?.latitude,
zoom: initialState.zoom,
};
}, [waypoints, directionCoordinates, interactive, currentPosition, initialState.zoom]);
return !isOffline && !!accessToken && !!initialViewState ? (
<View
style={style}
// eslint-disable-next-line react/jsx-props-no-spreading
{...responder.panHandlers}
>
<Map
onDrag={() => setUserInteractedWithMap(true)}
ref={setRef}
mapLib={mapboxgl}
mapboxAccessToken={accessToken}
initialViewState={initialViewState}
style={StyleUtils.getTextColorStyle(theme.mapAttributionText)}
mapStyle={styleURL}
interactive={interactive}
>
{interactive && (
<Marker
key="Current-position"
longitude={currentPosition?.longitude ?? 0}
latitude={currentPosition?.latitude ?? 0}
>
<View style={styles.currentPositionDot} />
</Marker>
)}
{waypoints?.map(({coordinate, markerComponent, id}) => {
const MarkerComponent = markerComponent;
if (utils.areSameCoordinate([coordinate[0], coordinate[1]], [currentPosition?.longitude ?? 0, currentPosition?.latitude ?? 0]) && interactive) {
return null;
}
return (
<Marker
key={id}
longitude={coordinate[0]}
latitude={coordinate[1]}
>
<MarkerComponent />
</Marker>
);
})}
{directionCoordinates && <Direction coordinates={directionCoordinates} />}
</Map>
{interactive && (
<View style={[styles.pAbsolute, styles.p5, styles.t0, styles.r0, {zIndex: 1}]}>
<Button
onPress={centerMap}
iconFill={theme.icon}
medium
icon={Expensicons.Crosshair}
accessibilityLabel={translate('common.center')}
/>
</View>
)}
</View>
) : (
<PendingMapView
title={translate('distance.mapPending.title')}
subtitle={isOffline ? translate('distance.mapPending.subtitle') : translate('distance.mapPending.onlineSubtitle')}
style={styles.mapEditView}
/>
);
},
);
export default withOnyx<ComponentProps, MapViewOnyxProps>({
userLocation: {
key: ONYXKEYS.USER_LOCATION,
},
})(MapView);