LoggingQueryField.tsx 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. import _ from 'lodash';
  2. import React from 'react';
  3. import Cascader from 'rc-cascader';
  4. import PluginPrism from 'slate-prism';
  5. import Prism from 'prismjs';
  6. import { TypeaheadOutput } from 'app/types/explore';
  7. // dom also includes Element polyfills
  8. import { getNextCharacter, getPreviousCousin } from 'app/features/explore/utils/dom';
  9. import BracesPlugin from 'app/features/explore/slate-plugins/braces';
  10. import RunnerPlugin from 'app/features/explore/slate-plugins/runner';
  11. import TypeaheadField, { TypeaheadInput, QueryFieldState } from 'app/features/explore/QueryField';
  12. const PRISM_SYNTAX = 'promql';
  13. export function willApplySuggestion(suggestion: string, { typeaheadContext, typeaheadText }: QueryFieldState): string {
  14. // Modify suggestion based on context
  15. switch (typeaheadContext) {
  16. case 'context-labels': {
  17. const nextChar = getNextCharacter();
  18. if (!nextChar || nextChar === '}' || nextChar === ',') {
  19. suggestion += '=';
  20. }
  21. break;
  22. }
  23. case 'context-label-values': {
  24. // Always add quotes and remove existing ones instead
  25. if (!typeaheadText.match(/^(!?=~?"|")/)) {
  26. suggestion = `"${suggestion}`;
  27. }
  28. if (getNextCharacter() !== '"') {
  29. suggestion = `${suggestion}"`;
  30. }
  31. break;
  32. }
  33. default:
  34. }
  35. return suggestion;
  36. }
  37. interface CascaderOption {
  38. label: string;
  39. value: string;
  40. children?: CascaderOption[];
  41. disabled?: boolean;
  42. }
  43. interface LoggingQueryFieldProps {
  44. datasource: any;
  45. error?: string | JSX.Element;
  46. hint?: any;
  47. history?: any[];
  48. initialQuery?: string | null;
  49. onClickHintFix?: (action: any) => void;
  50. onPressEnter?: () => void;
  51. onQueryChange?: (value: string, override?: boolean) => void;
  52. }
  53. interface LoggingQueryFieldState {
  54. logLabelOptions: any[];
  55. syntaxLoaded: boolean;
  56. }
  57. class LoggingQueryField extends React.PureComponent<LoggingQueryFieldProps, LoggingQueryFieldState> {
  58. plugins: any[];
  59. languageProvider: any;
  60. constructor(props: LoggingQueryFieldProps, context) {
  61. super(props, context);
  62. if (props.datasource.languageProvider) {
  63. this.languageProvider = props.datasource.languageProvider;
  64. }
  65. this.plugins = [
  66. BracesPlugin(),
  67. RunnerPlugin({ handler: props.onPressEnter }),
  68. PluginPrism({
  69. onlyIn: node => node.type === 'code_block',
  70. getSyntax: node => 'promql',
  71. }),
  72. ];
  73. this.state = {
  74. logLabelOptions: [],
  75. syntaxLoaded: false,
  76. };
  77. }
  78. componentDidMount() {
  79. if (this.languageProvider) {
  80. this.languageProvider.start().then(() => this.onReceiveMetrics());
  81. }
  82. }
  83. onChangeLogLabels = (values: string[], selectedOptions: CascaderOption[]) => {
  84. let query;
  85. if (selectedOptions.length === 1) {
  86. if (selectedOptions[0].children.length === 0) {
  87. query = selectedOptions[0].value;
  88. } else {
  89. // Ignore click on group
  90. return;
  91. }
  92. } else {
  93. const key = selectedOptions[0].value;
  94. const value = selectedOptions[1].value;
  95. query = `{${key}="${value}"}`;
  96. }
  97. this.onChangeQuery(query, true);
  98. };
  99. onChangeQuery = (value: string, override?: boolean) => {
  100. // Send text change to parent
  101. const { onQueryChange } = this.props;
  102. if (onQueryChange) {
  103. onQueryChange(value, override);
  104. }
  105. };
  106. onClickHintFix = () => {
  107. const { hint, onClickHintFix } = this.props;
  108. if (onClickHintFix && hint && hint.fix) {
  109. onClickHintFix(hint.fix.action);
  110. }
  111. };
  112. onReceiveMetrics = () => {
  113. Prism.languages[PRISM_SYNTAX] = this.languageProvider.getSyntax();
  114. const { logLabelOptions } = this.languageProvider;
  115. this.setState({
  116. logLabelOptions,
  117. syntaxLoaded: true,
  118. });
  119. };
  120. onTypeahead = (typeahead: TypeaheadInput): TypeaheadOutput => {
  121. if (!this.languageProvider) {
  122. return { suggestions: [] };
  123. }
  124. const { history } = this.props;
  125. const { prefix, text, value, wrapperNode } = typeahead;
  126. // Get DOM-dependent context
  127. const wrapperClasses = Array.from(wrapperNode.classList);
  128. const labelKeyNode = getPreviousCousin(wrapperNode, '.attr-name');
  129. const labelKey = labelKeyNode && labelKeyNode.textContent;
  130. const nextChar = getNextCharacter();
  131. const result = this.languageProvider.provideCompletionItems(
  132. { text, value, prefix, wrapperClasses, labelKey },
  133. { history }
  134. );
  135. console.log('handleTypeahead', wrapperClasses, text, prefix, nextChar, labelKey, result.context);
  136. return result;
  137. };
  138. render() {
  139. const { error, hint, initialQuery } = this.props;
  140. const { logLabelOptions, syntaxLoaded } = this.state;
  141. const cleanText = this.languageProvider ? this.languageProvider.cleanText : undefined;
  142. return (
  143. <div className="prom-query-field">
  144. <div className="prom-query-field-tools">
  145. <Cascader options={logLabelOptions} onChange={this.onChangeLogLabels}>
  146. <button className="btn navbar-button navbar-button--tight">Log labels</button>
  147. </Cascader>
  148. </div>
  149. <div className="prom-query-field-wrapper">
  150. <TypeaheadField
  151. additionalPlugins={this.plugins}
  152. cleanText={cleanText}
  153. initialValue={initialQuery}
  154. onTypeahead={this.onTypeahead}
  155. onWillApplySuggestion={willApplySuggestion}
  156. onValueChanged={this.onChangeQuery}
  157. placeholder="Enter a PromQL query"
  158. portalOrigin="prometheus"
  159. syntaxLoaded={syntaxLoaded}
  160. />
  161. {error ? <div className="prom-query-field-info text-error">{error}</div> : null}
  162. {hint ? (
  163. <div className="prom-query-field-info text-warning">
  164. {hint.label}{' '}
  165. {hint.fix ? (
  166. <a className="text-link muted" onClick={this.onClickHintFix}>
  167. {hint.fix.label}
  168. </a>
  169. ) : null}
  170. </div>
  171. ) : null}
  172. </div>
  173. </div>
  174. );
  175. }
  176. }
  177. export default LoggingQueryField;