-
Notifications
You must be signed in to change notification settings - Fork 3k
/
Copy pathindex.js
403 lines (358 loc) · 16.9 KB
/
index.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
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
import _ from 'underscore';
import React, {useMemo, useRef, useState} from 'react';
import PropTypes from 'prop-types';
import {LogBox, ScrollView, View, Text, ActivityIndicator} from 'react-native';
import {GooglePlacesAutocomplete} from 'react-native-google-places-autocomplete';
import lodashGet from 'lodash/get';
import compose from '../../libs/compose';
import withLocalize, {withLocalizePropTypes} from '../withLocalize';
import styles from '../../styles/styles';
import themeColors from '../../styles/themes/default';
import TextInput from '../TextInput';
import * as ApiUtils from '../../libs/ApiUtils';
import * as GooglePlacesUtils from '../../libs/GooglePlacesUtils';
import CONST from '../../CONST';
import * as StyleUtils from '../../styles/StyleUtils';
import resetDisplayListViewBorderOnBlur from './resetDisplayListViewBorderOnBlur';
import variables from '../../styles/variables';
import {withNetwork} from '../OnyxProvider';
import networkPropTypes from '../networkPropTypes';
// The error that's being thrown below will be ignored until we fork the
// react-native-google-places-autocomplete repo and replace the
// VirtualizedList component with a VirtualizedList-backed instead
LogBox.ignoreLogs(['VirtualizedLists should never be nested']);
const propTypes = {
/** The ID used to uniquely identify the input in a Form */
inputID: PropTypes.string,
/** Saves a draft of the input value when used in a form */
shouldSaveDraft: PropTypes.bool,
/** Callback that is called when the text input is blurred */
onBlur: PropTypes.func,
/** Error text to display */
errorText: PropTypes.oneOfType([PropTypes.string, PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.string, PropTypes.object]))]),
/** Hint text to display */
hint: PropTypes.string,
/** The label to display for the field */
label: PropTypes.string.isRequired,
/** The value to set the field to initially */
value: PropTypes.string,
/** The value to set the field to initially */
defaultValue: PropTypes.string,
/** A callback function when the value of this field has changed */
onInputChange: PropTypes.func.isRequired,
/** A callback function when an address has been auto-selected */
onPress: PropTypes.func,
/** Customize the TextInput container */
// eslint-disable-next-line react/forbid-prop-types
containerStyles: PropTypes.arrayOf(PropTypes.object),
/** Should address search be limited to results in the USA */
isLimitedToUSA: PropTypes.bool,
/** A list of predefined places that can be shown when the user isn't searching for something */
predefinedPlaces: 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,
}),
}),
}),
),
/** A map of inputID key names */
renamedInputKeys: PropTypes.shape({
street: PropTypes.string,
street2: PropTypes.string,
city: PropTypes.string,
state: PropTypes.string,
lat: PropTypes.string,
lng: PropTypes.string,
zipCode: PropTypes.string,
}),
/** Maximum number of characters allowed in search input */
maxInputLength: PropTypes.number,
/** The result types to return from the Google Places Autocomplete request */
resultTypes: PropTypes.string,
/** Information about the network */
network: networkPropTypes.isRequired,
...withLocalizePropTypes,
};
const defaultProps = {
inputID: undefined,
shouldSaveDraft: false,
onBlur: () => {},
onPress: () => {},
errorText: '',
hint: '',
value: undefined,
defaultValue: undefined,
containerStyles: [],
isLimitedToUSA: false,
renamedInputKeys: {
street: 'addressStreet',
street2: 'addressStreet2',
city: 'addressCity',
state: 'addressState',
zipCode: 'addressZipCode',
lat: 'addressLat',
lng: 'addressLng',
},
maxInputLength: undefined,
predefinedPlaces: [],
resultTypes: 'address',
};
// Do not convert to class component! It's been tried before and presents more challenges than it's worth.
// Relevant thread: https://expensify.slack.com/archives/C03TQ48KC/p1634088400387400
// Reference: https://github.com/FaridSafi/react-native-google-places-autocomplete/issues/609#issuecomment-886133839
function AddressSearch(props) {
const [displayListViewBorder, setDisplayListViewBorder] = useState(false);
const [isTyping, setIsTyping] = useState(false);
const containerRef = useRef();
const query = useMemo(
() => ({
language: props.preferredLocale,
types: props.resultTypes,
components: props.isLimitedToUSA ? 'country:us' : undefined,
}),
[props.preferredLocale, props.resultTypes, props.isLimitedToUSA],
);
const saveLocationDetails = (autocompleteData, details) => {
const addressComponents = details.address_components;
if (!addressComponents) {
// When there are details, but no address_components, this indicates that some predefined options have been passed
// to this component which don't match the usual properties coming from auto-complete. In that case, only a limited
// amount of data massaging needs to happen for what the parent expects to get from this function.
if (_.size(details)) {
props.onPress({
address: lodashGet(details, 'description', ''),
lat: lodashGet(details, 'geometry.location.lat', 0),
lng: lodashGet(details, 'geometry.location.lng', 0),
});
}
return;
}
// Gather the values from the Google details
const {
street_number: streetNumber,
route: streetName,
subpremise,
locality,
sublocality,
postal_town: postalTown,
postal_code: zipCode,
administrative_area_level_1: state,
administrative_area_level_2: stateFallback,
country: countryPrimary,
} = GooglePlacesUtils.getAddressComponents(addressComponents, {
street_number: 'long_name',
route: 'long_name',
subpremise: 'long_name',
locality: 'long_name',
sublocality: 'long_name',
postal_town: 'long_name',
postal_code: 'long_name',
administrative_area_level_1: 'short_name',
administrative_area_level_2: 'long_name',
country: 'short_name',
});
// The state's iso code (short_name) is needed for the StatePicker component but we also
// need the state's full name (long_name) when we render the state in a TextInput.
const {administrative_area_level_1: longStateName} = GooglePlacesUtils.getAddressComponents(addressComponents, {
administrative_area_level_1: 'long_name',
});
// Make sure that the order of keys remains such that the country is always set above the state.
// Refer to https://github.com/Expensify/App/issues/15633 for more information.
const {
country: countryFallbackLongName = '',
state: stateAutoCompleteFallback = '',
city: cityAutocompleteFallback = '',
} = GooglePlacesUtils.getPlaceAutocompleteTerms(autocompleteData.terms);
const countryFallback = _.findKey(CONST.ALL_COUNTRIES, (country) => country === countryFallbackLongName);
const country = countryPrimary || countryFallback;
const values = {
street: `${streetNumber} ${streetName}`.trim(),
// Autocomplete returns any additional valid address fragments (e.g. Apt #) as subpremise.
street2: subpremise,
// Make sure country is updated first, since city and state will be reset if the country changes
country: '',
// When locality is not returned, many countries return the city as postalTown (e.g. 5 New Street
// Square, London), otherwise as sublocality (e.g. 384 Court Street Brooklyn). If postalTown is
// returned, the sublocality will be a city subdivision so shouldn't take precedence (e.g.
// Salagatan, Upssala, Sweden).
city: locality || postalTown || sublocality || cityAutocompleteFallback,
zipCode,
state: state || stateAutoCompleteFallback,
lat: lodashGet(details, 'geometry.location.lat', 0),
lng: lodashGet(details, 'geometry.location.lng', 0),
address: lodashGet(details, 'formatted_address', ''),
};
// If the address is not in the US, use the full length state name since we're displaying the address's
// state / province in a TextInput instead of in a picker.
if (country !== CONST.COUNTRY.US) {
values.state = longStateName;
}
// UK addresses return countries (e.g. England) in the state field (administrative_area_level_1)
// So we use a secondary field (administrative_area_level_2) as a fallback
if (country === CONST.COUNTRY.GB) {
values.state = stateFallback;
}
// Not all pages define the Address Line 2 field, so in that case we append any additional address details
// (e.g. Apt #) to Address Line 1
if (subpremise && typeof props.renamedInputKeys.street2 === 'undefined') {
values.street += `, ${subpremise}`;
}
const isValidCountryCode = lodashGet(CONST.ALL_COUNTRIES, country);
if (isValidCountryCode) {
values.country = country;
}
if (props.inputID) {
_.each(values, (value, key) => {
const inputKey = lodashGet(props.renamedInputKeys, key, key);
if (!inputKey) {
return;
}
props.onInputChange(value, inputKey);
});
} else {
props.onInputChange(values);
}
props.onPress(values);
};
return (
/*
* The GooglePlacesAutocomplete component uses a VirtualizedList internally,
* and VirtualizedLists cannot be directly nested within other VirtualizedLists of the same orientation.
* To work around this, we wrap the GooglePlacesAutocomplete component with a horizontal ScrollView
* that has scrolling disabled and would otherwise not be needed
*/
<ScrollView
horizontal
contentContainerStyle={styles.flex1}
scrollEnabled={false}
// keyboardShouldPersistTaps="always" is required for Android native,
// otherwise tapping on a result doesn't do anything. More information
// here: https://github.com/FaridSafi/react-native-google-places-autocomplete#use-inside-a-scrollview-or-flatlist
keyboardShouldPersistTaps="always"
>
<View
style={styles.w100}
ref={containerRef}
>
<GooglePlacesAutocomplete
disableScroll
fetchDetails
suppressDefaultStyles
enablePoweredByContainer={false}
predefinedPlaces={props.predefinedPlaces}
listEmptyComponent={
props.network.isOffline || !isTyping ? null : (
<Text style={[styles.textLabel, styles.colorMuted, styles.pv4, styles.ph3, styles.overflowAuto]}>{props.translate('common.noResultsFound')}</Text>
)
}
listLoaderComponent={
<View style={[styles.pv4]}>
<ActivityIndicator
color={themeColors.spinner}
size="small"
/>
</View>
}
renderHeaderComponent={() =>
!props.value &&
props.predefinedPlaces && (
<Text style={[styles.textLabel, styles.colorMuted, styles.pt2, styles.ph3, styles.overflowAuto]}>{props.translate('common.recentDestinations')}</Text>
)
}
onPress={(data, details) => {
saveLocationDetails(data, details);
setIsTyping(false);
// After we select an option, we set displayListViewBorder to false to prevent UI flickering
setDisplayListViewBorder(false);
}}
query={query}
requestUrl={{
useOnPlatform: 'all',
url: props.network.isOffline ? null : ApiUtils.getCommandURL({command: 'Proxy_GooglePlaces&proxyUrl='}),
}}
textInputProps={{
InputComp: TextInput,
ref: (node) => {
if (!props.innerRef) {
return;
}
if (_.isFunction(props.innerRef)) {
props.innerRef(node);
return;
}
// eslint-disable-next-line no-param-reassign
props.innerRef.current = node;
},
label: props.label,
containerStyles: props.containerStyles,
errorText: props.errorText,
hint: displayListViewBorder ? undefined : props.hint,
value: props.value,
defaultValue: props.defaultValue,
inputID: props.inputID,
shouldSaveDraft: props.shouldSaveDraft,
onBlur: (event) => {
resetDisplayListViewBorderOnBlur(setDisplayListViewBorder, event, containerRef);
props.onBlur();
},
autoComplete: 'off',
onInputChange: (text) => {
setIsTyping(true);
if (props.inputID) {
props.onInputChange(text);
} else {
props.onInputChange({street: text});
}
// If the text is empty and we have no predefined places, we set displayListViewBorder to false to prevent UI flickering
if (_.isEmpty(text) && _.isEmpty(props.predefinedPlaces)) {
setDisplayListViewBorder(false);
}
},
maxLength: props.maxInputLength,
spellCheck: false,
}}
styles={{
textInputContainer: [styles.flexColumn],
listView: [StyleUtils.getGoogleListViewStyle(displayListViewBorder), styles.overflowAuto, styles.borderLeft, styles.borderRight],
row: [styles.pv4, styles.ph3, styles.overflowAuto],
description: [styles.googleSearchText],
separator: [styles.googleSearchSeparator],
}}
numberOfLines={2}
isRowScrollable={false}
listHoverColor={themeColors.border}
listUnderlayColor={themeColors.buttonPressedBG}
onLayout={(event) => {
// We use the height of the element to determine if we should hide the border of the listView dropdown
// to prevent a lingering border when there are no address suggestions.
setDisplayListViewBorder(event.nativeEvent.layout.height > variables.googleEmptyListViewHeight);
}}
/>
</View>
</ScrollView>
);
}
AddressSearch.propTypes = propTypes;
AddressSearch.defaultProps = defaultProps;
AddressSearch.displayName = 'AddressSearch';
export default compose(
withNetwork(),
withLocalize,
)(
React.forwardRef((props, ref) => (
<AddressSearch
// eslint-disable-next-line react/jsx-props-no-spreading
{...props}
innerRef={ref}
/>
)),
);