LokiQueryField.tsx 7.8 KB

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