LokiQueryField.tsx 8.3 KB

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