ElasticsearchQueryField.tsx 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import _ from 'lodash';
  2. import React from 'react';
  3. // @ts-ignore
  4. import PluginPrism from 'slate-prism';
  5. // @ts-ignore
  6. import Prism from 'prismjs';
  7. // dom also includes Element polyfills
  8. import QueryField from 'app/features/explore/QueryField';
  9. import { ExploreQueryFieldProps } from '@grafana/ui';
  10. import { ElasticDatasource } from '../datasource';
  11. import { ElasticsearchOptions, ElasticsearchQuery } from '../types';
  12. interface Props extends ExploreQueryFieldProps<ElasticDatasource, ElasticsearchQuery, ElasticsearchOptions> {}
  13. interface State {
  14. syntaxLoaded: boolean;
  15. }
  16. class ElasticsearchQueryField extends React.PureComponent<Props, State> {
  17. plugins: any[];
  18. constructor(props: Props, context: React.Context<any>) {
  19. super(props, context);
  20. this.plugins = [
  21. PluginPrism({
  22. onlyIn: (node: any) => node.type === 'code_block',
  23. getSyntax: (node: any) => 'lucene',
  24. }),
  25. ];
  26. this.state = {
  27. syntaxLoaded: false,
  28. };
  29. }
  30. componentDidMount() {
  31. if (!this.props.query.isLogsQuery) {
  32. this.onChangeQuery('', true);
  33. }
  34. }
  35. componentWillUnmount() {}
  36. componentDidUpdate(prevProps: Props) {
  37. // if query changed from the outside (i.e. cleared via explore toolbar)
  38. if (!this.props.query.isLogsQuery) {
  39. this.onChangeQuery('', true);
  40. }
  41. }
  42. onChangeQuery = (value: string, override?: boolean) => {
  43. // Send text change to parent
  44. const { query, onChange, onRunQuery } = this.props;
  45. if (onChange) {
  46. const nextQuery: ElasticsearchQuery = { ...query, query: value, isLogsQuery: true };
  47. onChange(nextQuery);
  48. if (override && onRunQuery) {
  49. onRunQuery();
  50. }
  51. }
  52. };
  53. render() {
  54. const { queryResponse, query } = this.props;
  55. const { syntaxLoaded } = this.state;
  56. return (
  57. <>
  58. <div className="gf-form-inline gf-form-inline--nowrap">
  59. <div className="gf-form gf-form--grow flex-shrink-1">
  60. <QueryField
  61. additionalPlugins={this.plugins}
  62. initialQuery={query.query}
  63. onChange={this.onChangeQuery}
  64. onRunQuery={this.props.onRunQuery}
  65. placeholder="Enter a Lucene query"
  66. portalOrigin="elasticsearch"
  67. syntaxLoaded={syntaxLoaded}
  68. />
  69. </div>
  70. </div>
  71. {queryResponse && queryResponse.error ? (
  72. <div className="prom-query-field-info text-error">{queryResponse.error.message}</div>
  73. ) : null}
  74. </>
  75. );
  76. }
  77. }
  78. export default ElasticsearchQueryField;