import { css, cx } from '@emotion/css'; import type * as monacoType from 'monaco-editor/esm/vs/editor/editor.api'; import React, { useCallback, useRef } from 'react'; import { CodeEditor, getInputStyles, Monaco, useTheme2 } from '@grafana/ui'; import { DynamicLabelsCompletionItemProvider } from '../dynamic-labels/CompletionItemProvider'; import language from '../dynamic-labels/definition'; import { TRIGGER_SUGGEST } from '../monarch/commands'; import { registerLanguage } from '../monarch/register'; const dynamicLabelsCompletionItemProvider = new DynamicLabelsCompletionItemProvider(); export interface Props { onChange: (query: string) => void; onRunQuery: () => void; label: string; width: number; } export function DynamicLabelsField({ label, width, onChange, onRunQuery }: Props) { const theme = useTheme2(); const styles = getInputStyles({ theme, width }); const containerRef = useRef(null); const onEditorMount = useCallback( (editor: monacoType.editor.IStandaloneCodeEditor, monaco: Monaco) => { editor.onDidFocusEditorText(() => editor.trigger(TRIGGER_SUGGEST.id, TRIGGER_SUGGEST.id, {})); editor.addCommand(monaco.KeyMod.Shift | monaco.KeyCode.Enter, () => { const text = editor.getValue(); onChange(text); onRunQuery(); }); const containerDiv = containerRef.current; containerDiv !== null && editor.layout({ width: containerDiv.clientWidth, height: containerDiv.clientHeight }); }, [onChange, onRunQuery] ); return (
{ if (value !== label) { onChange(value); onRunQuery(); } }} onBeforeEditorMount={(monaco: Monaco) => registerLanguage(monaco, language, dynamicLabelsCompletionItemProvider) } onEditorDidMount={onEditorMount} />
); }