import { FormEvent, useState, useEffect } from 'react'; import { usePrevious } from 'react-use'; import { QueryEditorProps, SelectableValue } from '@grafana/data'; import { InlineField, InlineFieldRow, Input, Select } from '@grafana/ui'; import { LokiDatasource } from '../datasource'; import { migrateVariableQuery } from '../migrations/variableQueryMigrations'; import { LokiOptions, LokiQuery, LokiVariableQuery, LokiVariableQueryType as QueryType } from '../types'; const variableOptions = [ { label: 'Label names', value: QueryType.LabelNames }, { label: 'Label values', value: QueryType.LabelValues }, ]; export type Props = QueryEditorProps; const refId = 'LokiVariableQueryEditor-VariableQuery'; export const LokiVariableQueryEditor = ({ onChange, query, datasource, range }: Props) => { const [type, setType] = useState(undefined); const [label, setLabel] = useState(''); const [labelOptions, setLabelOptions] = useState>>([]); const [stream, setStream] = useState(''); const previousType = usePrevious(type); useEffect(() => { if (!query) { return; } const variableQuery = typeof query === 'string' ? migrateVariableQuery(query) : query; setType(variableQuery.type); setLabel(variableQuery.label || ''); setStream(variableQuery.stream || ''); }, [query]); useEffect(() => { // Fetch label names when the query type is LabelValues, and the previous type was not the same if (type !== QueryType.LabelValues || previousType === type) { return; } datasource.languageProvider.fetchLabels({ timeRange: range }).then((labelNames) => { setLabelOptions(labelNames.map((labelName) => ({ label: labelName, value: labelName }))); }); }, [datasource, type, range, previousType]); const onQueryTypeChange = (newType: SelectableValue) => { setType(newType.value); if (newType.value !== undefined) { onChange({ type: newType.value, label, stream, refId, }); } }; const onLabelChange = (newLabel: SelectableValue) => { setLabel(newLabel.value || ''); }; const onStreamChange = (e: FormEvent) => { setStream(e.currentTarget.value); }; const handleBlur = () => { if (type !== undefined) { onChange({ type, label, stream, refId: 'LokiVariableQueryEditor-VariableQuery' }); } }; return ( <> )} {type === QueryType.LabelValues && ( { 'Optional. If defined, a list of values for the specified log stream selector is returned. For example: {label="value"} or {label="$variable"}' } } > )} ); };