-
Notifications
You must be signed in to change notification settings - Fork 3.9k
Expand file tree
/
Copy pathMapViewImpl.web.tsx
More file actions
354 lines (310 loc) · 13.9 KB
/
Copy pathMapViewImpl.web.tsx
File metadata and controls
354 lines (310 loc) · 13.9 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
import Button from '@components/Button';
import 'mapbox-gl/dist/mapbox-gl.css';
import ImageSVG from '@components/ImageSVG';
import {PressableWithoutFeedback} from '@components/Pressable';
import Text from '@components/Text';
import {useMemoizedLazyExpensifyIcons} from '@hooks/useLazyAsset';
import useOnyx from '@hooks/useOnyx';
import usePrevious from '@hooks/usePrevious';
import useStyleUtils from '@hooks/useStyleUtils';
import useTheme from '@hooks/useTheme';
import useThemeStyles from '@hooks/useThemeStyles';
import DistanceRequestUtils from '@libs/DistanceRequestUtils';
import type {GeolocationErrorCallback} from '@libs/getCurrentPosition/getCurrentPosition.types';
import {GeolocationErrorCode} from '@libs/getCurrentPosition/getCurrentPosition.types';
import {clearUserLocation, setUserLocation} 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 type {MapRef, ViewState} from 'react-map-gl/mapbox';
// 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 React, {useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState} from 'react';
import Map, {Marker} from 'react-map-gl/mapbox';
import {View} from 'react-native';
import type {MapViewProps} from './MapViewTypes';
import './mapbox.css';
import Direction from './Direction';
import MapMarkerIcon from './MapMarkerIcon';
import PendingMapView from './PendingMapView';
import responder from './responder';
import useDistanceUnit from './useDistanceUnit';
import utils from './utils';
function MapViewImpl({
style,
styleURL,
waypoints,
mapPadding,
accessToken,
directionCoordinates: directionCoordinatesProp,
initialState = {location: CONST.MAPBOX.DEFAULT_COORDINATE, zoom: CONST.MAPBOX.DEFAULT_ZOOM},
interactive = true,
distanceInMeters,
unit,
ref,
shouldDisplayCurrentLocation = true,
}: MapViewProps) {
const directionCoordinates = !directionCoordinatesProp || utils.isSingleSegmentRoute(directionCoordinatesProp) ? directionCoordinatesProp : directionCoordinatesProp.flat();
const [userLocation] = useOnyx(ONYXKEYS.USER_LOCATION);
const {isOffline} = useNetwork();
const {translate} = useLocalize();
const {distanceUnit, toggleDistanceUnit} = useDistanceUnit(unit);
const theme = useTheme();
const styles = useThemeStyles();
const StyleUtils = useStyleUtils();
const expensifyIcons = useMemoizedLazyExpensifyIcons(['Crosshair', 'MapCurrentLocation']);
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 && shouldDisplayCurrentLocation && (!waypoints || waypoints.length === 0),
[userInteractedWithMap, waypoints, shouldDisplayCurrentLocation],
);
const setCurrentPositionToInitialState: GeolocationErrorCallback = useCallback(
(error) => {
if (error?.code !== GeolocationErrorCode.PERMISSION_DENIED || !initialLocation) {
return;
}
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};
setUserLocation(currentCoords);
}, setCurrentPositionToInitialState);
}, [isOffline, shouldPanMapToCurrentPosition, setCurrentPositionToInitialState]),
);
useEffect(() => {
if (!currentPosition || !mapRef) {
return;
}
if (!shouldPanMapToCurrentPosition()) {
return;
}
// Avoid animating the navigation 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.longitude, prevUserPosition.latitude, shouldPanMapToCurrentPosition]);
const resetBoundaries = useCallback(() => {
if (!waypoints || waypoints.length === 0) {
return;
}
if (!mapRef) {
return;
}
if (waypoints.length === 1) {
mapRef.flyTo({
center: waypoints.at(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-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?.longitude, currentPosition?.latitude, 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?.longitude, currentPosition?.latitude, initialState.zoom]);
const distanceSymbolCoordinate = useMemo(() => {
if (!directionCoordinates?.length || !waypoints?.length) {
return;
}
const {northEast, southWest} = utils.getBounds(
waypoints.map((waypoint) => waypoint.coordinate),
directionCoordinates,
);
const boundsCenter = utils.getBoundsCenter({northEast, southWest});
return utils.findClosestCoordinateOnLineFromCenter(boundsCenter, directionCoordinates);
}, [waypoints, directionCoordinates]);
return !isOffline && !!accessToken && !!initialViewState ? (
<View
style={style}
{...responder.panHandlers}
>
<Map
onDrag={() => setUserInteractedWithMap(true)}
ref={setRef}
mapboxAccessToken={accessToken}
initialViewState={initialViewState}
style={{...StyleUtils.getTextColorStyle(theme.mapAttributionText), zIndex: -1}}
mapStyle={styleURL}
interactive={interactive}
>
{interactive && shouldDisplayCurrentLocation && (
<Marker
key="Current-position"
longitude={currentPosition?.longitude ?? 0}
latitude={currentPosition?.latitude ?? 0}
>
<ImageSVG
src={expensifyIcons.MapCurrentLocation}
width={CONST.MAP_MARKER_SIZES.CURRENT_LOCATION.width}
height={CONST.MAP_MARKER_SIZES.CURRENT_LOCATION.height}
/>
</Marker>
)}
{!!distanceSymbolCoordinate && !!distanceInMeters && !!distanceUnit && (
<Marker
key="distance-label"
longitude={distanceSymbolCoordinate.at(0) ?? 0}
latitude={distanceSymbolCoordinate.at(1) ?? 0}
>
<PressableWithoutFeedback
sentryLabel="MapView-ToggleDistanceUnit"
accessibilityLabel={CONST.ROLE.BUTTON}
role={CONST.ROLE.BUTTON}
onPress={toggleDistanceUnit}
>
<View style={styles.distanceLabelWrapper}>
<Text style={styles.distanceLabelText}> {DistanceRequestUtils.getDistanceForDisplayLabel(distanceInMeters, distanceUnit)}</Text>
</View>
</PressableWithoutFeedback>
</Marker>
)}
{waypoints?.map(({coordinate, markerType, id}) => {
if (
utils.areSameCoordinate([coordinate[0], coordinate[1]], [currentPosition?.longitude ?? 0, currentPosition?.latitude ?? 0]) &&
interactive &&
shouldDisplayCurrentLocation
) {
return null;
}
return (
<Marker
key={id}
longitude={coordinate[0]}
latitude={coordinate[1]}
>
<MapMarkerIcon markerType={markerType} />
</Marker>
);
})}
{!!directionCoordinatesProp && <Direction coordinates={directionCoordinatesProp} />}
</Map>
{interactive && (
<View style={[styles.pAbsolute, styles.p5, styles.t0, styles.r0, styles.zIndex1]}>
<Button
onPress={centerMap}
iconFill={theme.icon}
icon={expensifyIcons.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 MapViewImpl;