LokiQueryFieldForm.tsx 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. // Libraries
  2. import React from 'react';
  3. // @ts-ignore
  4. import Cascader from 'rc-cascader';
  5. // @ts-ignore
  6. import PluginPrism from 'slate-prism';
  7. // Components
  8. import QueryField, { TypeaheadInput, QueryFieldState } from 'app/features/explore/QueryField';
  9. // Utils & Services
  10. // dom also includes Element polyfills
  11. import { getNextCharacter, getPreviousCousin } from 'app/features/explore/utils/dom';
  12. import BracesPlugin from 'app/features/explore/slate-plugins/braces';
  13. import RunnerPlugin from 'app/features/explore/slate-plugins/runner';
  14. // Types
  15. import { LokiQuery } from '../types';
  16. import { TypeaheadOutput, HistoryItem } from 'app/types/explore';
  17. import { ExploreDataSourceApi, ExploreQueryFieldProps, DataSourceStatus } from '@grafana/ui';
  18. function getChooserText(hasSyntax: boolean, hasLogLabels: boolean, datasourceStatus: DataSourceStatus) {
  19. if (datasourceStatus === DataSourceStatus.Disconnected) {
  20. return '(Disconnected)';
  21. }
  22. if (!hasSyntax) {
  23. return 'Loading labels...';
  24. }
  25. if (!hasLogLabels) {
  26. return '(No labels found)';
  27. }
  28. return 'Log labels';
  29. }
  30. function willApplySuggestion(suggestion: string, { typeaheadContext, typeaheadText }: QueryFieldState): string {
  31. // Modify suggestion based on context
  32. switch (typeaheadContext) {
  33. case 'context-labels': {
  34. const nextChar = getNextCharacter();
  35. if (!nextChar || nextChar === '}' || nextChar === ',') {
  36. suggestion += '=';
  37. }
  38. break;
  39. }
  40. case 'context-label-values': {
  41. // Always add quotes and remove existing ones instead
  42. if (!typeaheadText.match(/^(!?=~?"|")/)) {
  43. suggestion = `"${suggestion}`;
  44. }
  45. if (getNextCharacter() !== '"') {
  46. suggestion = `${suggestion}"`;
  47. }
  48. break;
  49. }
  50. default:
  51. }
  52. return suggestion;
  53. }
  54. export interface CascaderOption {
  55. label: string;
  56. value: string;
  57. children?: CascaderOption[];
  58. disabled?: boolean;
  59. }
  60. export interface LokiQueryFieldFormProps extends ExploreQueryFieldProps<ExploreDataSourceApi, LokiQuery> {
  61. history: HistoryItem[];
  62. syntax: any;
  63. logLabelOptions: any[];
  64. syntaxLoaded: any;
  65. onLoadOptions: (selectedOptions: CascaderOption[]) => void;
  66. onLabelsRefresh?: () => void;
  67. }
  68. export class LokiQueryFieldForm extends React.PureComponent<LokiQueryFieldFormProps> {
  69. plugins: any[];
  70. pluginsSearch: any[];
  71. modifiedSearch: string;
  72. modifiedQuery: string;
  73. constructor(props: LokiQueryFieldFormProps, context: React.Context<any>) {
  74. super(props, context);
  75. this.plugins = [
  76. BracesPlugin(),
  77. RunnerPlugin({ handler: props.onExecuteQuery }),
  78. PluginPrism({
  79. onlyIn: (node: any) => node.type === 'code_block',
  80. getSyntax: (node: any) => 'promql',
  81. }),
  82. ];
  83. this.pluginsSearch = [RunnerPlugin({ handler: props.onExecuteQuery })];
  84. }
  85. loadOptions = (selectedOptions: CascaderOption[]) => {
  86. this.props.onLoadOptions(selectedOptions);
  87. };
  88. onChangeLogLabels = (values: string[], selectedOptions: CascaderOption[]) => {
  89. if (selectedOptions.length === 2) {
  90. const key = selectedOptions[0].value;
  91. const value = selectedOptions[1].value;
  92. const query = `{${key}="${value}"}`;
  93. this.onChangeQuery(query, true);
  94. }
  95. };
  96. onChangeQuery = (value: string, override?: boolean) => {
  97. // Send text change to parent
  98. const { query, onQueryChange, onExecuteQuery } = this.props;
  99. if (onQueryChange) {
  100. const nextQuery = { ...query, expr: value };
  101. onQueryChange(nextQuery);
  102. if (override && onExecuteQuery) {
  103. onExecuteQuery();
  104. }
  105. }
  106. };
  107. onClickHintFix = () => {
  108. const { hint, onExecuteHint } = this.props;
  109. if (onExecuteHint && hint && hint.fix) {
  110. onExecuteHint(hint.fix.action);
  111. }
  112. };
  113. onTypeahead = (typeahead: TypeaheadInput): TypeaheadOutput => {
  114. const { datasource } = this.props;
  115. if (!datasource.languageProvider) {
  116. return { suggestions: [] };
  117. }
  118. const { history } = this.props;
  119. const { prefix, text, value, wrapperNode } = typeahead;
  120. // Get DOM-dependent context
  121. const wrapperClasses = Array.from(wrapperNode.classList);
  122. const labelKeyNode = getPreviousCousin(wrapperNode, '.attr-name');
  123. const labelKey = labelKeyNode && labelKeyNode.textContent;
  124. const nextChar = getNextCharacter();
  125. const result = datasource.languageProvider.provideCompletionItems(
  126. { text, value, prefix, wrapperClasses, labelKey },
  127. { history }
  128. );
  129. console.log('handleTypeahead', wrapperClasses, text, prefix, nextChar, labelKey, result.context);
  130. return result;
  131. };
  132. render() {
  133. const {
  134. error,
  135. hint,
  136. query,
  137. syntaxLoaded,
  138. logLabelOptions,
  139. onLoadOptions,
  140. onLabelsRefresh,
  141. datasource,
  142. datasourceStatus,
  143. } = this.props;
  144. const cleanText = datasource.languageProvider ? datasource.languageProvider.cleanText : undefined;
  145. const hasLogLabels = logLabelOptions && logLabelOptions.length > 0;
  146. const chooserText = getChooserText(syntaxLoaded, hasLogLabels, datasourceStatus);
  147. const buttonDisabled = !syntaxLoaded || datasourceStatus === DataSourceStatus.Disconnected;
  148. return (
  149. <>
  150. <div className="gf-form-inline">
  151. <div className="gf-form">
  152. <Cascader
  153. options={logLabelOptions}
  154. onChange={this.onChangeLogLabels}
  155. loadData={onLoadOptions}
  156. onPopupVisibleChange={(isVisible: boolean) => {
  157. if (isVisible && onLabelsRefresh) {
  158. onLabelsRefresh();
  159. }
  160. }}
  161. >
  162. <button className="gf-form-label gf-form-label--btn" disabled={buttonDisabled}>
  163. {chooserText} <i className="fa fa-caret-down" />
  164. </button>
  165. </Cascader>
  166. </div>
  167. <div className="gf-form gf-form--grow">
  168. <QueryField
  169. additionalPlugins={this.plugins}
  170. cleanText={cleanText}
  171. initialQuery={query.expr}
  172. onTypeahead={this.onTypeahead}
  173. onWillApplySuggestion={willApplySuggestion}
  174. onQueryChange={this.onChangeQuery}
  175. onExecuteQuery={this.props.onExecuteQuery}
  176. placeholder="Enter a Loki query"
  177. portalOrigin="loki"
  178. syntaxLoaded={syntaxLoaded}
  179. />
  180. </div>
  181. </div>
  182. <div>
  183. {error ? <div className="prom-query-field-info text-error">{error}</div> : null}
  184. {hint ? (
  185. <div className="prom-query-field-info text-warning">
  186. {hint.label}{' '}
  187. {hint.fix ? (
  188. <a className="text-link muted" onClick={this.onClickHintFix}>
  189. {hint.fix.label}
  190. </a>
  191. ) : null}
  192. </div>
  193. ) : null}
  194. </div>
  195. </>
  196. );
  197. }
  198. }