|
1 |
| -import { PanelProps } from '@grafana/data'; |
| 1 | +import { AppEvents, PanelProps } from '@grafana/data'; |
| 2 | +import { getBackendSrv, getDataSourceSrv, SystemJS } from '@grafana/runtime'; |
2 | 3 | import { Button, HorizontalGroup, VerticalGroup } from '@grafana/ui';
|
3 | 4 | import React from 'react';
|
4 | 5 | import { ButtonOptions, Options } from 'types';
|
5 | 6 |
|
6 | 7 | interface Props extends PanelProps<Options> {}
|
7 | 8 |
|
8 |
| -const Buttons: React.FC<Options> = ({ buttons }) => { |
9 |
| - return ( |
10 |
| - <React.Fragment> |
11 |
| - {buttons.map((b: ButtonOptions, index: number) => ( |
12 |
| - <Button key={index} variant={b.variant}> |
13 |
| - {b.text || 'Button'} |
14 |
| - </Button> |
15 |
| - ))} |
16 |
| - </React.Fragment> |
17 |
| - ); |
18 |
| -}; |
19 |
| - |
20 | 9 | export const ButtonPanel: React.FC<Props> = ({ options }) => {
|
| 10 | + const renderButtons = (buttons: ButtonOptions[]) => { |
| 11 | + return buttons.map((b: ButtonOptions, index: number) => ( |
| 12 | + <Button |
| 13 | + key={index} |
| 14 | + variant={b.variant} |
| 15 | + onClick={async () => { |
| 16 | + const payload = JSON.parse(b.query || ''); |
| 17 | + const ds = await getDataSourceSrv().get(b.datasource); |
| 18 | + try { |
| 19 | + const resp = await getBackendSrv().datasourceRequest({ |
| 20 | + method: 'POST', |
| 21 | + url: 'api/tsdb/query', |
| 22 | + data: { |
| 23 | + queries: [ |
| 24 | + { |
| 25 | + datasourceId: ds.id, |
| 26 | + refId: '1', |
| 27 | + ...payload, |
| 28 | + }, |
| 29 | + ], |
| 30 | + }, |
| 31 | + }); |
| 32 | + SystemJS.load('app/core/app_events').then((appEvents: any) => { |
| 33 | + appEvents.emit(AppEvents.alertSuccess, [ |
| 34 | + b.text + ': ' + resp.status + ' (' + resp.statusText + ')', |
| 35 | + ]); |
| 36 | + }); |
| 37 | + } catch (error) { |
| 38 | + SystemJS.load('app/core/app_events').then((appEvents: any) => { |
| 39 | + appEvents.emit(AppEvents.alertError, [ |
| 40 | + b.text + ': ' + error.status + ' (' + error.statusText + ')', |
| 41 | + error.data.message, |
| 42 | + ]); |
| 43 | + }); |
| 44 | + } |
| 45 | + }} |
| 46 | + > |
| 47 | + {b.text || 'Button'} |
| 48 | + </Button> |
| 49 | + )); |
| 50 | + }; |
| 51 | + |
21 | 52 | return (
|
22 | 53 | (options.orientation === 'vertical' && (
|
23 | 54 | <VerticalGroup justify="center" align="center">
|
24 |
| - <Buttons {...options} /> |
| 55 | + {renderButtons(options.buttons)} |
25 | 56 | </VerticalGroup>
|
26 | 57 | )) || (
|
27 | 58 | <HorizontalGroup justify="center" align="center">
|
28 |
| - <Buttons {...options} /> |
| 59 | + {renderButtons(options.buttons)} |
29 | 60 | </HorizontalGroup>
|
30 | 61 | )
|
31 | 62 | );
|
|
0 commit comments