LokiQueryFieldForm.tsx 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. // Libraries
  2. import React from 'react';
  3. // @ts-ignore
  4. import Cascader from 'rc-cascader';
  5. import { SlatePrism } from '@grafana/ui';
  6. // Components
  7. import QueryField, { TypeaheadInput } from 'app/features/explore/QueryField';
  8. // Utils & Services
  9. // dom also includes Element polyfills
  10. import BracesPlugin from 'app/features/explore/slate-plugins/braces';
  11. import { Plugin, Node } from 'slate';
  12. // Types
  13. import { LokiQuery } from '../types';
  14. import { TypeaheadOutput } from 'app/types/explore';
  15. import { DataSourceApi, ExploreQueryFieldProps, DataSourceStatus, DOMUtil } from '@grafana/ui';
  16. import { AbsoluteTimeRange } from '@grafana/data';
  17. import { Grammar } from 'prismjs';
  18. import LokiLanguageProvider, { LokiHistoryItem } from '../language_provider';
  19. import { SuggestionsState } from 'app/features/explore/slate-plugins/suggestions';
  20. function getChooserText(hasSyntax: boolean, hasLogLabels: boolean, datasourceStatus: DataSourceStatus) {
  21. if (datasourceStatus === DataSourceStatus.Disconnected) {
  22. return '(Disconnected)';
  23. }
  24. if (!hasSyntax) {
  25. return 'Loading labels...';
  26. }
  27. if (!hasLogLabels) {
  28. return '(No labels found)';
  29. }
  30. return 'Log labels';
  31. }
  32. function willApplySuggestion(suggestion: string, { typeaheadContext, typeaheadText }: SuggestionsState): string {
  33. // Modify suggestion based on context
  34. switch (typeaheadContext) {
  35. case 'context-labels': {
  36. const nextChar = DOMUtil.getNextCharacter();
  37. if (!nextChar || nextChar === '}' || nextChar === ',') {
  38. suggestion += '=';
  39. }
  40. break;
  41. }
  42. case 'context-label-values': {
  43. // Always add quotes and remove existing ones instead
  44. if (!typeaheadText.match(/^(!?=~?"|")/)) {
  45. suggestion = `"${suggestion}`;
  46. }
  47. if (DOMUtil.getNextCharacter() !== '"') {
  48. suggestion = `${suggestion}"`;
  49. }
  50. break;
  51. }
  52. default:
  53. }
  54. return suggestion;
  55. }
  56. export interface CascaderOption {
  57. label: string;
  58. value: string;
  59. children?: CascaderOption[];
  60. disabled?: boolean;
  61. }
  62. export interface LokiQueryFieldFormProps extends ExploreQueryFieldProps<DataSourceApi<LokiQuery>, LokiQuery> {
  63. history: LokiHistoryItem[];
  64. syntax: Grammar;
  65. logLabelOptions: any[];
  66. syntaxLoaded: boolean;
  67. absoluteRange: AbsoluteTimeRange;
  68. onLoadOptions: (selectedOptions: CascaderOption[]) => void;
  69. onLabelsRefresh?: () => void;
  70. }
  71. export class LokiQueryFieldForm extends React.PureComponent<LokiQueryFieldFormProps> {
  72. plugins: Plugin[];
  73. modifiedSearch: string;
  74. modifiedQuery: string;
  75. constructor(props: LokiQueryFieldFormProps, context: React.Context<any>) {
  76. super(props, context);
  77. this.plugins = [
  78. BracesPlugin(),
  79. SlatePrism({
  80. onlyIn: (node: Node) => node.object === 'block' && node.type === 'code_block',
  81. getSyntax: (node: Node) => 'promql',
  82. }),
  83. ];
  84. }
  85. loadOptions = (selectedOptions: CascaderOption[]) => {
  86. this.props.onLoadOptions(selectedOptions);
  87. };
  88. onChangeLogLabels = (values: string[], selectedOptions: CascaderOption[]) => {
  89. if (selectedOptions.length === 2) {
  90. const key = selectedOptions[0].value;
  91. const value = selectedOptions[1].value;
  92. const query = `{${key}="${value}"}`;
  93. this.onChangeQuery(query, true);
  94. }
  95. };
  96. onChangeQuery = (value: string, override?: boolean) => {
  97. // Send text change to parent
  98. const { query, onChange, onRunQuery } = this.props;
  99. if (onChange) {
  100. const nextQuery = { ...query, expr: value };
  101. onChange(nextQuery);
  102. if (override && onRunQuery) {
  103. onRunQuery();
  104. }
  105. }
  106. };
  107. onTypeahead = async (typeahead: TypeaheadInput): Promise<TypeaheadOutput> => {
  108. const { datasource } = this.props;
  109. if (!datasource.languageProvider) {
  110. return { suggestions: [] };
  111. }
  112. const lokiLanguageProvider = datasource.languageProvider as LokiLanguageProvider;
  113. const { history, absoluteRange } = this.props;
  114. const { prefix, text, value, wrapperClasses, labelKey } = typeahead;
  115. const result = await lokiLanguageProvider.provideCompletionItems(
  116. { text, value, prefix, wrapperClasses, labelKey },
  117. { history, absoluteRange }
  118. );
  119. //console.log('handleTypeahead', wrapperClasses, text, prefix, nextChar, labelKey, result.context);
  120. return result;
  121. };
  122. render() {
  123. const {
  124. queryResponse,
  125. query,
  126. syntaxLoaded,
  127. logLabelOptions,
  128. onLoadOptions,
  129. onLabelsRefresh,
  130. datasource,
  131. datasourceStatus,
  132. } = this.props;
  133. const lokiLanguageProvider = datasource.languageProvider as LokiLanguageProvider;
  134. const cleanText = datasource.languageProvider ? lokiLanguageProvider.cleanText : undefined;
  135. const hasLogLabels = logLabelOptions && logLabelOptions.length > 0;
  136. const chooserText = getChooserText(syntaxLoaded, hasLogLabels, datasourceStatus);
  137. const buttonDisabled = !syntaxLoaded || datasourceStatus === DataSourceStatus.Disconnected;
  138. const showError = queryResponse && queryResponse.error && queryResponse.error.refId === query.refId;
  139. return (
  140. <>
  141. <div className="gf-form-inline">
  142. <div className="gf-form">
  143. <Cascader
  144. options={logLabelOptions}
  145. onChange={this.onChangeLogLabels}
  146. loadData={onLoadOptions}
  147. expandIcon={null}
  148. onPopupVisibleChange={(isVisible: boolean) => {
  149. if (isVisible && onLabelsRefresh) {
  150. onLabelsRefresh();
  151. }
  152. }}
  153. >
  154. <button className="gf-form-label gf-form-label--btn" disabled={buttonDisabled}>
  155. {chooserText} <i className="fa fa-caret-down" />
  156. </button>
  157. </Cascader>
  158. </div>
  159. <div className="gf-form gf-form--grow">
  160. <QueryField
  161. additionalPlugins={this.plugins}
  162. cleanText={cleanText}
  163. initialQuery={query.expr}
  164. onTypeahead={this.onTypeahead}
  165. onWillApplySuggestion={willApplySuggestion}
  166. onChange={this.onChangeQuery}
  167. onRunQuery={this.props.onRunQuery}
  168. placeholder="Enter a Loki query"
  169. portalOrigin="loki"
  170. syntaxLoaded={syntaxLoaded}
  171. />
  172. </div>
  173. </div>
  174. <div>
  175. {showError ? <div className="prom-query-field-info text-error">{queryResponse.error.message}</div> : null}
  176. </div>
  177. </>
  178. );
  179. }
  180. }