LokiQueryField.tsx 7.1 KB

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