2022-04-22 21:33:13 +08:00
|
|
|
import React, { useState } from 'react';
|
|
|
|
|
2022-03-29 23:49:21 +08:00
|
|
|
import { DataSourceApi, SelectableValue, toOption } from '@grafana/data';
|
2022-01-31 14:57:14 +08:00
|
|
|
import { Select } from '@grafana/ui';
|
2022-04-22 21:33:13 +08:00
|
|
|
|
2022-01-31 14:57:14 +08:00
|
|
|
import { promQueryModeller } from '../PromQueryModeller';
|
2022-02-16 15:05:16 +08:00
|
|
|
import { getOperationParamId } from '../shared/operationUtils';
|
2022-03-29 23:49:21 +08:00
|
|
|
import { QueryBuilderLabelFilter, QueryBuilderOperationParamEditorProps } from '../shared/types';
|
2022-01-31 14:57:14 +08:00
|
|
|
import { PromVisualQuery } from '../types';
|
|
|
|
|
2022-02-16 15:05:16 +08:00
|
|
|
export function LabelParamEditor({
|
|
|
|
onChange,
|
|
|
|
index,
|
2023-09-06 16:25:53 +08:00
|
|
|
operationId,
|
2022-02-16 15:05:16 +08:00
|
|
|
value,
|
|
|
|
query,
|
|
|
|
datasource,
|
|
|
|
}: QueryBuilderOperationParamEditorProps) {
|
2022-01-31 14:57:14 +08:00
|
|
|
const [state, setState] = useState<{
|
2023-10-06 18:48:15 +08:00
|
|
|
options?: SelectableValue[];
|
2022-01-31 14:57:14 +08:00
|
|
|
isLoading?: boolean;
|
|
|
|
}>({});
|
|
|
|
|
|
|
|
return (
|
|
|
|
<Select
|
2023-09-06 16:25:53 +08:00
|
|
|
inputId={getOperationParamId(operationId, index)}
|
2022-01-31 14:57:14 +08:00
|
|
|
autoFocus={value === '' ? true : undefined}
|
|
|
|
openMenuOnFocus
|
|
|
|
onOpenMenu={async () => {
|
|
|
|
setState({ isLoading: true });
|
2022-03-29 23:49:21 +08:00
|
|
|
const options = await loadGroupByLabels(query, datasource);
|
2022-01-31 14:57:14 +08:00
|
|
|
setState({ options, isLoading: undefined });
|
|
|
|
}}
|
|
|
|
isLoading={state.isLoading}
|
|
|
|
allowCustomValue
|
|
|
|
noOptionsMessage="No labels found"
|
|
|
|
loadingMessage="Loading labels"
|
|
|
|
options={state.options}
|
|
|
|
value={toOption(value as string)}
|
|
|
|
onChange={(value) => onChange(index, value.value!)}
|
|
|
|
/>
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2023-10-06 18:48:15 +08:00
|
|
|
async function loadGroupByLabels(query: PromVisualQuery, datasource: DataSourceApi): Promise<SelectableValue[]> {
|
2022-03-29 23:49:21 +08:00
|
|
|
let labels: QueryBuilderLabelFilter[] = query.labels;
|
|
|
|
|
2022-05-24 23:43:58 +08:00
|
|
|
// This function is used by both Prometheus and Loki and this the only difference.
|
|
|
|
if (datasource.type === 'prometheus') {
|
2022-03-29 23:49:21 +08:00
|
|
|
labels = [{ label: '__name__', op: '=', value: query.metric }, ...query.labels];
|
|
|
|
}
|
2022-01-31 14:57:14 +08:00
|
|
|
|
2022-03-29 23:49:21 +08:00
|
|
|
const expr = promQueryModeller.renderLabels(labels);
|
2022-01-31 14:57:14 +08:00
|
|
|
const result = await datasource.languageProvider.fetchSeriesLabels(expr);
|
|
|
|
|
|
|
|
return Object.keys(result).map((x) => ({
|
|
|
|
label: x,
|
|
|
|
value: x,
|
|
|
|
}));
|
|
|
|
}
|