LokiQueryField.tsx 7.1 KB

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