InputQueryEditor.tsx 2.6 KB

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