Repository navigation
Expand file tree
/
Copy pathAddressForm.tsx
More file actions
360 lines (307 loc) · 14.4 KB
/
Copy pathAddressForm.tsx
File metadata and controls
360 lines (307 loc) · 14.4 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
355
356
357
358
359
360
import useLocalize from '@hooks/useLocalize';
import useThemeStyles from '@hooks/useThemeStyles';
import type {ForwardedFSClassProps} from '@libs/Fullstory/types';
import {getInvalidAddressErrorTranslationPath, isRequiredFulfilled} from '@libs/ValidationUtils';
import type {Country} from '@src/CONST';
import CONST from '@src/CONST';
import type ONYXKEYS from '@src/ONYXKEYS';
import INPUT_IDS from '@src/types/form/HomeAddressForm';
import type {ReactNode} from 'react';
import {CONST as COMMON_CONST} from 'expensify-common';
import React, {createContext, useContext} from 'react';
import {View} from 'react-native';
import type {FormInputErrors, FormOnyxValues} from './Form/types';
import AddressSearch from './AddressSearch';
import CountrySelector from './CountrySelector';
import FormProvider from './Form/FormProvider';
import InputWrapper from './Form/InputWrapper';
import StateSelector from './StateSelector';
import TextInput from './TextInput';
type CountryZipRegex = {
regex?: RegExp;
samples?: string;
};
const countryZipRegexData: Partial<Record<string, CountryZipRegex>> = COMMON_CONST.COUNTRY_ZIP_REGEX_DATA;
type AddressFormID = typeof ONYXKEYS.FORMS.HOME_ADDRESS_FORM | typeof ONYXKEYS.FORMS.WORKSPACE_OFFICE_LOCATION_FORM;
type AddressFormProps<TFormID extends AddressFormID> = ForwardedFSClassProps & {
/** Address city field */
city?: string;
/** Address country field */
country?: Country | '';
/** Address state field */
state?: string;
/** Address street line 1 field */
street1?: string;
/** Address street line 2 field */
street2?: string;
/** Address zip code field */
zip?: string;
/** Callback which is executed when the user changes address, city or state */
onAddressChanged?: (value: unknown, key: unknown) => void;
/** Callback which is executed when the user submits his address changes */
onSubmit: (values: FormOnyxValues<TFormID>) => void;
/** Whether or not should the form data should be saved as draft */
shouldSaveDraft?: boolean;
/** Text displayed on the bottom submit button */
submitButtonText?: string;
/** A unique Onyx key identifying the form */
formID: TFormID;
/** The inputs of the form, which place the address inputs with `<AddressForm.Fields />`. Defaults to the address inputs alone. */
children?: ReactNode;
/** Validates the inputs the form adds to the address inputs. Its errors are added to the address errors. */
validate?: (values: FormOnyxValues<TFormID>) => Record<string, string>;
/** Whether to hide the country selector (e.g. when country cannot be changed) */
shouldHideCountrySelector?: boolean;
/** Whether the form submit button should be enabled when offline */
enabledWhenOffline?: boolean;
/**
* Whether to force the zip/postal code to be present. Workspace addresses for homeAndOffice commuter exclusions
* require a complete address
*/
shouldRequireZip?: boolean;
/** Whether PO boxes and mail drops are rejected on address lines */
shouldValidatePhysicalAddress?: boolean;
/**
* Whether the form should apply its own bottom safe-area padding. Defaults to true for the common case of a
* screen whose own ScreenWrapper has delegated bottom safe-area handling to this form (edge-to-edge mode).
* Set to false when the parent already applies it (e.g. a ScreenWrapper using the legacy, non-edge-to-edge
* default), otherwise the inset is padded twice, visible as extra bottom padding on iOS.
*/
addBottomSafeAreaPadding?: boolean;
};
/** The values the address inputs start from and report changes to, shared by AddressForm with its AddressForm.Fields */
type AddressFieldsSettings = {
city: string;
country: Country | '';
state: string;
street1: string;
street2: string;
zip: string;
onAddressChanged: (value: unknown, key: unknown) => void;
shouldSaveDraft: boolean;
shouldHideCountrySelector: boolean;
};
const AddressFieldsContext = createContext<AddressFieldsSettings>({
city: '',
country: '',
state: '',
street1: '',
street2: '',
zip: '',
onAddressChanged: () => {},
shouldSaveDraft: false,
shouldHideCountrySelector: false,
});
/** The address inputs of an AddressForm */
function AddressFormFields() {
const styles = useThemeStyles();
const {translate} = useLocalize();
const {city, country, state, street1, street2, zip, onAddressChanged, shouldSaveDraft, shouldHideCountrySelector} = useContext(AddressFieldsContext);
const zipSampleFormat = (country && countryZipRegexData[country]?.samples) ?? '';
const zipFormat = translate('common.zipCodeExampleFormat', zipSampleFormat);
const isUSAForm = country === CONST.COUNTRY.US;
return (
<>
<View>
<InputWrapper
InputComponent={AddressSearch}
inputID={INPUT_IDS.ADDRESS_LINE_1}
label={translate('common.addressLine', 1)}
onValueChange={(data: unknown, key: unknown) => {
onAddressChanged(data, key);
}}
defaultValue={street1}
renamedInputKeys={{
street: INPUT_IDS.ADDRESS_LINE_1,
street2: INPUT_IDS.ADDRESS_LINE_2,
city: INPUT_IDS.CITY,
state: INPUT_IDS.STATE,
zipCode: INPUT_IDS.ZIP_POST_CODE,
country: INPUT_IDS.COUNTRY as Country,
}}
shouldSaveDraft={shouldSaveDraft}
autoComplete="address-line1"
/>
</View>
<View style={styles.formSpaceVertical} />
<InputWrapper
InputComponent={TextInput}
inputID={INPUT_IDS.ADDRESS_LINE_2}
label={translate('common.addressLine', 2)}
aria-label={translate('common.addressLine', 2)}
role={CONST.ROLE.PRESENTATION}
defaultValue={street2}
spellCheck={false}
shouldSaveDraft={shouldSaveDraft}
autoComplete="address-line2"
/>
<View style={styles.formSpaceVertical} />
{!shouldHideCountrySelector && (
<>
<View style={styles.mhn5}>
<InputWrapper
InputComponent={CountrySelector}
inputID={INPUT_IDS.COUNTRY}
value={country}
onValueChange={onAddressChanged}
shouldSaveDraft={shouldSaveDraft}
/>
</View>
<View style={styles.formSpaceVertical} />
</>
)}
{isUSAForm ? (
<View style={styles.mhn5}>
<InputWrapper
InputComponent={StateSelector}
inputID={INPUT_IDS.STATE}
value={state}
onValueChange={onAddressChanged}
shouldSaveDraft={shouldSaveDraft}
/>
</View>
) : (
<InputWrapper
InputComponent={TextInput}
inputID={INPUT_IDS.STATE}
label={translate('common.stateOrProvince')}
aria-label={translate('common.stateOrProvince')}
role={CONST.ROLE.PRESENTATION}
value={state}
spellCheck={false}
onValueChange={onAddressChanged}
shouldSaveDraft={shouldSaveDraft}
/>
)}
<View style={styles.formSpaceVertical} />
<InputWrapper
InputComponent={TextInput}
inputID={INPUT_IDS.CITY}
label={translate('common.city')}
aria-label={translate('common.city')}
role={CONST.ROLE.PRESENTATION}
defaultValue={city}
spellCheck={false}
onValueChange={onAddressChanged}
shouldSaveDraft={shouldSaveDraft}
/>
<View style={styles.formSpaceVertical} />
<InputWrapper
InputComponent={TextInput}
inputID={INPUT_IDS.ZIP_POST_CODE}
label={translate('common.zipPostCode')}
aria-label={translate('common.zipPostCode')}
role={CONST.ROLE.PRESENTATION}
autoCapitalize="characters"
defaultValue={zip}
hint={zipFormat}
onValueChange={onAddressChanged}
shouldSaveDraft={shouldSaveDraft}
autoComplete="postal-code"
/>
</>
);
}
function AddressForm<TFormID extends AddressFormID>({
city = '',
country = '',
formID,
onAddressChanged = () => {},
onSubmit,
shouldSaveDraft = false,
state = '',
street1 = '',
street2 = '',
submitButtonText = '',
zip = '',
shouldHideCountrySelector = false,
enabledWhenOffline: enabledWhenOfflineProp = true,
shouldRequireZip = false,
shouldValidatePhysicalAddress = false,
addBottomSafeAreaPadding = true,
forwardedFSClass,
children,
validate,
}: AddressFormProps<TFormID>) {
const styles = useThemeStyles();
const {translate} = useLocalize();
const validator = (rawValues: FormOnyxValues<TFormID>): FormInputErrors<TFormID> => {
// Every form rendered here has the home address fields, so they are validated the same way
const addressValues: FormOnyxValues<typeof ONYXKEYS.FORMS.HOME_ADDRESS_FORM> = rawValues;
// When hidden, the country input is unregistered so fall back to the country prop.
const values = shouldHideCountrySelector ? {...addressValues, country: addressValues.country || country} : addressValues;
const errors: Record<string, string> = {};
const baseRequiredFields = shouldHideCountrySelector ? (['addressLine1', 'city', 'state'] as const) : (['addressLine1', 'city', 'country', 'state'] as const);
const requiredFields = shouldRequireZip ? ([...baseRequiredFields, 'zipPostCode'] as const) : baseRequiredFields;
// Check "State" dropdown is a valid state if selected Country is USA
if (values.country === CONST.COUNTRY.US && !values.state) {
errors.state = translate('common.error.fieldRequired');
}
// Add "Field required" errors if any required field is empty
for (const fieldKey of requiredFields) {
const fieldValue = values[fieldKey] ?? '';
if (isRequiredFulfilled(fieldValue)) {
continue;
}
errors[fieldKey] = translate('common.error.fieldRequired');
}
if (values.addressLine1.length > CONST.FORM_CHARACTER_LIMIT) {
errors.addressLine1 = translate('common.error.characterLimitExceedCounter', values.addressLine1.length, CONST.FORM_CHARACTER_LIMIT);
}
if (values.addressLine2.length > CONST.FORM_CHARACTER_LIMIT) {
errors.addressLine2 = translate('common.error.characterLimitExceedCounter', values.addressLine2.length, CONST.FORM_CHARACTER_LIMIT);
}
if (values.city.length > CONST.FORM_CHARACTER_LIMIT) {
errors.city = translate('common.error.characterLimitExceedCounter', values.city.length, CONST.FORM_CHARACTER_LIMIT);
}
if (values.country !== CONST.COUNTRY.US && values.state.length > CONST.STATE_CHARACTER_LIMIT) {
errors.state = translate('common.error.characterLimitExceedCounter', values.state.length, CONST.STATE_CHARACTER_LIMIT);
}
if (shouldValidatePhysicalAddress) {
const addressLine1Error = getInvalidAddressErrorTranslationPath(values.addressLine1);
if (values.addressLine1 && addressLine1Error) {
errors.addressLine1 = translate(addressLine1Error);
}
const addressLine2Error = getInvalidAddressErrorTranslationPath(values.addressLine2);
if (values.addressLine2 && addressLine2Error) {
errors.addressLine2 = translate(addressLine2Error);
}
}
// If no country is selected, default value is an empty string and there's no related regex data so we default to an empty object
const countryRegexDetails = values.country ? countryZipRegexData?.[values.country] : {};
// The postal code system might not exist for a country, so no regex either for them.
const countrySpecificZipRegex = countryRegexDetails?.regex;
const countryZipFormat = countryRegexDetails?.samples ?? '';
if (countrySpecificZipRegex) {
if (!countrySpecificZipRegex.test(values.zipPostCode?.trim().toUpperCase())) {
if (isRequiredFulfilled(values.zipPostCode?.trim())) {
errors.zipPostCode = translate('privatePersonalDetails.error.incorrectZipFormat', countryZipFormat);
} else {
errors.zipPostCode = translate('common.error.fieldRequired');
}
}
} else if (!COMMON_CONST.GENERIC_ZIP_CODE_REGEX.test(values?.zipPostCode?.trim()?.toUpperCase() ?? '')) {
errors.zipPostCode = translate('privatePersonalDetails.error.incorrectZipFormat');
}
// TypeScript can't tell that the address input IDs are keys of a generic form, though every form in AddressFormID has them
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
return (validate ? {...errors, ...validate(rawValues)} : errors) as FormInputErrors<TFormID>;
};
return (
<FormProvider
style={[styles.flexGrow1, styles.mh5]}
formID={formID}
validate={validator}
onSubmit={onSubmit}
submitButtonText={submitButtonText}
enabledWhenOffline={enabledWhenOfflineProp}
addBottomSafeAreaPadding={addBottomSafeAreaPadding}
forwardedFSClass={forwardedFSClass}
>
<AddressFieldsContext.Provider value={{city, country, state, street1, street2, zip, onAddressChanged, shouldSaveDraft, shouldHideCountrySelector}}>
{children ?? <AddressFormFields />}
</AddressFieldsContext.Provider>
</FormProvider>
);
}
export default Object.assign(AddressForm, {Fields: AddressFormFields});