Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[TS migration] Migrate 'AddressForm.js' component to TypeScript #34149

Merged
merged 15 commits into from
Mar 4, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/ONYXKEYS.ts
Original file line number Diff line number Diff line change
Expand Up @@ -540,8 +540,8 @@ type OnyxValues = {
[ONYXKEYS.FORMS.REPORT_VIRTUAL_CARD_FRAUD_DRAFT]: OnyxTypes.Form;
[ONYXKEYS.FORMS.REPORT_PHYSICAL_CARD_FORM]: OnyxTypes.Form;
[ONYXKEYS.FORMS.REPORT_PHYSICAL_CARD_FORM_DRAFT]: OnyxTypes.Form;
[ONYXKEYS.FORMS.GET_PHYSICAL_CARD_FORM]: OnyxTypes.Form;
[ONYXKEYS.FORMS.GET_PHYSICAL_CARD_FORM_DRAFT]: OnyxTypes.Form;
[ONYXKEYS.FORMS.GET_PHYSICAL_CARD_FORM]: OnyxTypes.AddressForm;
[ONYXKEYS.FORMS.GET_PHYSICAL_CARD_FORM_DRAFT]: OnyxTypes.AddressForm;
[ONYXKEYS.FORMS.POLICY_REPORT_FIELD_EDIT_FORM]: OnyxTypes.Form;
[ONYXKEYS.FORMS.POLICY_REPORT_FIELD_EDIT_FORM_DRAFT]: OnyxTypes.Form;
// @ts-expect-error Different values are defined under the same key: ReimbursementAccount and ReimbursementAccountForm
Expand Down
135 changes: 79 additions & 56 deletions src/components/AddressForm.js → src/components/AddressForm.tsx
Original file line number Diff line number Diff line change
@@ -1,109 +1,134 @@
import {CONST as COMMON_CONST} from 'expensify-common/lib/CONST';
import lodashGet from 'lodash/get';
import PropTypes from 'prop-types';
import type {CONST as COMMON_CONST} from 'expensify-common/lib/CONST';
import React, {useCallback} from 'react';
import {View} from 'react-native';
import _ from 'underscore';
import useLocalize from '@hooks/useLocalize';
import useThemeStyles from '@hooks/useThemeStyles';
import * as ErrorUtils from '@libs/ErrorUtils';
import type * as Localize from '@libs/Localize';
import Navigation from '@libs/Navigation/Navigation';
import * as ValidationUtils from '@libs/ValidationUtils';
import CONST from '@src/CONST';
import type {Country} from '@src/CONST';
import type ONYXKEYS from '@src/ONYXKEYS';
import type {Errors} from '@src/types/onyx/OnyxCommon';
import AddressSearch from './AddressSearch';
import CountrySelector from './CountrySelector';
import FormProvider from './Form/FormProvider';
import InputWrapper from './Form/InputWrapper';
import type {OnyxFormValuesFields} from './Form/types';
import StatePicker from './StatePicker';
import TextInput from './TextInput';

const propTypes = {
type AddressFormProps = {
/** Address city field */
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
type AddressFormProps = {
type CountryZipRegex = {
regex?: RegExp;
samples?: string
}
type AddressFormProps = {

Let's add a new type for the country zip regex.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

updated

city: PropTypes.string,
city?: string;

/** Address country field */
country: PropTypes.string,
country?: Country | '';

/** Address state field */
state: PropTypes.string,
state?: keyof typeof COMMON_CONST.STATES | '';

/** Address street line 1 field */
street1: PropTypes.string,
street1?: string;

/** Address street line 2 field */
street2: PropTypes.string,
street2?: string;

/** Address zip code field */
zip: PropTypes.string,
zip?: string;

/** Callback which is executed when the user changes address, city or state */
onAddressChanged: PropTypes.func,
onAddressChanged?: (value: unknown, key: string) => void;

/** Callback which is executed when the user submits his address changes */
onSubmit: PropTypes.func.isRequired,
onSubmit: () => void;

/** Whether or not should the form data should be saved as draft */
shouldSaveDraft: PropTypes.bool,
shouldSaveDraft?: boolean;

/** Text displayed on the bottom submit button */
submitButtonText: PropTypes.string,
submitButtonText?: string;

/** A unique Onyx key identifying the form */
formID: PropTypes.string.isRequired,
formID: typeof ONYXKEYS.FORMS.GET_PHYSICAL_CARD_FORM;
};

const defaultProps = {
city: '',
country: '',
onAddressChanged: () => {},
shouldSaveDraft: false,
state: '',
street1: '',
street2: '',
submitButtonText: '',
zip: '',
};

function AddressForm({city, country, formID, onAddressChanged, onSubmit, shouldSaveDraft, state, street1, street2, submitButtonText, zip}) {
function AddressForm({
city = '',
country = '',
formID,
onAddressChanged = () => {},
onSubmit,
shouldSaveDraft = false,
state = '',
street1 = '',
street2 = '',
submitButtonText = '',
zip = '',
}: AddressFormProps) {
const styles = useThemeStyles();
const {translate} = useLocalize();
const zipSampleFormat = lodashGet(CONST.COUNTRY_ZIP_REGEX_DATA, [country, 'samples'], '');

let zipSampleFormat = '';

if (country) {
const countryData = CONST.COUNTRY_ZIP_REGEX_DATA[country];
if (countryData && 'samples' in countryData) {
zipSampleFormat = countryData.samples;
}
}

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
let zipSampleFormat = '';
if (country) {
const countryData = CONST.COUNTRY_ZIP_REGEX_DATA[country];
if (countryData && 'samples' in countryData) {
zipSampleFormat = countryData.samples;
}
}
const zipSampleFormat = (country && (CONST.COUNTRY_ZIP_REGEX_DATA[country] as CountryZipRegex)?.samples) ?? '';

Let's simplify the above code a bit with the new type CountryZipRegex.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

updated

const zipFormat = translate('common.zipCodeExampleFormat', {zipSampleFormat});
const isUSAForm = country === CONST.COUNTRY.US;

/**
* @param {Function} translate - translate function
* @param {Boolean} isUSAForm - selected country ISO code is US
* @param {Object} values - form input values
* @returns {Object} - An object containing the errors for each inputID
* @param translate - translate function
* @param isUSAForm - selected country ISO code is US
* @param values - form input values
* @returns - An object containing the errors for each inputID
*/
const validator = useCallback((values) => {
const errors = {};
const requiredFields = ['addressLine1', 'city', 'country', 'state'];

const validator = useCallback((values: OnyxFormValuesFields<typeof ONYXKEYS.FORMS.GET_PHYSICAL_CARD_FORM>): Errors => {
const errors: Errors = {};
const requiredFields = ['addressLine1', 'city', 'country', 'state'] as const;

// Check "State" dropdown is a valid state if selected Country is USA
if (values.country === CONST.COUNTRY.US && !COMMON_CONST.STATES[values.state]) {
if (values.country === CONST.COUNTRY.US && !values.state) {
errors.state = 'common.error.fieldRequired';
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it does not work as before

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It works as it was before since this value can be entered only with dropdown

}

// Add "Field required" errors if any required field is empty
_.each(requiredFields, (fieldKey) => {
if (ValidationUtils.isRequiredFulfilled(values[fieldKey])) {
requiredFields.forEach((fieldKey) => {
const fieldValue = values[fieldKey] ?? '';
if (ValidationUtils.isRequiredFulfilled(fieldValue)) {
return;
}

errors[fieldKey] = 'common.error.fieldRequired';
});

// 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 = lodashGet(CONST.COUNTRY_ZIP_REGEX_DATA, values.country, {});
const countryRegexDetails = values.country ? CONST.COUNTRY_ZIP_REGEX_DATA?.[values.country] : {};

// The postal code system might not exist for a country, so no regex either for them.
const countrySpecificZipRegex = lodashGet(countryRegexDetails, 'regex');
const countryZipFormat = lodashGet(countryRegexDetails, 'samples');
let countrySpecificZipRegex;
let countryZipFormat;

if ('regex' in countryRegexDetails) {
countrySpecificZipRegex = countryRegexDetails.regex as RegExp;
}

if ('samples' in countryRegexDetails) {
countryZipFormat = countryRegexDetails.samples as string;
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why are this assertions needed? What are the types of countryRegexDetails.regex and countryRegexDetails.samples?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To specify types in this case (some countries don't have those fields and ts resolve those fields as unknown)

RegExp and string accordingly


ErrorUtils.addErrorMessage(errors, 'firstName', 'bankAccount.error.firstName');

if (countrySpecificZipRegex) {
if (!countrySpecificZipRegex.test(values.zipPostCode.trim().toUpperCase())) {
if (ValidationUtils.isRequiredFulfilled(values.zipPostCode.trim())) {
errors.zipPostCode = ['privatePersonalDetails.error.incorrectZipFormat', {zipFormat: countryZipFormat}];
errors.zipPostCode = ['privatePersonalDetails.error.incorrectZipFormat', {zipFormat: countryZipFormat ?? ''}];
} else {
errors.zipPostCode = 'common.error.fieldRequired';
}
Expand All @@ -129,12 +154,12 @@ function AddressForm({city, country, formID, onAddressChanged, onSubmit, shouldS
InputComponent={AddressSearch}
inputID="addressLine1"
label={translate('common.addressLine', {lineNumber: 1})}
onValueChange={(data, key) => {
onValueChange={(data: unknown, key: string) => {
onAddressChanged(data, key);
// This enforces the country selector to use the country from address instead of the country from URL
Navigation.setParams({country: undefined});
}}
defaultValue={street1 || ''}
defaultValue={street1}
renamedInputKeys={{
street: 'addressLine1',
street2: 'addressLine2',
Expand All @@ -153,8 +178,8 @@ function AddressForm({city, country, formID, onAddressChanged, onSubmit, shouldS
inputID="addressLine2"
label={translate('common.addressLine', {lineNumber: 2})}
aria-label={translate('common.addressLine', {lineNumber: 2})}
role={CONST.ACCESSIBILITY_ROLE.TEXT}
defaultValue={street2 || ''}
role={CONST.ROLE.PRESENTATION}
defaultValue={street2}
maxLength={CONST.FORM_CHARACTER_LIMIT}
spellCheck={false}
shouldSaveDraft={shouldSaveDraft}
Expand Down Expand Up @@ -185,8 +210,8 @@ function AddressForm({city, country, formID, onAddressChanged, onSubmit, shouldS
inputID="state"
label={translate('common.stateOrProvince')}
aria-label={translate('common.stateOrProvince')}
role={CONST.ACCESSIBILITY_ROLE.TEXT}
value={state || ''}
role={CONST.ROLE.PRESENTATION}
value={state}
maxLength={CONST.FORM_CHARACTER_LIMIT}
spellCheck={false}
onValueChange={onAddressChanged}
Expand All @@ -199,8 +224,8 @@ function AddressForm({city, country, formID, onAddressChanged, onSubmit, shouldS
inputID="city"
label={translate('common.city')}
aria-label={translate('common.city')}
role={CONST.ACCESSIBILITY_ROLE.TEXT}
defaultValue={city || ''}
role={CONST.ROLE.PRESENTATION}
defaultValue={city}
maxLength={CONST.FORM_CHARACTER_LIMIT}
spellCheck={false}
onValueChange={onAddressChanged}
Expand All @@ -212,9 +237,9 @@ function AddressForm({city, country, formID, onAddressChanged, onSubmit, shouldS
inputID="zipPostCode"
label={translate('common.zipPostCode')}
aria-label={translate('common.zipPostCode')}
role={CONST.ACCESSIBILITY_ROLE.TEXT}
role={CONST.ROLE.PRESENTATION}
autoCapitalize="characters"
defaultValue={zip || ''}
defaultValue={zip}
maxLength={CONST.BANK_ACCOUNT.MAX_LENGTH.ZIP_CODE}
hint={zipFormat}
onValueChange={onAddressChanged}
Expand All @@ -224,8 +249,6 @@ function AddressForm({city, country, formID, onAddressChanged, onSubmit, shouldS
);
}

AddressForm.defaultProps = defaultProps;
AddressForm.displayName = 'AddressForm';
AddressForm.propTypes = propTypes;

export default AddressForm;
2 changes: 1 addition & 1 deletion src/components/AddressSearch/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -398,7 +398,7 @@ function AddressSearch(
if (inputID) {
onInputChange?.(text);
} else {
onInputChange({street: text});
onInputChange?.({street: text});
}
// If the text is empty and we have no predefined places, we set displayListViewBorder to false to prevent UI flickering
if (!text && !predefinedPlaces.length) {
Expand Down
7 changes: 4 additions & 3 deletions src/components/AddressSearch/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,10 @@ type RenamedInputKeysProps = {
street2: string;
city: string;
state: string;
lat: string;
lng: string;
lat?: string;
lng?: string;
zipCode: string;
country?: string;
};

type OnPressProps = {
Expand Down Expand Up @@ -58,7 +59,7 @@ type AddressSearchProps = {
defaultValue?: string;

/** A callback function when the value of this field has changed */
onInputChange: (value: string | number | RenamedInputKeysProps | StreetValue, key?: string) => void;
onInputChange?: (value: string | number | RenamedInputKeysProps | StreetValue, key?: string) => void;

/** A callback function when an address has been auto-selected */
onPress?: (props: OnPressProps) => void;
Expand Down
6 changes: 3 additions & 3 deletions src/components/CountrySelector.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,17 @@ type CountrySelectorProps = {
errorText?: string;

/** Callback called when the country changes. */
onInputChange: (value?: string) => void;
onInputChange?: (value?: string) => void;

/** Current selected country */
value?: Country;
value?: Country | '';

/** inputID used by the Form component */
// eslint-disable-next-line react/no-unused-prop-types
inputID: string;
};

function CountrySelector({errorText = '', value: countryCode, onInputChange}: CountrySelectorProps, ref: ForwardedRef<View>) {
function CountrySelector({errorText = '', value: countryCode, onInputChange = () => {}}: CountrySelectorProps, ref: ForwardedRef<View>) {
const styles = useThemeStyles();
const {translate} = useLocalize();

Expand Down
12 changes: 11 additions & 1 deletion src/components/Form/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@ import type {GestureResponderEvent, NativeSyntheticEvent, StyleProp, TextInputFo
import type AddressSearch from '@components/AddressSearch';
import type AmountTextInput from '@components/AmountTextInput';
import type CheckboxWithLabel from '@components/CheckboxWithLabel';
import type CountrySelector from '@components/CountrySelector';
import type Picker from '@components/Picker';
import type SingleChoiceQuestion from '@components/SingleChoiceQuestion';
import type StatePicker from '@components/StatePicker';
import type TextInput from '@components/TextInput';
import type {OnyxFormKey, OnyxValues} from '@src/ONYXKEYS';
import type Form from '@src/types/onyx/Form';
Expand All @@ -17,7 +19,15 @@ import type {BaseForm, FormValueType} from '@src/types/onyx/Form';
* TODO: Add remaining inputs here once these components are migrated to Typescript:
* CountrySelector | StatePicker | DatePicker | EmojiPickerButtonDropdown | RoomNameInput | ValuePicker
*/
type ValidInputs = typeof TextInput | typeof AmountTextInput | typeof SingleChoiceQuestion | typeof CheckboxWithLabel | typeof Picker | typeof AddressSearch;
type ValidInputs =
| typeof TextInput
| typeof AmountTextInput
| typeof SingleChoiceQuestion
| typeof CheckboxWithLabel
| typeof Picker
| typeof AddressSearch
| typeof CountrySelector
| typeof StatePicker;

type ValueTypeKey = 'string' | 'boolean' | 'date';

Expand Down
2 changes: 1 addition & 1 deletion src/libs/Navigation/Navigation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,7 @@ function goBack(fallbackRoute?: Route, shouldEnforceFallback = false, shouldPopT
/**
* Update route params for the specified route.
*/
function setParams(params: Record<string, unknown>, routeKey: string) {
function setParams(params: Record<string, unknown>, routeKey = '') {
navigationRef.current?.dispatch({
...CommonActions.setParams(params),
source: routeKey,
Expand Down
6 changes: 5 additions & 1 deletion src/libs/ValidationUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,11 @@ function isValidPastDate(date: string | Date): boolean {
/**
* Used to validate a value that is "required".
*/
function isRequiredFulfilled(value: string | Date | unknown[] | Record<string, unknown>): boolean {
function isRequiredFulfilled(value: boolean | string | Date | unknown[] | Record<string, unknown>): boolean {
if (typeof value === 'boolean') {
return true;
}

if (typeof value === 'string') {
return !StringUtils.isEmptyString(value);
}
Expand Down
Loading
Loading