InputQueryEditor.tsx 2.6 KB

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