1import React, { useCallback, useState } from 'react';
2import { Input } from '@grafana/ui';
3
4import { Field } from '../Field';
5import { AzureQueryEditorFieldProps } from '../../types';
6import { setLegendAlias } from './setQueryValue';
7
8const LegendFormatField: React.FC<AzureQueryEditorFieldProps> = ({ onQueryChange, query }) => {
9  const [value, setValue] = useState<string>(query.azureMonitor?.alias ?? '');
10
11  // As calling onQueryChange initiates a the datasource refresh, we only want to call it once
12  // the field loses focus
13  const handleChange = useCallback((ev: React.FormEvent) => {
14    if (ev.target instanceof HTMLInputElement) {
15      setValue(ev.target.value);
16    }
17  }, []);
18
19  const handleBlur = useCallback(() => {
20    const newQuery = setLegendAlias(query, value);
21    onQueryChange(newQuery);
22  }, [onQueryChange, query, value]);
23
24  return (
25    <Field label="Legend format">
26      <Input
27        id="azure-monitor-metrics-legend-field"
28        placeholder="Alias patterns"
29        value={value}
30        onChange={handleChange}
31        onBlur={handleBlur}
32        width={38}
33      />
34    </Field>
35  );
36};
37
38export default LegendFormatField;
39