16e18cb1451f143f5267281266ae1d4a7278de9a
[arvados-workbench2.git] / src / components / float-input / float-input.tsx
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import * as React from 'react';
6 import { Input } from '@material-ui/core';
7 import { InputProps } from '@material-ui/core/Input';
8
9 export class FloatInput extends React.Component<InputProps> {
10     state = {
11         endsWithDecimalSeparator: false,
12     };
13
14     handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
15         const { onChange = () => { return; } } = this.props;
16         const [, fraction] = event.target.value.split('.');
17         this.setState({ endsWithDecimalSeparator: fraction === '' });
18         const parsedValue = parseFloat(event.target.value).toString();
19         event.target.value = parsedValue;
20         onChange(event);
21     }
22
23     render() {
24         const parsedValue = parseFloat(typeof this.props.value === 'string' ? this.props.value : '');
25         const value = isNaN(parsedValue) ? '' : parsedValue.toString();
26         const props = {
27             ...this.props,
28             value: value + (this.state.endsWithDecimalSeparator ? '.' : ''),
29             onChange: this.handleChange,
30         };
31         return <Input {...props} />;
32     }
33 }