Files
grafana/public/app/core/components/Select/MetricSelect.tsx

67 lines
1.9 KiB
TypeScript
Raw Normal View History

import React, { useMemo, useCallback, FC } from 'react';
2018-12-18 11:25:13 +01:00
import _ from 'lodash';
2018-12-19 21:34:13 +01:00
import { LegacyForms } from '@grafana/ui';
import { SelectableValue } from '@grafana/data';
2018-12-19 21:34:13 +01:00
import { Variable } from 'app/types/templates';
const { Select } = LegacyForms;
2018-12-18 11:25:13 +01:00
export interface Props {
onChange: (value: string | undefined) => void;
options: Array<SelectableValue<string>>;
2018-12-19 21:14:55 +01:00
isSearchable: boolean;
2018-12-19 21:19:43 +01:00
value: string;
2018-12-18 11:25:13 +01:00
placeholder?: string;
className?: string;
2018-12-19 21:34:13 +01:00
variables?: Variable[];
2018-12-18 11:25:13 +01:00
}
export const MetricSelect: FC<Props> = props => {
const { value, placeholder, className, isSearchable, onChange } = props;
const options = useSelectOptions(props);
const selected = useSelectedOption(options, value);
const onChangeValue = useCallback((selectable: SelectableValue<string>) => onChange(selectable.value), [onChange]);
2018-12-18 11:25:13 +01:00
return (
<Select
className={className}
isMulti={false}
isClearable={false}
backspaceRemovesValue={false}
onChange={onChangeValue}
options={options}
isSearchable={isSearchable}
maxMenuHeight={500}
placeholder={placeholder}
noOptionsMessage={() => 'No options found'}
value={selected}
/>
);
};
2018-12-18 11:25:13 +01:00
const useSelectOptions = ({ variables = [], options }: Props): Array<SelectableValue<string>> => {
return useMemo(() => {
if (!Array.isArray(variables) || variables.length === 0) {
return options;
}
return [
{
label: 'Template Variables',
options: variables.map(({ name }) => ({
label: `$${name}`,
value: `$${name}`,
})),
},
...options,
];
}, [variables, options]);
};
const useSelectedOption = (options: Array<SelectableValue<string>>, value: string): SelectableValue<string> => {
return useMemo(() => {
const allOptions = options.every(o => o.options) ? _.flatten(options.map(o => o.options)) : options;
return allOptions.find(option => option.value === value);
}, [options, value]);
};