InputQueryEditor.tsx 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. // Libraries
  2. import React, { PureComponent } from 'react';
  3. // Types
  4. import { InputDatasource, describeDataFrame } from './InputDatasource';
  5. import { InputQuery, InputOptions } from './types';
  6. import { FormLabel, Select, QueryEditorProps, TableInputCSV } from '@grafana/ui';
  7. import { DataFrame, toCSV, SelectableValue } from '@grafana/data';
  8. type Props = QueryEditorProps<InputDatasource, InputQuery, InputOptions>;
  9. const options = [
  10. { value: 'panel', label: 'Panel', description: 'Save data in the panel configuration.' },
  11. { value: 'shared', label: 'Shared', description: 'Save data in the shared datasource object.' },
  12. ];
  13. interface State {
  14. text: string;
  15. }
  16. export class InputQueryEditor extends PureComponent<Props, State> {
  17. state = {
  18. text: '',
  19. };
  20. onComponentDidMount() {
  21. const { query } = this.props;
  22. const text = query.data ? toCSV(query.data) : '';
  23. this.setState({ text });
  24. }
  25. onSourceChange = (item: SelectableValue<string>) => {
  26. const { datasource, query, onChange, onRunQuery } = this.props;
  27. let data: DataFrame[] | undefined = undefined;
  28. if (item.value === 'panel') {
  29. if (query.data) {
  30. return;
  31. }
  32. data = [...datasource.data];
  33. if (!data) {
  34. data = [
  35. {
  36. fields: [],
  37. rows: [],
  38. },
  39. ];
  40. }
  41. this.setState({ text: toCSV(data) });
  42. }
  43. onChange({ ...query, data });
  44. onRunQuery();
  45. };
  46. onSeriesParsed = (data: DataFrame[], text: string) => {
  47. const { query, onChange, onRunQuery } = this.props;
  48. this.setState({ text });
  49. if (!data) {
  50. data = [
  51. {
  52. fields: [],
  53. rows: [],
  54. },
  55. ];
  56. }
  57. onChange({ ...query, data });
  58. onRunQuery();
  59. };
  60. render() {
  61. const { datasource, query } = this.props;
  62. const { id, name } = datasource;
  63. const { text } = this.state;
  64. const selected = query.data ? options[0] : options[1];
  65. return (
  66. <div>
  67. <div className="gf-form">
  68. <FormLabel width={4}>Data</FormLabel>
  69. <Select width={6} options={options} value={selected} onChange={this.onSourceChange} />
  70. <div className="btn btn-link">
  71. {query.data ? (
  72. describeDataFrame(query.data)
  73. ) : (
  74. <a href={`datasources/edit/${id}/`}>
  75. {name}: {describeDataFrame(datasource.data)} &nbsp;&nbsp;
  76. <i className="fa fa-pencil-square-o" />
  77. </a>
  78. )}
  79. </div>
  80. </div>
  81. {query.data && <TableInputCSV text={text} onSeriesParsed={this.onSeriesParsed} width={'100%'} height={200} />}
  82. </div>
  83. );
  84. }
  85. }