LokiQueryField.tsx 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  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. import LokiDatasource from '../datasource';
  14. // Types
  15. import { LokiQuery } from '../types';
  16. import { TypeaheadOutput } from 'app/types/explore';
  17. import { makePromiseCancelable, CancelablePromise } from 'app/core/utils/CancelablePromise';
  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 {
  59. datasource: LokiDatasource;
  60. error?: string | JSX.Element;
  61. hint?: any;
  62. history?: any[];
  63. initialQuery?: LokiQuery;
  64. onClickHintFix?: (action: any) => void;
  65. onPressEnter?: () => void;
  66. onQueryChange?: (value: LokiQuery, override?: boolean) => void;
  67. }
  68. interface LokiQueryFieldState {
  69. logLabelOptions: any[];
  70. syntaxLoaded: boolean;
  71. }
  72. export class LokiQueryField extends React.PureComponent<LokiQueryFieldProps, LokiQueryFieldState> {
  73. plugins: any[];
  74. pluginsSearch: any[];
  75. languageProvider: any;
  76. modifiedSearch: string;
  77. modifiedQuery: string;
  78. languageProviderInitializationPromise: CancelablePromise<any>;
  79. constructor(props: LokiQueryFieldProps, context) {
  80. super(props, context);
  81. if (props.datasource.languageProvider) {
  82. this.languageProvider = props.datasource.languageProvider;
  83. }
  84. this.plugins = [
  85. BracesPlugin(),
  86. RunnerPlugin({ handler: props.onPressEnter }),
  87. PluginPrism({
  88. onlyIn: node => node.type === 'code_block',
  89. getSyntax: node => 'promql',
  90. }),
  91. ];
  92. this.pluginsSearch = [RunnerPlugin({ handler: props.onPressEnter })];
  93. this.state = {
  94. logLabelOptions: [],
  95. syntaxLoaded: false,
  96. };
  97. }
  98. componentDidMount() {
  99. if (this.languageProvider) {
  100. this.languageProviderInitializationPromise = makePromiseCancelable(this.languageProvider.start());
  101. this.languageProviderInitializationPromise.promise
  102. .then(remaining => {
  103. remaining.map(task => task.then(this.onUpdateLanguage).catch(() => {}));
  104. })
  105. .then(() => this.onUpdateLanguage())
  106. .catch(({ isCanceled }) => {
  107. if (isCanceled) {
  108. console.warn('LokiQueryField has unmounted, language provider intialization was canceled');
  109. }
  110. });
  111. }
  112. }
  113. componentWillUnmount() {
  114. if (this.languageProviderInitializationPromise) {
  115. this.languageProviderInitializationPromise.cancel();
  116. }
  117. }
  118. loadOptions = (selectedOptions: CascaderOption[]) => {
  119. const targetOption = selectedOptions[selectedOptions.length - 1];
  120. this.setState(state => {
  121. const nextOptions = state.logLabelOptions.map(option => {
  122. if (option.value === targetOption.value) {
  123. return {
  124. ...option,
  125. loading: true,
  126. };
  127. }
  128. return option;
  129. });
  130. return { logLabelOptions: nextOptions };
  131. });
  132. this.languageProvider
  133. .fetchLabelValues(targetOption.value)
  134. .then(this.onUpdateLanguage)
  135. .catch(() => {});
  136. };
  137. onChangeLogLabels = (values: string[], selectedOptions: CascaderOption[]) => {
  138. if (selectedOptions.length === 2) {
  139. const key = selectedOptions[0].value;
  140. const value = selectedOptions[1].value;
  141. const query = `{${key}="${value}"}`;
  142. this.onChangeQuery(query, true);
  143. }
  144. };
  145. onChangeQuery = (value: string, override?: boolean) => {
  146. // Send text change to parent
  147. const { initialQuery, onQueryChange } = this.props;
  148. if (onQueryChange) {
  149. const query = {
  150. ...initialQuery,
  151. expr: value,
  152. };
  153. onQueryChange(query, override);
  154. }
  155. };
  156. onClickHintFix = () => {
  157. const { hint, onClickHintFix } = this.props;
  158. if (onClickHintFix && hint && hint.fix) {
  159. onClickHintFix(hint.fix.action);
  160. }
  161. };
  162. onUpdateLanguage = () => {
  163. Prism.languages[PRISM_SYNTAX] = this.languageProvider.getSyntax();
  164. const { logLabelOptions } = this.languageProvider;
  165. this.setState({
  166. logLabelOptions,
  167. syntaxLoaded: true,
  168. });
  169. };
  170. onTypeahead = (typeahead: TypeaheadInput): TypeaheadOutput => {
  171. if (!this.languageProvider) {
  172. return { suggestions: [] };
  173. }
  174. const { history } = this.props;
  175. const { prefix, text, value, wrapperNode } = typeahead;
  176. // Get DOM-dependent context
  177. const wrapperClasses = Array.from(wrapperNode.classList);
  178. const labelKeyNode = getPreviousCousin(wrapperNode, '.attr-name');
  179. const labelKey = labelKeyNode && labelKeyNode.textContent;
  180. const nextChar = getNextCharacter();
  181. const result = this.languageProvider.provideCompletionItems(
  182. { text, value, prefix, wrapperClasses, labelKey },
  183. { history }
  184. );
  185. console.log('handleTypeahead', wrapperClasses, text, prefix, nextChar, labelKey, result.context);
  186. return result;
  187. };
  188. render() {
  189. const { error, hint, initialQuery } = this.props;
  190. const { logLabelOptions, syntaxLoaded } = this.state;
  191. const cleanText = this.languageProvider ? this.languageProvider.cleanText : undefined;
  192. const hasLogLabels = logLabelOptions && logLabelOptions.length > 0;
  193. const chooserText = getChooserText(syntaxLoaded, hasLogLabels);
  194. return (
  195. <>
  196. <div className="gf-form-inline">
  197. <div className="gf-form">
  198. <Cascader options={logLabelOptions} onChange={this.onChangeLogLabels} loadData={this.loadOptions}>
  199. <button className="gf-form-label gf-form-label--btn" disabled={!syntaxLoaded}>
  200. {chooserText} <i className="fa fa-caret-down" />
  201. </button>
  202. </Cascader>
  203. </div>
  204. <div className="gf-form gf-form--grow">
  205. <QueryField
  206. additionalPlugins={this.plugins}
  207. cleanText={cleanText}
  208. initialQuery={initialQuery.expr}
  209. onTypeahead={this.onTypeahead}
  210. onWillApplySuggestion={willApplySuggestion}
  211. onValueChanged={this.onChangeQuery}
  212. placeholder="Enter a Loki query"
  213. portalOrigin="loki"
  214. syntaxLoaded={syntaxLoaded}
  215. />
  216. </div>
  217. </div>
  218. <div>
  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. </>
  232. );
  233. }
  234. }
  235. export default LokiQueryField;