LokiQueryField.tsx 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. // Libraries
  2. import React from 'react';
  3. import Cascader from 'rc-cascader';
  4. import PluginPrism from 'slate-prism';
  5. import Prism from 'prismjs';
  6. // Components
  7. import QueryField, { TypeaheadInput, QueryFieldState } from 'app/features/explore/QueryField';
  8. // Utils & Services
  9. // dom also includes Element polyfills
  10. import { getNextCharacter, getPreviousCousin } from 'app/features/explore/utils/dom';
  11. import BracesPlugin from 'app/features/explore/slate-plugins/braces';
  12. import RunnerPlugin from 'app/features/explore/slate-plugins/runner';
  13. // Types
  14. import { LokiQuery } from '../types';
  15. import { TypeaheadOutput, HistoryItem } from 'app/types/explore';
  16. import { makePromiseCancelable, CancelablePromise } from 'app/core/utils/CancelablePromise';
  17. import { ExploreDataSourceApi, ExploreQueryFieldProps } from '@grafana/ui';
  18. const PRISM_SYNTAX = 'promql';
  19. function getChooserText(hasSytax, hasLogLabels) {
  20. if (!hasSytax) {
  21. return 'Loading labels...';
  22. }
  23. if (!hasLogLabels) {
  24. return '(No labels found)';
  25. }
  26. return 'Log labels';
  27. }
  28. export function willApplySuggestion(suggestion: string, { typeaheadContext, typeaheadText }: QueryFieldState): string {
  29. // Modify suggestion based on context
  30. switch (typeaheadContext) {
  31. case 'context-labels': {
  32. const nextChar = getNextCharacter();
  33. if (!nextChar || nextChar === '}' || nextChar === ',') {
  34. suggestion += '=';
  35. }
  36. break;
  37. }
  38. case 'context-label-values': {
  39. // Always add quotes and remove existing ones instead
  40. if (!typeaheadText.match(/^(!?=~?"|")/)) {
  41. suggestion = `"${suggestion}`;
  42. }
  43. if (getNextCharacter() !== '"') {
  44. suggestion = `${suggestion}"`;
  45. }
  46. break;
  47. }
  48. default:
  49. }
  50. return suggestion;
  51. }
  52. interface CascaderOption {
  53. label: string;
  54. value: string;
  55. children?: CascaderOption[];
  56. disabled?: boolean;
  57. }
  58. interface LokiQueryFieldProps extends ExploreQueryFieldProps<ExploreDataSourceApi, LokiQuery> {
  59. history: HistoryItem[];
  60. }
  61. interface LokiQueryFieldState {
  62. logLabelOptions: any[];
  63. syntaxLoaded: boolean;
  64. }
  65. export class LokiQueryField extends React.PureComponent<LokiQueryFieldProps, LokiQueryFieldState> {
  66. plugins: any[];
  67. pluginsSearch: any[];
  68. languageProvider: any;
  69. modifiedSearch: string;
  70. modifiedQuery: string;
  71. languageProviderInitializationPromise: CancelablePromise<any>;
  72. constructor(props: LokiQueryFieldProps, context) {
  73. super(props, context);
  74. if (props.datasource.languageProvider) {
  75. this.languageProvider = props.datasource.languageProvider;
  76. }
  77. this.plugins = [
  78. BracesPlugin(),
  79. RunnerPlugin({ handler: props.onExecuteQuery }),
  80. PluginPrism({
  81. onlyIn: node => node.type === 'code_block',
  82. getSyntax: node => 'promql',
  83. }),
  84. ];
  85. this.pluginsSearch = [RunnerPlugin({ handler: props.onExecuteQuery })];
  86. this.state = {
  87. logLabelOptions: [],
  88. syntaxLoaded: false,
  89. };
  90. }
  91. componentDidMount() {
  92. if (this.languageProvider) {
  93. this.languageProviderInitializationPromise = makePromiseCancelable(this.languageProvider.start());
  94. this.languageProviderInitializationPromise.promise
  95. .then(remaining => {
  96. remaining.map(task => task.then(this.onUpdateLanguage).catch(() => {}));
  97. })
  98. .then(() => this.onUpdateLanguage())
  99. .catch(({ isCanceled }) => {
  100. if (isCanceled) {
  101. console.warn('LokiQueryField has unmounted, language provider intialization was canceled');
  102. }
  103. });
  104. }
  105. }
  106. componentWillUnmount() {
  107. if (this.languageProviderInitializationPromise) {
  108. this.languageProviderInitializationPromise.cancel();
  109. }
  110. }
  111. loadOptions = (selectedOptions: CascaderOption[]) => {
  112. const targetOption = selectedOptions[selectedOptions.length - 1];
  113. this.setState(state => {
  114. const nextOptions = state.logLabelOptions.map(option => {
  115. if (option.value === targetOption.value) {
  116. return {
  117. ...option,
  118. loading: true,
  119. };
  120. }
  121. return option;
  122. });
  123. return { logLabelOptions: nextOptions };
  124. });
  125. this.languageProvider
  126. .fetchLabelValues(targetOption.value)
  127. .then(this.onUpdateLanguage)
  128. .catch(() => {});
  129. };
  130. onChangeLogLabels = (values: string[], selectedOptions: CascaderOption[]) => {
  131. if (selectedOptions.length === 2) {
  132. const key = selectedOptions[0].value;
  133. const value = selectedOptions[1].value;
  134. const query = `{${key}="${value}"}`;
  135. this.onChangeQuery(query, true);
  136. }
  137. };
  138. onChangeQuery = (value: string, override?: boolean) => {
  139. // Send text change to parent
  140. const { initialQuery, onQueryChange, onExecuteQuery } = this.props;
  141. if (onQueryChange) {
  142. const query = {
  143. ...initialQuery,
  144. expr: value,
  145. };
  146. onQueryChange(query);
  147. if (override && onExecuteQuery) {
  148. onExecuteQuery();
  149. }
  150. }
  151. };
  152. onClickHintFix = () => {
  153. const { hint, onExecuteHint } = this.props;
  154. if (onExecuteHint && hint && hint.fix) {
  155. onExecuteHint(hint.fix.action);
  156. }
  157. };
  158. onUpdateLanguage = () => {
  159. Prism.languages[PRISM_SYNTAX] = this.languageProvider.getSyntax();
  160. const { logLabelOptions } = this.languageProvider;
  161. this.setState({
  162. logLabelOptions,
  163. syntaxLoaded: true,
  164. });
  165. };
  166. onTypeahead = (typeahead: TypeaheadInput): TypeaheadOutput => {
  167. if (!this.languageProvider) {
  168. return { suggestions: [] };
  169. }
  170. const { history } = this.props;
  171. const { prefix, text, value, wrapperNode } = typeahead;
  172. // Get DOM-dependent context
  173. const wrapperClasses = Array.from(wrapperNode.classList);
  174. const labelKeyNode = getPreviousCousin(wrapperNode, '.attr-name');
  175. const labelKey = labelKeyNode && labelKeyNode.textContent;
  176. const nextChar = getNextCharacter();
  177. const result = this.languageProvider.provideCompletionItems(
  178. { text, value, prefix, wrapperClasses, labelKey },
  179. { history }
  180. );
  181. console.log('handleTypeahead', wrapperClasses, text, prefix, nextChar, labelKey, result.context);
  182. return result;
  183. };
  184. render() {
  185. const { error, hint, initialQuery } = this.props;
  186. const { logLabelOptions, syntaxLoaded } = this.state;
  187. const cleanText = this.languageProvider ? this.languageProvider.cleanText : undefined;
  188. const hasLogLabels = logLabelOptions && logLabelOptions.length > 0;
  189. const chooserText = getChooserText(syntaxLoaded, hasLogLabels);
  190. return (
  191. <>
  192. <div className="gf-form-inline">
  193. <div className="gf-form">
  194. <Cascader options={logLabelOptions} onChange={this.onChangeLogLabels} loadData={this.loadOptions}>
  195. <button className="gf-form-label gf-form-label--btn" disabled={!syntaxLoaded}>
  196. {chooserText} <i className="fa fa-caret-down" />
  197. </button>
  198. </Cascader>
  199. </div>
  200. <div className="gf-form gf-form--grow">
  201. <QueryField
  202. additionalPlugins={this.plugins}
  203. cleanText={cleanText}
  204. initialQuery={initialQuery.expr}
  205. onTypeahead={this.onTypeahead}
  206. onWillApplySuggestion={willApplySuggestion}
  207. onQueryChange={this.onChangeQuery}
  208. onExecuteQuery={this.props.onExecuteQuery}
  209. placeholder="Enter a Loki query"
  210. portalOrigin="loki"
  211. syntaxLoaded={syntaxLoaded}
  212. />
  213. </div>
  214. </div>
  215. <div>
  216. {error ? <div className="prom-query-field-info text-error">{error}</div> : null}
  217. {hint ? (
  218. <div className="prom-query-field-info text-warning">
  219. {hint.label}{' '}
  220. {hint.fix ? (
  221. <a className="text-link muted" onClick={this.onClickHintFix}>
  222. {hint.fix.label}
  223. </a>
  224. ) : null}
  225. </div>
  226. ) : null}
  227. </div>
  228. </>
  229. );
  230. }
  231. }
  232. export default LokiQueryField;