-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
WaypointEditor.js
276 lines (250 loc) · 11.8 KB
/
WaypointEditor.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, {useMemo, useRef, useState} from 'react';
import _ from 'underscore';
import lodashGet from 'lodash/get';
import {View} from 'react-native';
import PropTypes from 'prop-types';
import {withOnyx} from 'react-native-onyx';
import {useNavigation} from '@react-navigation/native';
import AddressSearch from '../../components/AddressSearch';
import ScreenWrapper from '../../components/ScreenWrapper';
import FullPageNotFoundView from '../../components/BlockingViews/FullPageNotFoundView';
import HeaderWithBackButton from '../../components/HeaderWithBackButton';
import Navigation from '../../libs/Navigation/Navigation';
import ONYXKEYS from '../../ONYXKEYS';
import Form from '../../components/Form';
import styles from '../../styles/styles';
import useWindowDimensions from '../../hooks/useWindowDimensions';
import useLocalize from '../../hooks/useLocalize';
import useNetwork from '../../hooks/useNetwork';
import CONST from '../../CONST';
import * as Expensicons from '../../components/Icon/Expensicons';
import ConfirmModal from '../../components/ConfirmModal';
import * as Transaction from '../../libs/actions/Transaction';
import * as ValidationUtils from '../../libs/ValidationUtils';
import ROUTES from '../../ROUTES';
import transactionPropTypes from '../../components/transactionPropTypes';
import * as ErrorUtils from '../../libs/ErrorUtils';
const propTypes = {
/** Route params */
route: PropTypes.shape({
params: PropTypes.shape({
/** IOU type */
iouType: PropTypes.string,
/** Thread reportID */
threadReportID: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
/** ID of the transaction being edited */
transactionID: PropTypes.string,
/** Index of the waypoint being edited */
waypointIndex: PropTypes.string,
}),
}),
recentWaypoints: PropTypes.arrayOf(
PropTypes.shape({
/** A description of the location (usually the address) */
description: PropTypes.string,
/** Data required by the google auto complete plugin to know where to put the markers on the map */
geometry: PropTypes.shape({
/** Data about the location */
location: PropTypes.shape({
/** Lattitude of the location */
lat: PropTypes.number,
/** Longitude of the location */
lng: PropTypes.number,
}),
}),
}),
),
/* Onyx props */
/** The optimistic transaction for this request */
transaction: transactionPropTypes,
};
const defaultProps = {
route: {},
recentWaypoints: [],
transaction: {},
};
function WaypointEditor({route: {params: {iouType = '', transactionID = '', waypointIndex = '', threadReportID = 0}} = {}, transaction, recentWaypoints}) {
const {windowWidth} = useWindowDimensions();
const [isDeleteStopModalOpen, setIsDeleteStopModalOpen] = useState(false);
const navigation = useNavigation();
const isFocused = navigation.isFocused();
const {translate} = useLocalize();
const {isOffline} = useNetwork();
const textInput = useRef(null);
const parsedWaypointIndex = parseInt(waypointIndex, 10);
const allWaypoints = lodashGet(transaction, 'comment.waypoints', {});
const waypointCount = _.keys(allWaypoints).length;
const currentWaypoint = lodashGet(allWaypoints, `waypoint${waypointIndex}`, {});
const wayPointDescriptionKey = useMemo(() => {
switch (parsedWaypointIndex) {
case 0:
return 'distance.waypointDescription.start';
case waypointCount - 1:
return 'distance.waypointDescription.finish';
default:
return 'distance.waypointDescription.stop';
}
}, [parsedWaypointIndex, waypointCount]);
const waypointAddress = lodashGet(currentWaypoint, 'address', '');
const isEditingWaypoint = Boolean(threadReportID);
const totalWaypoints = _.size(lodashGet(transaction, 'comment.waypoints', {}));
// Hide the menu when there is only start and finish waypoint
const shouldShowThreeDotsButton = totalWaypoints > 2;
const validate = (values) => {
const errors = {};
const waypointValue = values[`waypoint${waypointIndex}`] || '';
if (isOffline && waypointValue !== '' && !ValidationUtils.isValidAddress(waypointValue)) {
ErrorUtils.addErrorMessage(errors, `waypoint${waypointIndex}`, 'bankAccount.error.address');
}
// If the user is online and they are trying to save a value without using the autocomplete, show an error message instructing them to use a selected address instead.
// That enables us to save the address with coordinates when it is selected
if (!isOffline && waypointValue !== '' && waypointAddress !== waypointValue) {
ErrorUtils.addErrorMessage(errors, `waypoint${waypointIndex}`, 'distance.errors.selectSuggestedAddress');
}
return errors;
};
const saveWaypoint = (waypoint) => {
if (parsedWaypointIndex < _.size(allWaypoints)) {
Transaction.saveWaypoint(transactionID, waypointIndex, waypoint);
} else {
const finishWaypoint = lodashGet(allWaypoints, `waypoint${_.size(allWaypoints) - 1}`, {});
Transaction.saveWaypoint(transactionID, waypointIndex, finishWaypoint);
Transaction.saveWaypoint(transactionID, waypointIndex - 1, waypoint);
}
};
const submit = (values) => {
const waypointValue = values[`waypoint${waypointIndex}`] || '';
// Allows letting you set a waypoint to an empty value
if (waypointValue === '') {
Transaction.removeWaypoint(transactionID, waypointIndex);
}
// While the user is offline, the auto-complete address search will not work
// Therefore, we're going to save the waypoint as just the address, and the lat/long will be filled in on the backend
if (isOffline && waypointValue) {
const waypoint = {
lat: null,
lng: null,
address: waypointValue,
};
saveWaypoint(waypoint);
}
// Other flows will be handled by selecting a waypoint with selectWaypoint as this is mainly for the offline flow
Navigation.goBack(ROUTES.MONEY_REQUEST_DISTANCE_TAB.getRoute(iouType));
};
const deleteStopAndHideModal = () => {
Transaction.removeWaypoint(transactionID, waypointIndex);
setIsDeleteStopModalOpen(false);
Navigation.goBack(ROUTES.MONEY_REQUEST_DISTANCE_TAB.getRoute(iouType));
};
const selectWaypoint = (values) => {
const waypoint = {
lat: values.lat,
lng: values.lng,
address: values.address,
};
Transaction.saveWaypoint(transactionID, waypointIndex, waypoint, isEditingWaypoint);
if (isEditingWaypoint) {
Navigation.goBack(ROUTES.REPORT_WITH_ID.getRoute(threadReportID));
return;
}
Navigation.goBack(ROUTES.MONEY_REQUEST_DISTANCE_TAB.getRoute(iouType));
};
return (
<ScreenWrapper
includeSafeAreaPaddingBottom={false}
onEntryTransitionEnd={() => textInput.current && textInput.current.focus()}
shouldEnableMaxHeight
testID={WaypointEditor.displayName}
>
<FullPageNotFoundView shouldShow={(Number.isNaN(parsedWaypointIndex) || parsedWaypointIndex < 0 || parsedWaypointIndex > waypointCount) && isFocused}>
<HeaderWithBackButton
title={translate(wayPointDescriptionKey)}
shouldShowBackButton
onBackButtonPress={() => {
Navigation.goBack(ROUTES.MONEY_REQUEST_DISTANCE_TAB.getRoute(iouType));
}}
shouldShowThreeDotsButton={shouldShowThreeDotsButton}
threeDotsAnchorPosition={styles.threeDotsPopoverOffset(windowWidth)}
threeDotsMenuItems={[
{
icon: Expensicons.Trashcan,
text: translate('distance.deleteWaypoint'),
onSelected: () => setIsDeleteStopModalOpen(true),
},
]}
/>
<ConfirmModal
title={translate('distance.deleteWaypoint')}
isVisible={isDeleteStopModalOpen}
onConfirm={deleteStopAndHideModal}
onCancel={() => setIsDeleteStopModalOpen(false)}
prompt={translate('distance.deleteWaypointConfirmation')}
confirmText={translate('common.delete')}
cancelText={translate('common.cancel')}
danger
/>
<Form
style={[styles.flexGrow1, styles.mh5]}
formID={ONYXKEYS.FORMS.WAYPOINT_FORM}
enabledWhenOffline
validate={validate}
onSubmit={submit}
shouldValidateOnChange={false}
shouldValidateOnBlur={false}
submitButtonText={translate('common.save')}
>
<View>
<AddressSearch
canUseCurrentLocation
inputID={`waypoint${waypointIndex}`}
ref={(e) => (textInput.current = e)}
hint={!isOffline ? 'distance.errors.selectSuggestedAddress' : ''}
containerStyles={[styles.mt4]}
label={translate('distance.address')}
defaultValue={waypointAddress}
onPress={selectWaypoint}
maxInputLength={CONST.FORM_CHARACTER_LIMIT}
renamedInputKeys={{
address: `waypoint${waypointIndex}`,
city: null,
country: null,
street: null,
street2: null,
zipCode: null,
lat: null,
lng: null,
state: null,
}}
predefinedPlaces={recentWaypoints}
resultTypes=""
/>
</View>
</Form>
</FullPageNotFoundView>
</ScreenWrapper>
);
}
WaypointEditor.displayName = 'WaypointEditor';
WaypointEditor.propTypes = propTypes;
WaypointEditor.defaultProps = defaultProps;
export default withOnyx({
transaction: {
key: ({route}) => `${ONYXKEYS.COLLECTION.TRANSACTION}${lodashGet(route, 'params.transactionID')}`,
selector: (transaction) => (transaction ? {transactionID: transaction.transactionID, comment: {waypoints: lodashGet(transaction, 'comment.waypoints')}} : null),
},
recentWaypoints: {
key: ONYXKEYS.NVP_RECENT_WAYPOINTS,
// Only grab the most recent 5 waypoints because that's all that is shown in the UI. This also puts them into the format of data
// that the google autocomplete component expects for it's "predefined places" feature.
selector: (waypoints) =>
_.map(waypoints ? waypoints.slice(0, 5) : [], (waypoint) => ({
description: waypoint.address,
geometry: {
location: {
lat: waypoint.lat,
lng: waypoint.lng,
},
},
})),
},
})(WaypointEditor);