LokiQueryFieldForm.tsx 6.2 KB

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