Expression.tsx 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import { css, cx } from '@emotion/css';
  2. import { LanguageMap, languages as prismLanguages } from 'prismjs';
  3. import React, { FC, useMemo } from 'react';
  4. import { GrafanaTheme } from '@grafana/data';
  5. import { Editor } from '@grafana/slate-react';
  6. import { makeValue, SlatePrism, useStyles } from '@grafana/ui';
  7. import LogqlSyntax from 'app/plugins/datasource/loki/syntax';
  8. import PromqlSyntax from 'app/plugins/datasource/prometheus/promql';
  9. import { RulesSource } from 'app/types/unified-alerting';
  10. import { DataSourceType, isCloudRulesSource } from '../utils/datasource';
  11. import { Well } from './Well';
  12. interface Props {
  13. expression: string;
  14. rulesSource: RulesSource;
  15. }
  16. export const HighlightedQuery: FC<{ language: 'promql' | 'logql'; expr: string }> = ({ language, expr }) => {
  17. const plugins = useMemo(
  18. () => [
  19. SlatePrism(
  20. {
  21. onlyIn: (node: any) => node.type === 'code_block',
  22. getSyntax: () => language,
  23. },
  24. { ...(prismLanguages as LanguageMap), [language]: language === 'logql' ? LogqlSyntax : PromqlSyntax }
  25. ),
  26. ],
  27. [language]
  28. );
  29. const slateValue = useMemo(() => makeValue(expr), [expr]);
  30. return <Editor plugins={plugins} value={slateValue} readOnly={true} />;
  31. };
  32. export const Expression: FC<Props> = ({ expression: query, rulesSource }) => {
  33. const styles = useStyles(getStyles);
  34. return (
  35. <Well className={cx(styles.well, 'slate-query-field')}>
  36. {isCloudRulesSource(rulesSource) ? (
  37. <HighlightedQuery expr={query} language={rulesSource.type === DataSourceType.Loki ? 'logql' : 'promql'} />
  38. ) : (
  39. query
  40. )}
  41. </Well>
  42. );
  43. };
  44. export const getStyles = (theme: GrafanaTheme) => ({
  45. well: css`
  46. font-family: ${theme.typography.fontFamily.monospace};
  47. `,
  48. });