LokiQueryFieldForm.tsx 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  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. import RunnerPlugin from 'app/features/explore/slate-plugins/runner';
  14. // Types
  15. import { LokiQuery } from '../types';
  16. import { TypeaheadOutput, HistoryItem } from 'app/types/explore';
  17. import { ExploreDataSourceApi, ExploreQueryFieldProps, DataSourceStatus } from '@grafana/ui';
  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<ExploreDataSourceApi<LokiQuery>, LokiQuery> {
  61. history: HistoryItem[];
  62. syntax: any;
  63. logLabelOptions: any[];
  64. syntaxLoaded: any;
  65. onLoadOptions: (selectedOptions: CascaderOption[]) => void;
  66. onLabelsRefresh?: () => void;
  67. }
  68. export class LokiQueryFieldForm extends React.PureComponent<LokiQueryFieldFormProps> {
  69. plugins: any[];
  70. pluginsSearch: 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. RunnerPlugin({ handler: props.onRunQuery }),
  78. PluginPrism({
  79. onlyIn: (node: any) => node.type === 'code_block',
  80. getSyntax: (node: any) => 'promql',
  81. }),
  82. ];
  83. this.pluginsSearch = [RunnerPlugin({ handler: props.onRunQuery })];
  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 = (typeahead: TypeaheadInput): TypeaheadOutput => {
  108. const { datasource } = this.props;
  109. if (!datasource.languageProvider) {
  110. return { suggestions: [] };
  111. }
  112. const { history } = this.props;
  113. const { prefix, text, value, wrapperNode } = typeahead;
  114. // Get DOM-dependent context
  115. const wrapperClasses = Array.from(wrapperNode.classList);
  116. const labelKeyNode = getPreviousCousin(wrapperNode, '.attr-name');
  117. const labelKey = labelKeyNode && labelKeyNode.textContent;
  118. const nextChar = getNextCharacter();
  119. const result = datasource.languageProvider.provideCompletionItems(
  120. { text, value, prefix, wrapperClasses, labelKey },
  121. { history }
  122. );
  123. console.log('handleTypeahead', wrapperClasses, text, prefix, nextChar, labelKey, result.context);
  124. return result;
  125. };
  126. render() {
  127. const {
  128. queryResponse,
  129. query,
  130. syntaxLoaded,
  131. logLabelOptions,
  132. onLoadOptions,
  133. onLabelsRefresh,
  134. datasource,
  135. datasourceStatus,
  136. } = this.props;
  137. const cleanText = datasource.languageProvider ? datasource.languageProvider.cleanText : undefined;
  138. const hasLogLabels = logLabelOptions && logLabelOptions.length > 0;
  139. const chooserText = getChooserText(syntaxLoaded, hasLogLabels, datasourceStatus);
  140. const buttonDisabled = !syntaxLoaded || datasourceStatus === DataSourceStatus.Disconnected;
  141. return (
  142. <>
  143. <div className="gf-form-inline">
  144. <div className="gf-form">
  145. <Cascader
  146. options={logLabelOptions}
  147. onChange={this.onChangeLogLabels}
  148. loadData={onLoadOptions}
  149. onPopupVisibleChange={(isVisible: boolean) => {
  150. if (isVisible && onLabelsRefresh) {
  151. onLabelsRefresh();
  152. }
  153. }}
  154. >
  155. <button className="gf-form-label gf-form-label--btn" disabled={buttonDisabled}>
  156. {chooserText} <i className="fa fa-caret-down" />
  157. </button>
  158. </Cascader>
  159. </div>
  160. <div className="gf-form gf-form--grow">
  161. <QueryField
  162. additionalPlugins={this.plugins}
  163. cleanText={cleanText}
  164. initialQuery={query.expr}
  165. onTypeahead={this.onTypeahead}
  166. onWillApplySuggestion={willApplySuggestion}
  167. onChange={this.onChangeQuery}
  168. onRunQuery={this.props.onRunQuery}
  169. placeholder="Enter a Loki query"
  170. portalOrigin="loki"
  171. syntaxLoaded={syntaxLoaded}
  172. />
  173. </div>
  174. </div>
  175. <div>
  176. {queryResponse && queryResponse.error ? (
  177. <div className="prom-query-field-info text-error">{queryResponse.error.message}</div>
  178. ) : null}
  179. </div>
  180. </>
  181. );
  182. }
  183. }