-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
DistanceRequest.js
276 lines (246 loc) · 11.4 KB
/
DistanceRequest.js
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
import React, {useEffect, useMemo, useState} from 'react';
import {ScrollView, View} from 'react-native';
import {withOnyx} from 'react-native-onyx';
import lodashGet from 'lodash/get';
import lodashHas from 'lodash/has';
import PropTypes from 'prop-types';
import _ from 'underscore';
import CONST from '../CONST';
import ROUTES from '../ROUTES';
import ONYXKEYS from '../ONYXKEYS';
import styles from '../styles/styles';
import variables from '../styles/variables';
import theme from '../styles/themes/default';
import transactionPropTypes from './transactionPropTypes';
import useNetwork from '../hooks/useNetwork';
import usePrevious from '../hooks/usePrevious';
import useLocalize from '../hooks/useLocalize';
import * as ErrorUtils from '../libs/ErrorUtils';
import Navigation from '../libs/Navigation/Navigation';
import * as MapboxToken from '../libs/actions/MapboxToken';
import * as Transaction from '../libs/actions/Transaction';
import * as TransactionUtils from '../libs/TransactionUtils';
import Button from './Button';
import MapView from './MapView';
import LinearGradient from './LinearGradient';
import * as Expensicons from './Icon/Expensicons';
import BlockingView from './BlockingViews/BlockingView';
import DotIndicatorMessage from './DotIndicatorMessage';
import MenuItemWithTopDescription from './MenuItemWithTopDescription';
import {iouPropTypes} from '../pages/iou/propTypes';
import reportPropTypes from '../pages/reportPropTypes';
import * as IOU from '../libs/actions/IOU';
const MAX_WAYPOINTS = 25;
const MAX_WAYPOINTS_TO_DISPLAY = 4;
const propTypes = {
/** Holds data related to Money Request view state, rather than the underlying Money Request data. */
iou: iouPropTypes,
/** Type of money request (i.e. IOU) */
iouType: PropTypes.oneOf(_.values(CONST.IOU.MONEY_REQUEST_TYPE)),
/** The report to which the distance request is associated */
report: reportPropTypes,
/** The optimistic transaction for this request */
transaction: transactionPropTypes,
/** Data about Mapbox token for calling Mapbox API */
mapboxAccessToken: PropTypes.shape({
/** Temporary token for Mapbox API */
token: PropTypes.string,
/** Time when the token will expire in ISO 8601 */
expiration: PropTypes.string,
}),
};
const defaultProps = {
iou: {},
iouType: '',
report: {},
transaction: {},
mapboxAccessToken: {
token: '',
},
};
function DistanceRequest({iou, iouType, report, transaction, mapboxAccessToken}) {
const [shouldShowGradient, setShouldShowGradient] = useState(false);
const [scrollContainerHeight, setScrollContainerHeight] = useState(0);
const [scrollContentHeight, setScrollContentHeight] = useState(0);
const {isOffline} = useNetwork();
const {translate} = useLocalize();
const reportID = lodashGet(report, 'reportID', '');
const waypoints = useMemo(() => lodashGet(transaction, 'comment.waypoints', {}), [transaction]);
const numberOfWaypoints = _.size(waypoints);
const lastWaypointIndex = numberOfWaypoints - 1;
const isLoadingRoute = lodashGet(transaction, 'comment.isLoading', false);
const hasRouteError = lodashHas(transaction, 'errorFields.route');
const previousWaypoints = usePrevious(waypoints);
const haveWaypointsChanged = !_.isEqual(previousWaypoints, waypoints);
const doesRouteExist = lodashHas(transaction, 'routes.route0.geometry.coordinates');
const shouldFetchRoute = (!doesRouteExist || haveWaypointsChanged) && !isLoadingRoute && TransactionUtils.validateWaypoints(waypoints);
const waypointMarkers = useMemo(
() =>
_.filter(
_.map(waypoints, (waypoint, key) => {
if (!waypoint || !lodashHas(waypoint, 'lat') || !lodashHas(waypoint, 'lng')) {
return;
}
const index = Number(key.replace('waypoint', ''));
let MarkerComponent;
if (index === 0) {
MarkerComponent = Expensicons.DotIndicatorUnfilled;
} else if (index === lastWaypointIndex) {
MarkerComponent = Expensicons.Location;
} else {
MarkerComponent = Expensicons.DotIndicator;
}
return {
id: `${waypoint.lng},${waypoint.lat},${index}`,
coordinate: [waypoint.lng, waypoint.lat],
markerComponent: () => (
<MarkerComponent
width={CONST.MAP_MARKER_SIZE}
height={CONST.MAP_MARKER_SIZE}
fill={theme.icon}
/>
),
};
}),
(waypoint) => waypoint,
),
[waypoints, lastWaypointIndex],
);
// Show up to the max number of waypoints plus 1/2 of one to hint at scrolling
const halfMenuItemHeight = Math.floor(variables.baseMenuItemHeight / 2);
const scrollContainerMaxHeight = variables.baseMenuItemHeight * MAX_WAYPOINTS_TO_DISPLAY + halfMenuItemHeight;
useEffect(() => {
MapboxToken.init();
return MapboxToken.stop;
}, []);
useEffect(() => {
if (!iou.transactionID || !_.isEmpty(waypoints)) {
return;
}
// Create the initial start and stop waypoints
Transaction.createInitialWaypoints(iou.transactionID);
}, [iou.transactionID, waypoints]);
const updateGradientVisibility = (event = {}) => {
// If a waypoint extends past the bottom of the visible area show the gradient, else hide it.
const visibleAreaEnd = lodashGet(event, 'nativeEvent.contentOffset.y', 0) + scrollContainerHeight;
setShouldShowGradient(visibleAreaEnd < scrollContentHeight);
};
useEffect(() => {
if (isOffline || !shouldFetchRoute) {
return;
}
Transaction.getRoute(iou.transactionID, waypoints);
}, [shouldFetchRoute, iou.transactionID, waypoints, isOffline]);
useEffect(updateGradientVisibility, [scrollContainerHeight, scrollContentHeight]);
return (
<>
<View
style={styles.distanceRequestContainer(scrollContainerMaxHeight)}
onLayout={(event = {}) => setScrollContainerHeight(lodashGet(event, 'nativeEvent.layout.height', 0))}
>
<ScrollView
onContentSizeChange={(width, height) => setScrollContentHeight(height)}
onScroll={updateGradientVisibility}
scrollEventThrottle={16}
>
{_.map(waypoints, (waypoint, key) => {
// key is of the form waypoint0, waypoint1, ...
const index = Number(key.replace('waypoint', ''));
let descriptionKey = 'distance.waypointDescription.';
let waypointIcon;
if (index === 0) {
descriptionKey += 'start';
waypointIcon = Expensicons.DotIndicatorUnfilled;
} else if (index === lastWaypointIndex) {
descriptionKey += 'finish';
waypointIcon = Expensicons.Location;
} else {
descriptionKey += 'stop';
waypointIcon = Expensicons.DotIndicator;
}
return (
<MenuItemWithTopDescription
description={translate(descriptionKey)}
title={lodashGet(waypoints, [`waypoint${index}`, 'address'], '')}
iconFill={theme.icon}
secondaryIcon={waypointIcon}
secondaryIconFill={theme.icon}
shouldShowRightIcon
onPress={() => Navigation.navigate(ROUTES.getMoneyRequestWaypointRoute('request', index))}
key={key}
/>
);
})}
</ScrollView>
{shouldShowGradient && (
<LinearGradient
style={[styles.pAbsolute, styles.b0, styles.l0, styles.r0, {height: halfMenuItemHeight}]}
colors={[theme.transparent, theme.modalBackground]}
/>
)}
{hasRouteError && (
<DotIndicatorMessage
style={[styles.mh5, styles.mv3]}
messages={ErrorUtils.getLatestErrorField(transaction, 'route')}
type="error"
/>
)}
</View>
<View style={[styles.flexRow, styles.justifyContentCenter, styles.pt1]}>
<Button
small
icon={Expensicons.Plus}
onPress={() => Transaction.addStop(iou.transactionID)}
text={translate('distance.addStop')}
isDisabled={numberOfWaypoints === MAX_WAYPOINTS}
innerStyles={[styles.ph10]}
/>
</View>
<View style={styles.mapViewContainer}>
{!isOffline && Boolean(mapboxAccessToken.token) ? (
<MapView
accessToken={mapboxAccessToken.token}
mapPadding={CONST.MAPBOX.PADDING}
pitchEnabled={false}
initialState={{
zoom: CONST.MAPBOX.DEFAULT_ZOOM,
location: CONST.MAPBOX.DEFAULT_COORDINATE,
}}
directionCoordinates={lodashGet(transaction, 'routes.route0.geometry.coordinates', [])}
style={styles.mapView}
waypoints={waypointMarkers}
styleURL={CONST.MAPBOX.STYLE_URL}
/>
) : (
<View style={[styles.mapPendingView]}>
<BlockingView
icon={Expensicons.EmptyStateRoutePending}
title={translate('distance.mapPending.title')}
subtitle={isOffline ? translate('distance.mapPending.subtitle') : translate('distance.mapPending.onlineSubtitle')}
shouldShowLink={false}
/>
</View>
)}
</View>
<Button
success
style={[styles.w100, styles.mb4, styles.ph4, styles.flexShrink0]}
onPress={() => IOU.navigateToNextPage(iou, iouType, reportID, report)}
pressOnEnter
isDisabled={waypointMarkers.length < 2}
text={translate('common.next')}
/>
</>
);
}
DistanceRequest.displayName = 'DistanceRequest';
DistanceRequest.propTypes = propTypes;
DistanceRequest.defaultProps = defaultProps;
export default withOnyx({
transaction: {
key: (props) => `${ONYXKEYS.COLLECTION.TRANSACTION}${props.iou.transactionID}`,
},
mapboxAccessToken: {
key: ONYXKEYS.MAPBOX_ACCESS_TOKEN,
},
})(DistanceRequest);