-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathutils.ts
More file actions
53 lines (45 loc) · 1.54 KB
/
utils.ts
File metadata and controls
53 lines (45 loc) · 1.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import { BaseQuickwitDataSource } from "./base";
import { useState, useEffect, useCallback } from "react";
import{ MetricFindValue } from '@grafana/data';
/**
* Provide suggestions based on datasource fields
*/
export type Suggestion = {
from: number,
options: Array<{
label: string,
detail?: string,
type?: string,
}>
}
export function useDatasourceFields(datasource: BaseQuickwitDataSource) {
const [fields, setFields] = useState<MetricFindValue[]>([]);
useEffect(() => {
if (datasource.getTagKeys) {
datasource.getTagKeys({ searchable: true }).then(setFields);
}
}, [datasource, setFields]);
const getSuggestions = useCallback(async (word: string): Promise<Suggestion> => {
let suggestions: Suggestion = { from: 0, options: [] };
const wordIsField = word.match(/([^:\s]+):'?([^'\s]*)'?/);
if (wordIsField?.length) {
const [_match, fieldName, _fieldValue] = wordIsField;
const candidateValues = await datasource.getTagValues({ key: fieldName });
suggestions.from = fieldName.length + 1; // Replace only the value part
suggestions.options = candidateValues.map(v => ({
type: 'text',
label: typeof v.text === 'number' ? `${v.text}` : `'${v.text}'`
}));
} else {
const candidateFields = fields;
suggestions.from = 0;
suggestions.options = candidateFields.map(f => ({
type: 'variable',
label: f.text,
detail: `${f.value}`
}));
}
return suggestions;
}, [datasource, fields]);
return {fields, getSuggestions}
}