Add conditional validation detection to int and float inputs
[arvados-workbench2.git] / src / views / run-process-panel / inputs / 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 { getInputLabel, FloatCommandInputParameter, isRequiredInput } from '~/models/workflow';
7 import { Field, WrappedFieldProps } from 'redux-form';
8 import { TextField } from '~/components/text-field/text-field';
9 import { isNumber } from '~/validators/is-number';
10 export interface FloatInputProps {
11     input: FloatCommandInputParameter;
12 }
13 export const FloatInput = ({ input }: FloatInputProps) =>
14     <Field
15         name={input.id}
16         label={getInputLabel(input)}
17         component={DecimalInput}
18         parse={parseFloat}
19         format={value => isNaN(value) ? '' : JSON.stringify(value)}
20         validate={[
21             isRequiredInput(input)
22                 ? isNumber
23                 : () => undefined,]} />;
24
25 class DecimalInput extends React.Component<WrappedFieldProps & { label?: string }> {
26     state = {
27         endsWithDecimalSeparator: false,
28     };
29
30     handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
31         const [base, fraction] = event.target.value.split('.');
32         this.setState({ endsWithDecimalSeparator: fraction === '' });
33         this.props.input.onChange(event);
34     }
35
36     render() {
37         const props = {
38             ...this.props,
39             input: {
40                 ...this.props.input,
41                 value: this.props.input.value + (this.state.endsWithDecimalSeparator ? '.' : ''),
42                 onChange: this.handleChange,
43             },
44         };
45         return <TextField {...props} />;
46     }
47 }