2019-12-18 11:29:20 +00:00
|
|
|
/**
|
|
|
|
* External dependencies
|
|
|
|
*/
|
|
|
|
import NumberFormat from 'react-number-format';
|
2020-01-14 20:52:42 +00:00
|
|
|
import classNames from 'classnames';
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Internal dependencies
|
|
|
|
*/
|
|
|
|
import './style.scss';
|
2019-12-18 11:29:20 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Formats currency data into the expected format for NumberFormat.
|
|
|
|
*
|
|
|
|
* @param {Object} currency Currency data.
|
|
|
|
* @return {Object} Formatted props for NumberFormat.
|
|
|
|
*/
|
|
|
|
const currencyToNumberFormat = ( currency ) => {
|
|
|
|
return {
|
|
|
|
thousandSeparator: currency.thousandSeparator,
|
|
|
|
decimalSeparator: currency.decimalSeparator,
|
|
|
|
decimalScale: currency.minorUnit,
|
2020-01-08 20:10:29 +00:00
|
|
|
fixedDecimalScale: true,
|
2019-12-18 11:29:20 +00:00
|
|
|
prefix: currency.prefix,
|
|
|
|
suffix: currency.suffix,
|
|
|
|
isNumericString: true,
|
|
|
|
};
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Formatted price component.
|
|
|
|
*
|
|
|
|
* Takes a price and returns a formatted price using the NumberFormat component.
|
|
|
|
*
|
|
|
|
* @param {Object} props Component props.
|
|
|
|
*/
|
|
|
|
const FormattedMonetaryAmount = ( {
|
2020-01-14 20:52:42 +00:00
|
|
|
className,
|
2019-12-18 11:29:20 +00:00
|
|
|
value,
|
|
|
|
currency,
|
|
|
|
onValueChange,
|
|
|
|
...props
|
|
|
|
} ) => {
|
2020-05-01 09:59:27 +00:00
|
|
|
if ( value === '-' ) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
2019-12-18 11:29:20 +00:00
|
|
|
const priceValue = value / 10 ** currency.minorUnit;
|
|
|
|
|
2020-05-01 09:59:27 +00:00
|
|
|
if ( ! Number.isFinite( priceValue ) ) {
|
2019-12-18 11:29:20 +00:00
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
2020-01-14 20:52:42 +00:00
|
|
|
const classes = classNames( 'wc-block-formatted-money-amount', className );
|
2019-12-18 11:29:20 +00:00
|
|
|
const numberFormatProps = {
|
|
|
|
displayType: 'text',
|
|
|
|
...props,
|
|
|
|
...currencyToNumberFormat( currency ),
|
|
|
|
value: undefined,
|
|
|
|
currency: undefined,
|
|
|
|
onValueChange: undefined,
|
|
|
|
};
|
|
|
|
|
|
|
|
// Wrapper for NumberFormat onValueChange which handles subunit conversion.
|
|
|
|
const onValueChangeWrapper = onValueChange
|
|
|
|
? ( values ) => {
|
|
|
|
const minorUnitValue = values.value * 10 ** currency.minorUnit;
|
|
|
|
onValueChange( minorUnitValue );
|
|
|
|
}
|
|
|
|
: () => {};
|
|
|
|
|
|
|
|
return (
|
|
|
|
<NumberFormat
|
2020-01-14 20:52:42 +00:00
|
|
|
className={ classes }
|
2019-12-18 11:29:20 +00:00
|
|
|
{ ...numberFormatProps }
|
|
|
|
value={ priceValue }
|
|
|
|
onValueChange={ onValueChangeWrapper }
|
|
|
|
/>
|
|
|
|
);
|
|
|
|
};
|
|
|
|
|
|
|
|
export default FormattedMonetaryAmount;
|