From 927393633c60acf1fabf1a026b5f11661ac03db0 Mon Sep 17 00:00:00 2001 From: Galen Kistler <109082771+gtk-grafana@users.noreply.github.com> Date: Wed, 5 Jul 2023 07:22:23 -0500 Subject: [PATCH] Prometheus: Code editor autocomplete returns bad results when text is highlighted (#70856) * adjust cursor when text is selected to give better autocomplete results in prometheus code editor --- .../monaco-completion-provider/index.ts | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/public/app/plugins/datasource/prometheus/components/monaco-query-field/monaco-completion-provider/index.ts b/public/app/plugins/datasource/prometheus/components/monaco-query-field/monaco-completion-provider/index.ts index 5f44f77adbf..c9dc43ecbbe 100644 --- a/public/app/plugins/datasource/prometheus/components/monaco-query-field/monaco-completion-provider/index.ts +++ b/public/app/plugins/datasource/prometheus/components/monaco-query-field/monaco-completion-provider/index.ts @@ -43,6 +43,7 @@ function getMonacoCompletionItemKind(type: CompletionType, monaco: Monaco): mona throw new NeverCaseError(type); } } + export function getCompletionProvider( monaco: Monaco, dataProvider: DataProvider @@ -63,10 +64,21 @@ export function getCompletionProvider( : monaco.Range.fromPositions(position); // documentation says `position` will be "adjusted" in `getOffsetAt` // i don't know what that means, to be sure i clone it + const positionClone = { column: position.column, lineNumber: position.lineNumber, }; + + // Check to see if the browser supports window.getSelection() + if (window.getSelection) { + const selectedText = window.getSelection()?.toString(); + // If the user has selected text, adjust the cursor position to be at the start of the selection, instead of the end + if (selectedText && selectedText.length > 0) { + positionClone.column = positionClone.column - selectedText.length; + } + } + const offset = model.getOffsetAt(positionClone); const situation = getSituation(model.getValue(), offset); const completionsPromise = situation != null ? getCompletions(situation, dataProvider) : Promise.resolve([]);