LoggingQueryField.tsx 6.7 KB

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