LokiQueryField.tsx 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  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 { query, onQueryChange, onExecuteQuery } = this.props;
  141. if (onQueryChange) {
  142. const nextQuery = { ...query, expr: value };
  143. onQueryChange(nextQuery);
  144. if (override && onExecuteQuery) {
  145. onExecuteQuery();
  146. }
  147. }
  148. };
  149. onClickHintFix = () => {
  150. const { hint, onExecuteHint } = this.props;
  151. if (onExecuteHint && hint && hint.fix) {
  152. onExecuteHint(hint.fix.action);
  153. }
  154. };
  155. onUpdateLanguage = () => {
  156. Prism.languages[PRISM_SYNTAX] = this.languageProvider.getSyntax();
  157. const { logLabelOptions } = this.languageProvider;
  158. this.setState({
  159. logLabelOptions,
  160. syntaxLoaded: true,
  161. });
  162. };
  163. onTypeahead = (typeahead: TypeaheadInput): TypeaheadOutput => {
  164. if (!this.languageProvider) {
  165. return { suggestions: [] };
  166. }
  167. const { history } = this.props;
  168. const { prefix, text, value, wrapperNode } = typeahead;
  169. // Get DOM-dependent context
  170. const wrapperClasses = Array.from(wrapperNode.classList);
  171. const labelKeyNode = getPreviousCousin(wrapperNode, '.attr-name');
  172. const labelKey = labelKeyNode && labelKeyNode.textContent;
  173. const nextChar = getNextCharacter();
  174. const result = this.languageProvider.provideCompletionItems(
  175. { text, value, prefix, wrapperClasses, labelKey },
  176. { history }
  177. );
  178. console.log('handleTypeahead', wrapperClasses, text, prefix, nextChar, labelKey, result.context);
  179. return result;
  180. };
  181. render() {
  182. const { error, hint, query } = this.props;
  183. const { logLabelOptions, syntaxLoaded } = this.state;
  184. const cleanText = this.languageProvider ? this.languageProvider.cleanText : undefined;
  185. const hasLogLabels = logLabelOptions && logLabelOptions.length > 0;
  186. const chooserText = getChooserText(syntaxLoaded, hasLogLabels);
  187. return (
  188. <>
  189. <div className="gf-form-inline">
  190. <div className="gf-form">
  191. <Cascader options={logLabelOptions} onChange={this.onChangeLogLabels} loadData={this.loadOptions}>
  192. <button className="gf-form-label gf-form-label--btn" disabled={!syntaxLoaded}>
  193. {chooserText} <i className="fa fa-caret-down" />
  194. </button>
  195. </Cascader>
  196. </div>
  197. <div className="gf-form gf-form--grow">
  198. <QueryField
  199. additionalPlugins={this.plugins}
  200. cleanText={cleanText}
  201. initialQuery={query.expr}
  202. onTypeahead={this.onTypeahead}
  203. onWillApplySuggestion={willApplySuggestion}
  204. onQueryChange={this.onChangeQuery}
  205. onExecuteQuery={this.props.onExecuteQuery}
  206. placeholder="Enter a Loki query"
  207. portalOrigin="loki"
  208. syntaxLoaded={syntaxLoaded}
  209. />
  210. </div>
  211. </div>
  212. <div>
  213. {error ? <div className="prom-query-field-info text-error">{error}</div> : null}
  214. {hint ? (
  215. <div className="prom-query-field-info text-warning">
  216. {hint.label}{' '}
  217. {hint.fix ? (
  218. <a className="text-link muted" onClick={this.onClickHintFix}>
  219. {hint.fix.label}
  220. </a>
  221. ) : null}
  222. </div>
  223. ) : null}
  224. </div>
  225. </>
  226. );
  227. }
  228. }
  229. export default LokiQueryField;