LokiQueryField.tsx 8.3 KB

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