1import React, { useCallback } from 'react';
2import {
3  FieldConfigEditorProps,
4  toIntegerOrUndefined,
5  toFloatOrUndefined,
6  NumberFieldConfigSettings,
7} from '@grafana/data';
8import { Input } from '../Input/Input';
9
10export const NumberValueEditor: React.FC<FieldConfigEditorProps<number, NumberFieldConfigSettings>> = ({
11  value,
12  onChange,
13  item,
14}) => {
15  const { settings } = item;
16
17  const onValueChange = useCallback(
18    (e: React.SyntheticEvent) => {
19      if (e.hasOwnProperty('key')) {
20        // handling keyboard event
21        const evt = e as React.KeyboardEvent<HTMLInputElement>;
22        if (evt.key === 'Enter') {
23          onChange(
24            settings?.integer
25              ? toIntegerOrUndefined(evt.currentTarget.value)
26              : toFloatOrUndefined(evt.currentTarget.value)
27          );
28        }
29      } else {
30        // handling form event
31        const evt = e as React.FormEvent<HTMLInputElement>;
32        onChange(
33          settings?.integer
34            ? toIntegerOrUndefined(evt.currentTarget.value)
35            : toFloatOrUndefined(evt.currentTarget.value)
36        );
37      }
38    },
39    [onChange, settings?.integer]
40  );
41
42  const defaultValue = value === undefined || value === null || isNaN(value) ? '' : value.toString();
43  return (
44    <Input
45      defaultValue={defaultValue}
46      min={settings?.min}
47      max={settings?.max}
48      type="number"
49      step={settings?.step}
50      placeholder={settings?.placeholder}
51      onBlur={onValueChange}
52      onKeyDown={onValueChange}
53    />
54  );
55};
56