grafana/public/app/plugins/datasource/stackdriver/components/StackdriverPicker.tsx

98 lines
2.4 KiB
TypeScript
Raw Normal View History

2018-12-18 04:25:13 -06:00
import React from 'react';
import _ from 'lodash';
import Select from 'app/core/components/Select/Select';
export interface Props {
onChange: (value: string) => void;
options: any[];
2018-12-19 14:14:55 -06:00
isSearchable: boolean;
2018-12-18 04:25:13 -06:00
selected: string;
placeholder?: string;
className?: string;
groupName?: string;
templateVariables?: any[];
2018-12-18 04:25:13 -06:00
}
interface State {
options: any[];
}
export class StackdriverPicker extends React.Component<Props, State> {
static defaultProps = {
templateVariables: [],
options: [],
groupName: 'Options',
};
2018-12-18 04:25:13 -06:00
constructor(props) {
super(props);
this.state = { options: [] };
2018-12-18 04:25:13 -06:00
}
componentDidMount() {
this.setState({ options: this.buildOptions(this.props) });
2018-12-18 04:25:13 -06:00
}
2018-12-18 09:09:32 -06:00
componentWillReceiveProps(nextProps: Props) {
if (nextProps.options.length > 0 || nextProps.templateVariables.length) {
this.setState({ options: this.buildOptions(nextProps) });
}
}
2018-12-18 09:09:32 -06:00
shouldComponentUpdate(nextProps: Props) {
2018-12-18 09:56:16 -06:00
const nextOptions = this.buildOptions(nextProps);
return nextProps.selected !== this.props.selected || !_.isEqual(nextOptions, this.state.options);
}
buildOptions({ templateVariables = [], groupName = '', options }) {
return templateVariables.length > 0
? [
this.getTemplateVariablesGroup(),
{
label: groupName,
expanded: true,
options,
},
]
: options;
}
getTemplateVariablesGroup() {
return {
label: 'Template Variables',
options: this.props.templateVariables.map(v => ({
label: `$${v.name}`,
value: `$${v.name}`,
})),
};
}
getSelectedOption() {
const { options } = this.state;
const allOptions = options.every(o => o.options) ? _.flatten(options.map(o => o.options)) : options;
return allOptions.find(option => option.value === this.props.selected);
}
2018-12-18 04:25:13 -06:00
render() {
2018-12-19 14:14:55 -06:00
const { placeholder, className, isSearchable, onChange } = this.props;
const { options } = this.state;
const selectedOption = this.getSelectedOption();
2018-12-18 04:25:13 -06:00
return (
<Select
className={className}
isMulti={false}
isClearable={false}
backspaceRemovesValue={false}
onChange={item => onChange(item.value)}
2018-12-18 04:25:13 -06:00
options={options}
2018-12-19 14:14:55 -06:00
isSearchable={isSearchable}
2018-12-18 04:25:13 -06:00
maxMenuHeight={500}
placeholder={placeholder}
noOptionsMessage={() => 'No options found'}
value={selectedOption}
/>
);
}
}