forked from grafana/grafana
-
Notifications
You must be signed in to change notification settings - Fork 0
/
autocomplete.ts
437 lines (388 loc) · 14.3 KB
/
autocomplete.ts
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
import { SelectableValue } from '@grafana/data';
import type { Monaco, monacoTypes } from '@grafana/ui';
import TempoLanguageProvider from '../language_provider';
interface Props {
languageProvider: TempoLanguageProvider;
}
/**
* Class that implements CompletionItemProvider interface and allows us to provide suggestion for the Monaco
* autocomplete system.
*/
export class CompletionProvider implements monacoTypes.languages.CompletionItemProvider {
languageProvider: TempoLanguageProvider;
constructor(props: Props) {
this.languageProvider = props.languageProvider;
}
triggerCharacters = ['{', '.', '[', '(', '=', '~', ' ', '"'];
static readonly intrinsics: string[] = ['duration', 'name', 'status'];
static readonly scopes: string[] = ['resource', 'span'];
static readonly operators: string[] = ['=', '-', '+', '<', '>', '>=', '<=', '=~'];
static readonly logicalOps: string[] = ['&&', '||'];
// We set these directly and ae required for the provider to function.
monaco: Monaco | undefined;
editor: monacoTypes.editor.IStandaloneCodeEditor | undefined;
private tags: { [tag: string]: Set<string> } = {};
private cachedValues: { [key: string]: Array<SelectableValue<string>> } = {};
provideCompletionItems(
model: monacoTypes.editor.ITextModel,
position: monacoTypes.Position
): monacoTypes.languages.ProviderResult<monacoTypes.languages.CompletionList> {
// Should not happen, this should not be called before it is initialized
if (!(this.monaco && this.editor)) {
throw new Error('provideCompletionItems called before CompletionProvider was initialized');
}
// if the model-id does not match, then this call is from a different editor-instance,
// not "our instance", so return nothing
if (this.editor.getModel()?.id !== model.id) {
return { suggestions: [] };
}
const { range, offset } = getRangeAndOffset(this.monaco, model, position);
const situation = this.getSituation(model.getValue(), offset);
const completionItems = this.getCompletions(situation);
return completionItems.then((items) => {
// monaco by-default alphabetically orders the items.
// to stop it, we use a number-as-string sortkey,
// so that monaco keeps the order we use
const maxIndexDigits = items.length.toString().length;
const suggestions: monacoTypes.languages.CompletionItem[] = items.map((item, index) => {
const suggestion = {
kind: getMonacoCompletionItemKind(item.type, this.monaco!),
label: item.label,
insertText: item.insertText,
sortText: index.toString().padStart(maxIndexDigits, '0'), // to force the order we have
range,
};
fixSuggestion(suggestion, item.type, model, offset, this.monaco!);
return suggestion;
});
return { suggestions };
});
}
/**
* We expect the tags list data directly from the request and assign it an empty set here.
*/
setTags(tags: string[]) {
tags.forEach((t) => (this.tags[t] = new Set<string>()));
}
private overrideTagName(tagName: string): string {
switch (tagName) {
case 'status':
return 'status.code';
default:
return tagName;
}
}
private async getTagValues(tagName: string): Promise<Array<SelectableValue<string>>> {
let tagValues: Array<SelectableValue<string>> = [];
if (this.cachedValues.hasOwnProperty(tagName)) {
tagValues = this.cachedValues[tagName];
} else {
tagValues = await this.languageProvider.getOptions(tagName);
this.cachedValues[tagName] = tagValues;
}
return tagValues;
}
/**
* Get suggestion based on the situation we are in like whether we should suggest tag names or values.
* @param situation
* @private
*/
private async getCompletions(situation: Situation): Promise<Completion[]> {
if (!Object.keys(this.tags).length) {
return [];
}
switch (situation.type) {
// Not really sure what would make sense to suggest in this case so just leave it
case 'UNKNOWN': {
return [];
}
case 'EMPTY': {
return this.getScopesCompletions('{ ')
.concat(this.getIntrinsicsCompletions('{ '))
.concat(this.getTagsCompletions('{ .'));
}
case 'SPANSET_EMPTY':
return this.getScopesCompletions().concat(this.getIntrinsicsCompletions()).concat(this.getTagsCompletions('.'));
case 'SPANSET_ONLY_DOT': {
return this.getTagsCompletions();
}
case 'SPANSET_IN_NAME':
return this.getScopesCompletions().concat(this.getIntrinsicsCompletions()).concat(this.getTagsCompletions());
case 'SPANSET_IN_NAME_SCOPE':
return this.getTagsCompletions();
case 'SPANSET_AFTER_NAME':
return CompletionProvider.operators.map((key) => ({
label: key,
insertText: key,
type: 'OPERATOR' as CompletionType,
}));
case 'SPANSET_IN_VALUE':
const tagName = this.overrideTagName(situation.tagName);
const tagsNoQuotesAroundValue: string[] = ['status'];
const tagValues = await this.getTagValues(tagName);
const items: Completion[] = [];
const getInsertionText = (val: SelectableValue<string>): string => {
if (situation.betweenQuotes) {
return val.label!;
}
return tagsNoQuotesAroundValue.includes(situation.tagName) ? val.label! : `"${val.label}"`;
};
tagValues.forEach((val) => {
if (val?.label) {
items.push({
label: val.label,
insertText: getInsertionText(val),
type: 'TAG_VALUE',
});
}
});
return items;
case 'SPANSET_AFTER_VALUE':
return CompletionProvider.logicalOps.concat('}').map((key) => ({
label: key,
insertText: key,
type: 'OPERATOR' as CompletionType,
}));
default:
throw new Error(`Unexpected situation ${situation}`);
}
}
private getTagsCompletions(prepend?: string): Completion[] {
return Object.keys(this.tags)
.sort((a, b) => a.localeCompare(b, undefined, { sensitivity: 'accent' }))
.map((key) => ({
label: key,
insertText: (prepend || '') + key,
type: 'TAG_NAME' as CompletionType,
}));
}
private getIntrinsicsCompletions(prepend?: string): Completion[] {
return CompletionProvider.intrinsics.map((key) => ({
label: key,
insertText: (prepend || '') + key,
type: 'KEYWORD' as CompletionType,
}));
}
private getScopesCompletions(prepend?: string): Completion[] {
return CompletionProvider.scopes.map((key) => ({
label: key,
insertText: (prepend || '') + key,
type: 'SCOPE' as CompletionType,
}));
}
private getSituationInSpanSet(textUntilCaret: string): Situation {
const nameRegex = /(?<name>[\w./-]+)?/;
const opRegex = /(?<op>[!=+\-<>]+)/;
// only allow spaces in the value if it's enclosed by quotes
const valueRegex = /(?<value>(?<open_quote>")([^"\n&|]+)?(?<close_quote>")?|([^"\n\s&|]+))?/;
// prettier-ignore
const fullRegex = new RegExp(
'([\\s{])' + // Space(s) or initial opening bracket {
'(' + // Open full set group
nameRegex.source +
'(?<space1>\\s*)' + // Optional space(s) between name and operator
'(' + // Open operator + value group
opRegex.source +
'(?<space2>\\s*)' + // Optional space(s) between operator and value
valueRegex.source +
')?' + // Close operator + value group
')' + // Close full set group
'(?<space3>\\s*)$' // Optional space(s) at the end of the set
);
const matched = textUntilCaret.match(fullRegex);
if (matched) {
const nameFull = matched.groups?.name;
const op = matched.groups?.op;
if (!nameFull) {
return {
type: 'SPANSET_EMPTY',
};
}
if (nameFull === '.') {
return {
type: 'SPANSET_ONLY_DOT',
};
}
const nameMatched = nameFull.match(/^(?<pre_dot>\.)?(?<word>\w[\w./-]*\w)(?<post_dot>\.)?$/);
// We already have a (potentially partial) tag name so let's check if there's an operator declared
// { .tag_name|
if (!op) {
// There's no operator so we check if the name is one of the known scopes
// { resource.|
if (CompletionProvider.scopes.filter((w) => w === nameMatched?.groups?.word) && nameMatched?.groups?.post_dot) {
return {
type: 'SPANSET_IN_NAME_SCOPE',
};
}
// It's not one of the scopes, so we now check if we're after the name (there's a space after the word) or if we still have to autocomplete the rest of the name
// In case there's a space we start autocompleting the operators { .http.method |
// Otherwise we keep showing the tags/intrinsics/scopes list { .http.met|
return {
type: matched.groups?.space1 ? 'SPANSET_AFTER_NAME' : 'SPANSET_IN_NAME',
};
}
// In case there's a space after the full [name + operator + value] group we can start autocompleting logical operators or close the spanset
// To avoid triggering this situation when we are writing a space inside a string we check the state of the open and close quotes
// { .http.method = "GET" |
if (matched.groups?.space3 && matched.groups.open_quote === matched.groups.close_quote) {
return {
type: 'SPANSET_AFTER_VALUE',
};
}
// remove the scopes from the word to get accurate autocompletes
// Ex: 'span.host.name' won't resolve to any autocomplete values, but removing 'span.' results in 'host.name' which can have autocomplete values
const noScopeWord = CompletionProvider.scopes.reduce(
(result, word) => result.replace(`${word}.`, ''),
nameMatched?.groups?.word || ''
);
// We already have an operator and know that the set isn't complete so let's autocomplete the possible values for the tag name
// { .http.method = |
return {
type: 'SPANSET_IN_VALUE',
tagName: noScopeWord,
betweenQuotes: !!matched.groups?.open_quote,
};
}
return {
type: 'EMPTY',
};
}
/**
* Figure out where is the cursor and what kind of suggestions are appropriate.
* @param text
* @param offset
*/
private getSituation(text: string, offset: number): Situation {
if (text === '' || offset === 0) {
return {
type: 'EMPTY',
};
}
const textUntilCaret = text.substring(0, offset);
// Check if we're inside a span set
let isInSpanSet = textUntilCaret.lastIndexOf('{') > textUntilCaret.lastIndexOf('}');
if (isInSpanSet) {
return this.getSituationInSpanSet(textUntilCaret);
}
// Will happen only if user writes something that isn't really a tag selector
return {
type: 'UNKNOWN',
};
}
}
/**
* Get item kind which is used for icon next to the suggestion.
* @param type
* @param monaco
*/
function getMonacoCompletionItemKind(type: CompletionType, monaco: Monaco): monacoTypes.languages.CompletionItemKind {
switch (type) {
case 'TAG_NAME':
return monaco.languages.CompletionItemKind.Enum;
case 'KEYWORD':
return monaco.languages.CompletionItemKind.Keyword;
case 'OPERATOR':
return monaco.languages.CompletionItemKind.Operator;
case 'TAG_VALUE':
return monaco.languages.CompletionItemKind.EnumMember;
case 'SCOPE':
return monaco.languages.CompletionItemKind.Class;
default:
throw new Error(`Unexpected CompletionType: ${type}`);
}
}
export type CompletionType = 'TAG_NAME' | 'TAG_VALUE' | 'KEYWORD' | 'OPERATOR' | 'SCOPE';
type Completion = {
type: CompletionType;
label: string;
insertText: string;
};
export type Tag = {
name: string;
value: string;
};
export type Situation =
| {
type: 'UNKNOWN';
}
| {
type: 'EMPTY';
}
| {
type: 'SPANSET_EMPTY';
}
| {
type: 'SPANSET_ONLY_DOT';
}
| {
type: 'SPANSET_AFTER_NAME';
}
| {
type: 'SPANSET_IN_NAME';
}
| {
type: 'SPANSET_IN_NAME_SCOPE';
}
| {
type: 'SPANSET_IN_VALUE';
tagName: string;
betweenQuotes: boolean;
}
| {
type: 'SPANSET_AFTER_VALUE';
};
function getRangeAndOffset(monaco: Monaco, model: monacoTypes.editor.ITextModel, position: monacoTypes.Position) {
const word = model.getWordAtPosition(position);
const range =
word != null
? monaco.Range.lift({
startLineNumber: position.lineNumber,
endLineNumber: position.lineNumber,
startColumn: word.startColumn,
endColumn: word.endColumn,
})
: monaco.Range.fromPositions(position);
// documentation says `position` will be "adjusted" in `getOffsetAt` so we clone it here just for sure.
const positionClone = {
column: position.column,
lineNumber: position.lineNumber,
};
const offset = model.getOffsetAt(positionClone);
return { offset, range };
}
/**
* Fix the suggestions range and insert text. For the range we have to adjust because monaco by default replaces just
* the last word which stops at dot while traceQL tags contain dots themselves and we want to replace the whole tag
* name when suggesting. The insert text needs to be adjusted for scope (leading dot) if scope is currently missing.
* This may be doable also when creating the suggestions but for a particular situation this seems to be easier to do
* here.
*/
function fixSuggestion(
suggestion: monacoTypes.languages.CompletionItem & { range: monacoTypes.IRange },
itemType: CompletionType,
model: monacoTypes.editor.ITextModel,
offset: number,
monaco: Monaco
) {
if (itemType === 'TAG_NAME') {
const match = model
.getValue()
.substring(0, offset)
.match(/(span\.|resource\.|\.)?([\w./-]*)$/);
if (match) {
const scope = match[1];
const tag = match[2];
if (tag) {
// Add the default scope if needed.
if (!scope && suggestion.insertText[0] !== '.') {
suggestion.insertText = '.' + suggestion.insertText;
}
// Adjust the range, so that we will replace the whole tag.
suggestion.range = monaco.Range.lift({
...suggestion.range,
startColumn: offset - tag.length + 1,
});
}
}
}
}