SQLCodeEditor.tsx 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import type * as monacoType from 'monaco-editor/esm/vs/editor/editor.api';
  2. import React, { FunctionComponent, useCallback, useEffect } from 'react';
  3. import { CodeEditor, Monaco } from '@grafana/ui';
  4. import language from '../cloudwatch-sql/definition';
  5. import { CloudWatchDatasource } from '../datasource';
  6. import { TRIGGER_SUGGEST } from '../monarch/commands';
  7. import { registerLanguage } from '../monarch/register';
  8. export interface Props {
  9. region: string;
  10. sql: string;
  11. onChange: (sql: string) => void;
  12. onRunQuery: () => void;
  13. datasource: CloudWatchDatasource;
  14. }
  15. export const SQLCodeEditor: FunctionComponent<Props> = ({ region, sql, onChange, onRunQuery, datasource }) => {
  16. useEffect(() => {
  17. datasource.sqlCompletionItemProvider.setRegion(region);
  18. }, [region, datasource]);
  19. const onEditorMount = useCallback(
  20. (editor: monacoType.editor.IStandaloneCodeEditor, monaco: Monaco) => {
  21. editor.onDidFocusEditorText(() => editor.trigger(TRIGGER_SUGGEST.id, TRIGGER_SUGGEST.id, {}));
  22. editor.addCommand(monaco.KeyMod.Shift | monaco.KeyCode.Enter, () => {
  23. const text = editor.getValue();
  24. onChange(text);
  25. onRunQuery();
  26. });
  27. },
  28. [onChange, onRunQuery]
  29. );
  30. return (
  31. <CodeEditor
  32. height={'150px'}
  33. language={language.id}
  34. value={sql}
  35. onBlur={(value) => {
  36. if (value !== sql) {
  37. onChange(value);
  38. }
  39. }}
  40. showMiniMap={false}
  41. showLineNumbers={true}
  42. onBeforeEditorMount={(monaco: Monaco) => registerLanguage(monaco, language, datasource.sqlCompletionItemProvider)}
  43. onEditorDidMount={onEditorMount}
  44. />
  45. );
  46. };