1import React, { useCallback } from 'react';
2import { StandardEditorProps, StringFieldConfigSettings } from '@grafana/data';
3import { Input } from '../Input/Input';
4import { TextArea } from '../TextArea/TextArea';
5
6export const StringValueEditor: React.FC<StandardEditorProps<string, StringFieldConfigSettings>> = ({
7  value,
8  onChange,
9  item,
10}) => {
11  const Component = item.settings?.useTextarea ? TextArea : Input;
12
13  const onValueChange = useCallback(
14    (e: React.SyntheticEvent) => {
15      let nextValue = value ?? '';
16      if (e.hasOwnProperty('key')) {
17        // handling keyboard event
18        const evt = e as React.KeyboardEvent<HTMLInputElement>;
19        if (evt.key === 'Enter' && !item.settings?.useTextarea) {
20          nextValue = evt.currentTarget.value.trim();
21        }
22      } else {
23        // handling form event
24        const evt = e as React.FormEvent<HTMLInputElement>;
25        nextValue = evt.currentTarget.value.trim();
26      }
27      if (nextValue === value) {
28        return; // no change
29      }
30      onChange(nextValue === '' ? undefined : nextValue);
31    },
32    [value, item.settings?.useTextarea, onChange]
33  );
34
35  return (
36    <Component
37      placeholder={item.settings?.placeholder}
38      defaultValue={value || ''}
39      rows={(item.settings?.useTextarea && item.settings.rows) || 5}
40      onBlur={onValueChange}
41      onKeyDown={onValueChange}
42    />
43  );
44};
45