2022-07-13 07:42:58 -07:00
|
|
|
import React from 'react';
|
|
|
|
|
2022-07-13 09:40:02 -07:00
|
|
|
import { CountryCode, formatPhoneNumber } from 'soapbox/utils/phone';
|
2022-07-13 07:42:58 -07:00
|
|
|
|
2022-07-13 09:40:02 -07:00
|
|
|
import HStack from '../hstack/hstack';
|
2022-07-13 07:42:58 -07:00
|
|
|
import Input from '../input/input';
|
|
|
|
|
2022-07-13 09:40:02 -07:00
|
|
|
import CountryCodeDropdown from './country-code-dropdown';
|
|
|
|
|
|
|
|
interface IPhoneInput extends Pick<React.InputHTMLAttributes<HTMLInputElement>, 'required' | 'autoFocus'> {
|
2022-07-13 07:42:58 -07:00
|
|
|
/** Input phone number. */
|
|
|
|
value?: string,
|
2022-07-13 09:40:02 -07:00
|
|
|
/** E164 country code. */
|
|
|
|
countryCode?: CountryCode,
|
2022-07-13 07:42:58 -07:00
|
|
|
/** Change event handler taking the formatted input. */
|
|
|
|
onChange?: (phone: string) => void,
|
|
|
|
}
|
|
|
|
|
|
|
|
/** Internationalized phone input with country code picker. */
|
|
|
|
const PhoneInput: React.FC<IPhoneInput> = (props) => {
|
2022-07-13 09:40:02 -07:00
|
|
|
const { countryCode = 1, value = '', onChange, ...rest } = props;
|
|
|
|
|
|
|
|
const handleCountryChange = (code: CountryCode) => {
|
|
|
|
if (onChange) {
|
|
|
|
onChange(formatPhoneNumber(countryCode, value));
|
|
|
|
}
|
|
|
|
};
|
2022-07-13 07:42:58 -07:00
|
|
|
|
|
|
|
/** Pass the formatted phone to the handler. */
|
|
|
|
const handleChange: React.ChangeEventHandler<HTMLInputElement> = ({ target }) => {
|
|
|
|
if (onChange) {
|
2022-07-13 09:40:02 -07:00
|
|
|
onChange(formatPhoneNumber(countryCode, target.value));
|
2022-07-13 07:42:58 -07:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
return (
|
2022-07-13 09:40:02 -07:00
|
|
|
<HStack>
|
|
|
|
<CountryCodeDropdown
|
|
|
|
countryCode={countryCode}
|
|
|
|
onChange={handleCountryChange}
|
|
|
|
/>
|
|
|
|
|
|
|
|
<Input
|
|
|
|
type='text'
|
|
|
|
onChange={handleChange}
|
|
|
|
value={value}
|
|
|
|
{...rest}
|
|
|
|
/>
|
|
|
|
</HStack>
|
2022-07-13 07:42:58 -07:00
|
|
|
);
|
|
|
|
};
|
|
|
|
|
|
|
|
export default PhoneInput;
|