LokiQueryField.tsx 7.2 KB

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