NewRuleFromPanelButton.tsx 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import React, { FC } from 'react';
  2. import { useSelector } from 'react-redux';
  3. import { useLocation } from 'react-router-dom';
  4. import { useAsync } from 'react-use';
  5. import { urlUtil } from '@grafana/data';
  6. import { Alert, Button, LinkButton } from '@grafana/ui';
  7. import { DashboardModel, PanelModel } from 'app/features/dashboard/state';
  8. import { StoreState } from 'app/types';
  9. import { panelToRuleFormValues } from '../../utils/rule-form';
  10. interface Props {
  11. panel: PanelModel;
  12. dashboard: DashboardModel;
  13. className?: string;
  14. }
  15. export const NewRuleFromPanelButton: FC<Props> = ({ dashboard, panel, className }) => {
  16. const templating = useSelector((state: StoreState) => {
  17. return state.templating;
  18. });
  19. const location = useLocation();
  20. const { loading, value: formValues } = useAsync(
  21. () => panelToRuleFormValues(panel, dashboard),
  22. // Templating variables are required to update formValues on each variable's change. It's used implicitly by the templating engine
  23. [panel, dashboard, templating]
  24. );
  25. if (loading) {
  26. return <Button disabled={true}>Create alert rule from this panel</Button>;
  27. }
  28. if (!formValues) {
  29. return (
  30. <Alert severity="info" title="No alerting capable query found">
  31. Cannot create alerts from this panel because no query to an alerting capable datasource is found.
  32. </Alert>
  33. );
  34. }
  35. const ruleFormUrl = urlUtil.renderUrl('alerting/new', {
  36. defaults: JSON.stringify(formValues),
  37. returnTo: location.pathname + location.search,
  38. });
  39. return (
  40. <LinkButton icon="bell" href={ruleFormUrl} className={className} data-testid="create-alert-rule-button">
  41. Create alert rule from this panel
  42. </LinkButton>
  43. );
  44. };