2020-01-17 16:58:08 +00:00
|
|
|
/**
|
|
|
|
* External dependencies
|
|
|
|
*/
|
|
|
|
import PropTypes from 'prop-types';
|
|
|
|
import { decodeEntities } from '@wordpress/html-entities';
|
2020-03-17 11:45:33 +00:00
|
|
|
import { useValidationContext } from '@woocommerce/base-context';
|
|
|
|
import classnames from 'classnames';
|
2020-01-17 16:58:08 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Internal dependencies
|
|
|
|
*/
|
2020-02-14 12:30:33 +00:00
|
|
|
import Select from '../select';
|
2020-03-17 11:45:33 +00:00
|
|
|
import { ValidationInputError } from '../validation';
|
2020-01-17 16:58:08 +00:00
|
|
|
|
|
|
|
const CountryInput = ( {
|
|
|
|
className,
|
|
|
|
countries,
|
|
|
|
label,
|
|
|
|
onChange,
|
|
|
|
value = '',
|
2020-02-19 15:10:26 +00:00
|
|
|
autoComplete = 'off',
|
2020-03-03 10:46:53 +00:00
|
|
|
required = false,
|
2020-01-17 16:58:08 +00:00
|
|
|
} ) => {
|
|
|
|
const options = Object.keys( countries ).map( ( key ) => ( {
|
|
|
|
key,
|
|
|
|
name: decodeEntities( countries[ key ] ),
|
|
|
|
} ) );
|
2020-03-17 11:45:33 +00:00
|
|
|
const { getValidationError } = useValidationContext();
|
|
|
|
const errorMessage = getValidationError( 'country' );
|
2020-01-17 16:58:08 +00:00
|
|
|
|
|
|
|
return (
|
2020-03-17 11:45:33 +00:00
|
|
|
<div className={ classnames( className, 'wc-block-country-input' ) }>
|
2020-02-19 15:10:26 +00:00
|
|
|
<Select
|
|
|
|
label={ label }
|
|
|
|
onChange={ onChange }
|
|
|
|
options={ options }
|
|
|
|
value={ options.find( ( option ) => option.key === value ) }
|
2020-03-03 10:46:53 +00:00
|
|
|
required={ required }
|
2020-03-17 11:45:33 +00:00
|
|
|
hasError={ !! errorMessage }
|
2020-02-19 15:10:26 +00:00
|
|
|
/>
|
|
|
|
{ autoComplete !== 'off' && (
|
|
|
|
<input
|
|
|
|
type="text"
|
|
|
|
aria-hidden={ true }
|
|
|
|
autoComplete={ autoComplete }
|
|
|
|
value={ value }
|
|
|
|
onChange={ ( event ) => {
|
|
|
|
const textValue = event.target.value;
|
|
|
|
const foundOption = options.find(
|
|
|
|
( option ) => option.key === textValue
|
|
|
|
);
|
|
|
|
onChange( foundOption ? foundOption.key : '' );
|
|
|
|
} }
|
|
|
|
style={ {
|
2020-03-13 12:02:08 +00:00
|
|
|
minHeight: '0',
|
2020-02-19 15:10:26 +00:00
|
|
|
height: '0',
|
|
|
|
border: '0',
|
|
|
|
padding: '0',
|
|
|
|
position: 'absolute',
|
|
|
|
} }
|
2020-03-04 14:35:18 +00:00
|
|
|
tabIndex={ -1 }
|
2020-02-19 15:10:26 +00:00
|
|
|
/>
|
|
|
|
) }
|
2020-03-17 11:45:33 +00:00
|
|
|
<ValidationInputError errorMessage={ errorMessage } />
|
|
|
|
</div>
|
2020-01-17 16:58:08 +00:00
|
|
|
);
|
|
|
|
};
|
|
|
|
|
|
|
|
CountryInput.propTypes = {
|
|
|
|
countries: PropTypes.objectOf( PropTypes.string ).isRequired,
|
|
|
|
onChange: PropTypes.func.isRequired,
|
|
|
|
className: PropTypes.string,
|
|
|
|
label: PropTypes.string,
|
|
|
|
value: PropTypes.string,
|
2020-02-19 15:10:26 +00:00
|
|
|
autoComplete: PropTypes.string,
|
2020-01-17 16:58:08 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
export default CountryInput;
|