LokiQueryFieldForm.tsx 6.4 KB

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