All files / src/form/fields SeriesInput.tsx

86.66% Statements 13/15
57.14% Branches 8/14
100% Functions 5/5
86.66% Lines 13/15

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53                      68x 8x 4x   4x     8x     16x             16x     4x 4x 4x 4x           4x 2x                      
import React, { ReactElement } from "react";
import { InputNumber, Timeline } from "antd";
 
interface SeriesInputProps {
  labels: string[];
  values: number[] | string[];
  onChange: (index: string, value: number) => void;
  labelSuffix?: string;
  valueSuffix?: string;
}
 
const SeriesInput = (props: SeriesInputProps): ReactElement => {
  const parseFunc = (value: string | undefined): number => {
    const strVal: string = (value == null) ?
      '' : value.replace(props.labelSuffix || '', '');
    return parseFloat(strVal);
  };
 
  return (
    <Timeline mode={"left"}>
      {props.labels.map((label, index) => (
        <Timeline.Item label={label + props.labelSuffix || ''}
          key={label}>
          <InputNumber
            value={Number(props.values[index])}
            size={"small"}
            min={0}
            max={100}
            formatter={value => `${value}${props.valueSuffix || ''}`}
            parser={parseFunc}
            onInput={value => {
              let numVal = NaN;
              Eif (typeof value === "string") {
                try {
                  numVal = Number.parseFloat(value);
                } catch (err) {
                  console.error(`Failed to convert ${value} to a number`);
                  return;
                }
              }
              if (!isNaN(numVal)) {
                props.onChange(props.labels[index], numVal || 0);
              }
            }}
          />
        </Timeline.Item>
      ))}
    </Timeline>
  );
};
 
export default SeriesInput;