RawFrameEditor.tsx 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import { isArray } from 'lodash';
  2. import React, { useState } from 'react';
  3. import { dataFrameToJSON, toDataFrame, toDataFrameDTO } from '@grafana/data';
  4. import { toDataQueryResponse } from '@grafana/runtime';
  5. import { Alert, CodeEditor } from '@grafana/ui';
  6. import { EditorProps } from '../QueryEditor';
  7. export const RawFrameEditor = ({ onChange, query }: EditorProps) => {
  8. const [error, setError] = useState<string>();
  9. const [warning, setWarning] = useState<string>();
  10. const onSaveFrames = (rawFrameContent: string) => {
  11. try {
  12. const json = JSON.parse(rawFrameContent);
  13. if (isArray(json)) {
  14. setError(undefined);
  15. setWarning(undefined);
  16. onChange({ ...query, rawFrameContent });
  17. return;
  18. }
  19. let data: any = undefined;
  20. // Copy paste from panel json
  21. if (isArray(json.series) && json.state) {
  22. data = json.series.map((v: any) => toDataFrameDTO(toDataFrame(v)));
  23. } else {
  24. // Chek if it is a copy of the raw resuls
  25. const v = toDataQueryResponse({ data: json });
  26. if (v.data?.length && !v.error) {
  27. data = v.data.map((f) => dataFrameToJSON(f));
  28. }
  29. }
  30. if (data) {
  31. console.log('Original', json);
  32. console.log('Save', data);
  33. setError(undefined);
  34. setWarning('Converted to direct frame result');
  35. onChange({ ...query, rawFrameContent: JSON.stringify(data, null, 2) });
  36. return;
  37. }
  38. setError('Unable to read dataframes in text');
  39. } catch (e) {
  40. console.log('Error parsing json', e);
  41. setError('Enter JSON array of data frames (or raw query results body)');
  42. setWarning(undefined);
  43. }
  44. };
  45. return (
  46. <>
  47. {error && <Alert title={error} severity="error" />}
  48. {warning && <Alert title={warning} severity="warning" />}
  49. <CodeEditor
  50. height={300}
  51. language="json"
  52. value={query.rawFrameContent ?? '[]'}
  53. onBlur={onSaveFrames}
  54. onSave={onSaveFrames}
  55. showMiniMap={true}
  56. showLineNumbers={true}
  57. />
  58. </>
  59. );
  60. };