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

provide currencyFormat for Plotly Dash #2932

Open
wants to merge 2 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
97 changes: 86 additions & 11 deletions components/dash-core-components/src/components/Input.react.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ const inputProps = [
'size',
'style',
'id',
'currencyFormat',
'currencySymbol',
];

/**
Expand All @@ -46,7 +48,10 @@ export default class Input extends PureComponent {

this.state = {
pendingEvent: undefined,
value: '',
value: '' | props.value,
displayValue: props.currencyFormat
? this.formatCurrency(props.value)
: props.value,
};

this.input = React.createRef();
Expand All @@ -58,6 +63,7 @@ export default class Input extends PureComponent {
this.debounceEvent = this.debounceEvent.bind(this);
this.setInputValue = this.setInputValue.bind(this);
this.setPropValue = this.setPropValue.bind(this);
this.handleInputChange = this.handleInputChange.bind(this);
}

UNSAFE_componentWillReceiveProps(nextProps) {
Expand Down Expand Up @@ -90,25 +96,58 @@ export default class Input extends PureComponent {
this.setState({value: this.props.value});
}
}
formatCurrency(value) {
if (isNaN(value) || value === '') {
return '';
}
const {currencySymbol} = this.props;

return `${currencySymbol}${Number(value).toLocaleString()}`;
Copy link
Contributor

Choose a reason for hiding this comment

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

are there cases where the currency symbol comes after the number? Or is that just odd English typography like 15¢ that isn't used for international currencies?

}
parseDisplayValue(value) {
if (!value) {
return '';
}
// Remove currency symbol and non-numeric characters
return Number(value.replace(/[^0-9.-]+/g, ''));
}
handleInputChange(event) {
const {value} = event.target;
const valueAsNumber = this.parseDisplayValue(value);
this.setState({
value: valueAsNumber,
displayValue: this.props.currencyFormat
? this.formatCurrency(valueAsNumber)
: valueAsNumber,
});
}

render() {
const valprops =
this.props.type === 'number' ? {} : {value: this.state.value};
const {loading_state} = this.props;
const {loading_state, currencyFormat} = this.props;
let valprops;
if (this.props.type === 'number' && !currencyFormat) {
valprops = { value: this.state.value }; // Always show the number
} else {
valprops = { value: this.state.displayValue }; // Use formatted display value for currency
}
let {className} = this.props;

const inputType = currencyFormat ? 'text' : 'number';

className = 'dash-input' + (className ? ` ${className}` : '');
return (
<input
type={inputType}
data-dash-is-loading={
(loading_state && loading_state.is_loading) || undefined
}
className={className}
ref={this.input}
onBlur={this.onBlur}
onChange={this.onChange}
onChange={this.handleInputChange}
onKeyPress={this.onKeyPress}
{...valprops}
{...pick(inputProps, this.props)}
{...pick(['type', 'name', 'id', 'placeholder'], inputProps)}
/>
);
}
Expand All @@ -119,7 +158,14 @@ export default class Input extends PureComponent {
value = convert(value);

if (!isEquivalent(base, value)) {
this.input.current.value = isNumeric(value) ? value : __value;
if (isNumeric(value)) {
const formattedValue = this.props.currencyFormat
? this.formatCurrency(value)
: value;
this.setState({displayValue: formattedValue}, () => {});
} else {
this.setState({displayValue: __value});
}
}
}

Expand All @@ -131,18 +177,22 @@ export default class Input extends PureComponent {
this.props.setProps({value});
}
}

onEvent() {
const {value} = this.input.current;
const valueAsNumber = convert(value);
const valueAsNumber = this.parseDisplayValue(value);

if (this.props.type === 'number') {
this.setPropValue(
this.props.value,
isNil(valueAsNumber) ? value : valueAsNumber
isNaN(valueAsNumber) ? value : valueAsNumber
);
} else {
this.props.setProps({value});
const formattedValue = this.props.currencyFormat
? this.formatCurrency(valueAsNumber)
: value;
this.props.setProps({value: formattedValue});
}

this.setState({pendingEvent: undefined});
}

Expand Down Expand Up @@ -207,6 +257,8 @@ Input.defaultProps = {
step: 'any',
persisted_props: ['value'],
persistence_type: 'local',
currencyFormat: false,
currencySymbol: '$',
};

Input.propTypes = {
Expand Down Expand Up @@ -239,6 +291,29 @@ Input.propTypes = {
*/
debounce: PropTypes.oneOfType([PropTypes.bool, PropTypes.number]),

/**
* If true and type is 'number', formats the input value as currency.
*/
currencyFormat: (props, propName, componentName) => {
if (props.currencyFormat && props.type !== 'number') {
return new Error(
`Invalid prop \`${propName}\` supplied to ` +
`\`${componentName}\`. \`${propName}\` can only be used when \`type\` is \`number\`.`
);
}
return null; // Ensure to return null if there’s no error
},

currencySymbol: (props, propName, componentName) => {
if (props.currencySymbol && props.type !== 'number') {
return new Error(
`Invalid prop \`${propName}\` supplied to ` +
`\`${componentName}\`. \`${propName}\` can only be used when \`type\` is \`number\`.`
);
}
return null; // Ensure to return null if there’s no error
},

/**
* A hint to the user of what can be entered in the control . The placeholder text must not contain carriage returns or line-feeds. Note: Do not use the placeholder attribute instead of a <label> element, their purposes are different. The <label> attribute describes the role of the form element (i.e. it indicates what kind of information is expected), and the placeholder attribute is a hint about the format that the content should take. There are cases in which the placeholder attribute is never displayed to the user, so the form must be understandable without it.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,3 +84,26 @@ def test_inni010_valid_numbers(dash_dcc, ninput_app):
dash_dcc.clear_input(elem)

assert dash_dcc.get_logs() == []


def test_currency_format(dash_dcc, ninput_app):
dash_dcc.start_server(ninput_app)
elem = dash_dcc.find_element("#input_currency")

elem.send_keys("1234.56")
elem.send_keys(Keys.TAB)

assert dash_dcc.wait_for_text_to_equal(
"#div_currency", "$1234.56"
), "the input value should be formatted with a currency symbol"

dash_dcc.clear_input(elem)

elem.send_keys("1000")
elem.send_keys(Keys.TAB)

assert dash_dcc.wait_for_text_to_equal(
"#div_currency", "$1000.00"
), "the input value should be formatted with a currency symbol"

assert dash_dcc.get_logs() == []