LokiQueryField.tsx 7.1 KB

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