PromQueryBuilderHints.tsx 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import { css } from '@emotion/css';
  2. import React, { useState, useEffect } from 'react';
  3. import { GrafanaTheme2, PanelData, QueryHint } from '@grafana/data';
  4. import { Button, Tooltip, useStyles2 } from '@grafana/ui';
  5. import { PrometheusDatasource } from '../../datasource';
  6. import { promQueryModeller } from '../PromQueryModeller';
  7. import { buildVisualQueryFromString } from '../parsing';
  8. import { PromVisualQuery } from '../types';
  9. export interface Props {
  10. query: PromVisualQuery;
  11. datasource: PrometheusDatasource;
  12. onChange: (update: PromVisualQuery) => void;
  13. data?: PanelData;
  14. }
  15. export const PromQueryBuilderHints = React.memo<Props>(({ datasource, query, onChange, data }) => {
  16. const [hints, setHints] = useState<QueryHint[]>([]);
  17. const styles = useStyles2(getStyles);
  18. useEffect(() => {
  19. const promQuery = { expr: promQueryModeller.renderQuery(query), refId: '' };
  20. // For now show only actionable hints
  21. const hints = datasource.getQueryHints(promQuery, data?.series || []).filter((hint) => hint.fix?.action);
  22. setHints(hints);
  23. }, [datasource, query, onChange, data, styles.hint]);
  24. return (
  25. <>
  26. {hints.length > 0 && (
  27. <div className={styles.container}>
  28. {hints.map((hint) => {
  29. return (
  30. <Tooltip content={`${hint.label} ${hint.fix?.label}`} key={hint.type}>
  31. <Button
  32. onClick={() => {
  33. const promQuery = { expr: promQueryModeller.renderQuery(query), refId: '' };
  34. const newPromQuery = datasource.modifyQuery(promQuery, hint!.fix!.action);
  35. const visualQuery = buildVisualQueryFromString(newPromQuery.expr);
  36. return onChange(visualQuery.query);
  37. }}
  38. fill="outline"
  39. size="sm"
  40. className={styles.hint}
  41. >
  42. {'hint: ' + hint.fix?.action?.type.toLowerCase().replace('_', ' ') + '()'}
  43. </Button>
  44. </Tooltip>
  45. );
  46. })}
  47. </div>
  48. )}
  49. </>
  50. );
  51. });
  52. PromQueryBuilderHints.displayName = 'PromQueryBuilderHints';
  53. const getStyles = (theme: GrafanaTheme2) => {
  54. return {
  55. container: css`
  56. display: flex;
  57. margin-bottom: ${theme.spacing(1)};
  58. align-items: center;
  59. `,
  60. hint: css`
  61. margin-right: ${theme.spacing(1)};
  62. `,
  63. };
  64. };