hooks.ts 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import { useMemo } from 'react';
  2. import useAsync from 'react-use/lib/useAsync';
  3. import { DataQueryError, DataSourceApi, PanelData, PanelPlugin } from '@grafana/data';
  4. import { getDataSourceSrv } from '@grafana/runtime';
  5. import { DashboardModel, PanelModel } from 'app/features/dashboard/state';
  6. import { InspectTab } from 'app/features/inspector/types';
  7. import { supportsDataQuery } from '../PanelEditor/utils';
  8. import { PanelInspectActionSupplier } from './PanelInspectActions';
  9. /**
  10. * Given PanelData return first data source supporting metadata inspector
  11. */
  12. export const useDatasourceMetadata = (data?: PanelData) => {
  13. const state = useAsync(async () => {
  14. const targets = data?.request?.targets || [];
  15. if (data && data.series && targets.length) {
  16. for (const frame of data.series) {
  17. if (frame.meta && frame.meta.custom) {
  18. // get data source from first query
  19. const dataSource = await getDataSourceSrv().get(targets[0].datasource);
  20. if (dataSource && dataSource.components?.MetadataInspector) {
  21. return dataSource;
  22. }
  23. }
  24. }
  25. }
  26. return undefined;
  27. }, [data]);
  28. return state.value;
  29. };
  30. /**
  31. * Configures tabs for PanelInspector
  32. */
  33. export const useInspectTabs = (
  34. panel: PanelModel,
  35. dashboard: DashboardModel,
  36. plugin: PanelPlugin | undefined | null,
  37. error?: DataQueryError,
  38. metaDs?: DataSourceApi
  39. ) => {
  40. return useMemo(() => {
  41. const tabs = [];
  42. if (supportsDataQuery(plugin)) {
  43. tabs.push({ label: 'Data', value: InspectTab.Data });
  44. tabs.push({ label: 'Stats', value: InspectTab.Stats });
  45. }
  46. if (metaDs) {
  47. tabs.push({ label: 'Meta Data', value: InspectTab.Meta });
  48. }
  49. tabs.push({ label: 'JSON', value: InspectTab.JSON });
  50. if (error && error.message) {
  51. tabs.push({ label: 'Error', value: InspectTab.Error });
  52. }
  53. // This is a quick internal hack to allow custom actions in inspect
  54. // For 8.1, something like this should be exposed through grafana/runtime
  55. const supplier = (window as any).grafanaPanelInspectActionSupplier as PanelInspectActionSupplier;
  56. if (supplier && supplier.getActions(panel)) {
  57. tabs.push({ label: 'Actions', value: InspectTab.Actions });
  58. }
  59. if (dashboard.meta.canEdit && supportsDataQuery(plugin)) {
  60. tabs.push({ label: 'Query', value: InspectTab.Query });
  61. }
  62. return tabs;
  63. }, [panel, plugin, metaDs, dashboard, error]);
  64. };