PromQueryField.tsx 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  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 TypeaheadField, { TypeaheadInput, QueryFieldState } from 'app/features/explore/QueryField';
  12. const HISTOGRAM_GROUP = '__histograms__';
  13. const METRIC_MARK = 'metric';
  14. const PRISM_SYNTAX = 'promql';
  15. export const RECORDING_RULES_GROUP = '__recording_rules__';
  16. export function groupMetricsByPrefix(metrics: string[], delimiter = '_'): CascaderOption[] {
  17. // Filter out recording rules and insert as first option
  18. const ruleRegex = /:\w+:/;
  19. const ruleNames = metrics.filter(metric => ruleRegex.test(metric));
  20. const rulesOption = {
  21. label: 'Recording rules',
  22. value: RECORDING_RULES_GROUP,
  23. children: ruleNames
  24. .slice()
  25. .sort()
  26. .map(name => ({ label: name, value: name })),
  27. };
  28. const options = ruleNames.length > 0 ? [rulesOption] : [];
  29. const metricsOptions = _.chain(metrics)
  30. .filter(metric => !ruleRegex.test(metric))
  31. .groupBy(metric => metric.split(delimiter)[0])
  32. .map((metricsForPrefix: string[], prefix: string): CascaderOption => {
  33. const prefixIsMetric = metricsForPrefix.length === 1 && metricsForPrefix[0] === prefix;
  34. const children = prefixIsMetric ? [] : metricsForPrefix.sort().map(m => ({ label: m, value: m }));
  35. return {
  36. children,
  37. label: prefix,
  38. value: prefix,
  39. };
  40. })
  41. .sortBy('label')
  42. .value();
  43. return [...options, ...metricsOptions];
  44. }
  45. export function willApplySuggestion(suggestion: string, { typeaheadContext, typeaheadText }: QueryFieldState): string {
  46. // Modify suggestion based on context
  47. switch (typeaheadContext) {
  48. case 'context-labels': {
  49. const nextChar = getNextCharacter();
  50. if (!nextChar || nextChar === '}' || nextChar === ',') {
  51. suggestion += '=';
  52. }
  53. break;
  54. }
  55. case 'context-label-values': {
  56. // Always add quotes and remove existing ones instead
  57. if (!typeaheadText.match(/^(!?=~?"|")/)) {
  58. suggestion = `"${suggestion}`;
  59. }
  60. if (getNextCharacter() !== '"') {
  61. suggestion = `${suggestion}"`;
  62. }
  63. break;
  64. }
  65. default:
  66. }
  67. return suggestion;
  68. }
  69. interface CascaderOption {
  70. label: string;
  71. value: string;
  72. children?: CascaderOption[];
  73. disabled?: boolean;
  74. }
  75. interface PromQueryFieldProps {
  76. datasource: any;
  77. error?: string | JSX.Element;
  78. hint?: any;
  79. history?: any[];
  80. initialQuery?: string | null;
  81. metricsByPrefix?: CascaderOption[];
  82. onClickHintFix?: (action: any) => void;
  83. onPressEnter?: () => void;
  84. onQueryChange?: (value: string, override?: boolean) => void;
  85. }
  86. interface PromQueryFieldState {
  87. metricsOptions: any[];
  88. metricsByPrefix: CascaderOption[];
  89. syntaxLoaded: boolean;
  90. }
  91. class PromQueryField extends React.PureComponent<PromQueryFieldProps, PromQueryFieldState> {
  92. plugins: any[];
  93. languageProvider: any;
  94. constructor(props: PromQueryFieldProps, context) {
  95. super(props, context);
  96. if (props.datasource.languageProvider) {
  97. this.languageProvider = props.datasource.languageProvider;
  98. }
  99. this.plugins = [
  100. BracesPlugin(),
  101. RunnerPlugin({ handler: props.onPressEnter }),
  102. PluginPrism({
  103. onlyIn: node => node.type === 'code_block',
  104. getSyntax: node => 'promql',
  105. }),
  106. ];
  107. this.state = {
  108. metricsByPrefix: [],
  109. metricsOptions: [],
  110. syntaxLoaded: false,
  111. };
  112. }
  113. componentDidMount() {
  114. if (this.languageProvider) {
  115. this.languageProvider
  116. .start()
  117. .then(remaining => {
  118. remaining.map(task => task.then(this.onUpdateLanguage).catch(() => {}));
  119. })
  120. .then(() => this.onUpdateLanguage());
  121. }
  122. }
  123. onChangeMetrics = (values: string[], selectedOptions: CascaderOption[]) => {
  124. let query;
  125. if (selectedOptions.length === 1) {
  126. if (selectedOptions[0].children.length === 0) {
  127. query = selectedOptions[0].value;
  128. } else {
  129. // Ignore click on group
  130. return;
  131. }
  132. } else {
  133. const prefix = selectedOptions[0].value;
  134. const metric = selectedOptions[1].value;
  135. if (prefix === HISTOGRAM_GROUP) {
  136. query = `histogram_quantile(0.95, sum(rate(${metric}[5m])) by (le))`;
  137. } else {
  138. query = metric;
  139. }
  140. }
  141. this.onChangeQuery(query, true);
  142. };
  143. onChangeQuery = (value: string, override?: boolean) => {
  144. // Send text change to parent
  145. const { onQueryChange } = this.props;
  146. if (onQueryChange) {
  147. onQueryChange(value, override);
  148. }
  149. };
  150. onClickHintFix = () => {
  151. const { hint, onClickHintFix } = this.props;
  152. if (onClickHintFix && hint && hint.fix) {
  153. onClickHintFix(hint.fix.action);
  154. }
  155. };
  156. onUpdateLanguage = () => {
  157. const { histogramMetrics, metrics } = this.languageProvider;
  158. if (!metrics) {
  159. return;
  160. }
  161. Prism.languages[PRISM_SYNTAX] = this.languageProvider.getSyntax();
  162. Prism.languages[PRISM_SYNTAX][METRIC_MARK] = {
  163. alias: 'variable',
  164. pattern: new RegExp(`(?:^|\\s)(${metrics.join('|')})(?:$|\\s)`),
  165. };
  166. // Build metrics tree
  167. const metricsByPrefix = groupMetricsByPrefix(metrics);
  168. const histogramOptions = histogramMetrics.map(hm => ({ label: hm, value: hm }));
  169. const metricsOptions =
  170. histogramMetrics.length > 0
  171. ? [
  172. { label: 'Histograms', value: HISTOGRAM_GROUP, children: histogramOptions, isLeaf: false },
  173. ...metricsByPrefix,
  174. ]
  175. : metricsByPrefix;
  176. this.setState({ metricsOptions, syntaxLoaded: true });
  177. };
  178. onTypeahead = (typeahead: TypeaheadInput): TypeaheadOutput => {
  179. if (!this.languageProvider) {
  180. return { suggestions: [] };
  181. }
  182. const { history } = this.props;
  183. const { prefix, text, value, wrapperNode } = typeahead;
  184. // Get DOM-dependent context
  185. const wrapperClasses = Array.from(wrapperNode.classList);
  186. const labelKeyNode = getPreviousCousin(wrapperNode, '.attr-name');
  187. const labelKey = labelKeyNode && labelKeyNode.textContent;
  188. const nextChar = getNextCharacter();
  189. const result = this.languageProvider.provideCompletionItems(
  190. { text, value, prefix, wrapperClasses, labelKey },
  191. { history }
  192. );
  193. console.log('handleTypeahead', wrapperClasses, text, prefix, nextChar, labelKey, result.context);
  194. return result;
  195. };
  196. render() {
  197. const { error, hint, initialQuery } = this.props;
  198. const { metricsOptions, syntaxLoaded } = this.state;
  199. const cleanText = this.languageProvider ? this.languageProvider.cleanText : undefined;
  200. const chooserText = syntaxLoaded ? 'Metrics' : 'Loading matrics...';
  201. return (
  202. <div className="prom-query-field">
  203. <div className="prom-query-field-tools">
  204. <Cascader options={metricsOptions} onChange={this.onChangeMetrics}>
  205. <button className="btn navbar-button navbar-button--tight" disabled={!syntaxLoaded}>
  206. {chooserText}
  207. </button>
  208. </Cascader>
  209. </div>
  210. <div className="prom-query-field-wrapper">
  211. <TypeaheadField
  212. additionalPlugins={this.plugins}
  213. cleanText={cleanText}
  214. initialValue={initialQuery}
  215. onTypeahead={this.onTypeahead}
  216. onWillApplySuggestion={willApplySuggestion}
  217. onValueChanged={this.onChangeQuery}
  218. placeholder="Enter a PromQL query"
  219. portalOrigin="prometheus"
  220. syntaxLoaded={syntaxLoaded}
  221. />
  222. {error ? <div className="prom-query-field-info text-error">{error}</div> : null}
  223. {hint ? (
  224. <div className="prom-query-field-info text-warning">
  225. {hint.label}{' '}
  226. {hint.fix ? (
  227. <a className="text-link muted" onClick={this.onClickHintFix}>
  228. {hint.fix.label}
  229. </a>
  230. ) : null}
  231. </div>
  232. ) : null}
  233. </div>
  234. </div>
  235. );
  236. }
  237. }
  238. export default PromQueryField;