LoggingQueryField.tsx 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  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
  81. .start()
  82. .then(remaining => {
  83. remaining.map(task => task.then(this.onUpdateLanguage).catch(() => {}));
  84. })
  85. .then(() => this.onUpdateLanguage());
  86. }
  87. }
  88. loadOptions = (selectedOptions: CascaderOption[]) => {
  89. const targetOption = selectedOptions[selectedOptions.length - 1];
  90. this.setState(state => {
  91. const nextOptions = state.logLabelOptions.map(option => {
  92. if (option.value === targetOption.value) {
  93. return {
  94. ...option,
  95. loading: true,
  96. };
  97. }
  98. return option;
  99. });
  100. return { logLabelOptions: nextOptions };
  101. });
  102. this.languageProvider
  103. .fetchLabelValues(targetOption.value)
  104. .then(this.onUpdateLanguage)
  105. .catch(() => {});
  106. };
  107. onChangeLogLabels = (values: string[], selectedOptions: CascaderOption[]) => {
  108. if (selectedOptions.length === 2) {
  109. const key = selectedOptions[0].value;
  110. const value = selectedOptions[1].value;
  111. const query = `{${key}="${value}"}`;
  112. this.onChangeQuery(query, true);
  113. }
  114. };
  115. onChangeQuery = (value: string, override?: boolean) => {
  116. // Send text change to parent
  117. const { onQueryChange } = this.props;
  118. if (onQueryChange) {
  119. onQueryChange(value, override);
  120. }
  121. };
  122. onClickHintFix = () => {
  123. const { hint, onClickHintFix } = this.props;
  124. if (onClickHintFix && hint && hint.fix) {
  125. onClickHintFix(hint.fix.action);
  126. }
  127. };
  128. onUpdateLanguage = () => {
  129. Prism.languages[PRISM_SYNTAX] = this.languageProvider.getSyntax();
  130. const { logLabelOptions } = this.languageProvider;
  131. this.setState({
  132. logLabelOptions,
  133. syntaxLoaded: true,
  134. });
  135. };
  136. onTypeahead = (typeahead: TypeaheadInput): TypeaheadOutput => {
  137. if (!this.languageProvider) {
  138. return { suggestions: [] };
  139. }
  140. const { history } = this.props;
  141. const { prefix, text, value, wrapperNode } = typeahead;
  142. // Get DOM-dependent context
  143. const wrapperClasses = Array.from(wrapperNode.classList);
  144. const labelKeyNode = getPreviousCousin(wrapperNode, '.attr-name');
  145. const labelKey = labelKeyNode && labelKeyNode.textContent;
  146. const nextChar = getNextCharacter();
  147. const result = this.languageProvider.provideCompletionItems(
  148. { text, value, prefix, wrapperClasses, labelKey },
  149. { history }
  150. );
  151. console.log('handleTypeahead', wrapperClasses, text, prefix, nextChar, labelKey, result.context);
  152. return result;
  153. };
  154. render() {
  155. const { error, hint, initialQuery } = this.props;
  156. const { logLabelOptions, syntaxLoaded } = this.state;
  157. const cleanText = this.languageProvider ? this.languageProvider.cleanText : undefined;
  158. const chooserText = syntaxLoaded ? 'Log labels' : 'Loading labels...';
  159. return (
  160. <div className="prom-query-field">
  161. <div className="prom-query-field-tools">
  162. <Cascader options={logLabelOptions} onChange={this.onChangeLogLabels} loadData={this.loadOptions}>
  163. <button className="btn navbar-button navbar-button--tight" disabled={!syntaxLoaded}>
  164. {chooserText}
  165. </button>
  166. </Cascader>
  167. </div>
  168. <div className="prom-query-field-wrapper">
  169. <TypeaheadField
  170. additionalPlugins={this.plugins}
  171. cleanText={cleanText}
  172. initialValue={initialQuery}
  173. onTypeahead={this.onTypeahead}
  174. onWillApplySuggestion={willApplySuggestion}
  175. onValueChanged={this.onChangeQuery}
  176. placeholder="Enter a PromQL query"
  177. portalOrigin="prometheus"
  178. syntaxLoaded={syntaxLoaded}
  179. />
  180. {error ? <div className="prom-query-field-info text-error">{error}</div> : null}
  181. {hint ? (
  182. <div className="prom-query-field-info text-warning">
  183. {hint.label}{' '}
  184. {hint.fix ? (
  185. <a className="text-link muted" onClick={this.onClickHintFix}>
  186. {hint.fix.label}
  187. </a>
  188. ) : null}
  189. </div>
  190. ) : null}
  191. </div>
  192. </div>
  193. );
  194. }
  195. }
  196. export default LoggingQueryField;