1import React, { PureComponent } from 'react';
2import { connect, ConnectedProps } from 'react-redux';
3import { Alert, InlineFieldRow, VerticalGroup } from '@grafana/ui';
4import { DataSourceRef, SelectableValue } from '@grafana/data';
5
6import { AdHocVariableModel } from '../types';
7import { VariableEditorProps } from '../editor/types';
8import { VariableEditorState } from '../editor/reducer';
9import { AdHocVariableEditorState } from './reducer';
10import { changeVariableDatasource, initAdHocVariableEditor } from './actions';
11import { StoreState } from 'app/types';
12import { VariableSectionHeader } from '../editor/VariableSectionHeader';
13import { VariableSelectField } from '../editor/VariableSelectField';
14
15const mapStateToProps = (state: StoreState) => ({
16  editor: state.templating.editor as VariableEditorState<AdHocVariableEditorState>,
17});
18
19const mapDispatchToProps = {
20  initAdHocVariableEditor,
21  changeVariableDatasource,
22};
23
24const connector = connect(mapStateToProps, mapDispatchToProps);
25
26export interface OwnProps extends VariableEditorProps<AdHocVariableModel> {}
27
28type Props = OwnProps & ConnectedProps<typeof connector>;
29
30export class AdHocVariableEditorUnConnected extends PureComponent<Props> {
31  componentDidMount() {
32    this.props.initAdHocVariableEditor();
33  }
34
35  onDatasourceChanged = (option: SelectableValue<DataSourceRef>) => {
36    this.props.changeVariableDatasource(option.value);
37  };
38
39  render() {
40    const { variable, editor } = this.props;
41    const dataSources = editor.extended?.dataSources ?? [];
42    const infoText = editor.extended?.infoText ?? null;
43    const options = dataSources.map((ds) => ({ label: ds.text, value: ds.value }));
44    const value = options.find((o) => o.value?.uid === variable.datasource?.uid) ?? options[0];
45
46    return (
47      <VerticalGroup spacing="xs">
48        <VariableSectionHeader name="Options" />
49        <VerticalGroup spacing="sm">
50          <InlineFieldRow>
51            <VariableSelectField
52              name="Data source"
53              value={value}
54              options={options}
55              onChange={this.onDatasourceChanged}
56              labelWidth={10}
57            />
58          </InlineFieldRow>
59          {infoText ? <Alert title={infoText} severity="info" /> : null}
60        </VerticalGroup>
61      </VerticalGroup>
62    );
63  }
64}
65
66export const AdHocVariableEditor = connector(AdHocVariableEditorUnConnected);
67