SqlEditor.tsx 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. import Editor, { OnChange, useMonaco } from '@monaco-editor/react'
  2. import { noop } from 'lodash'
  3. import { useEffect, useRef } from 'react'
  4. import { LogoLoader } from 'ui'
  5. import { formatSql } from '@/lib/formatSql'
  6. // [Joshen] We should deprecate this and use CodeEditor instead
  7. interface SqlEditorProps {
  8. contextmenu?: boolean
  9. defaultValue?: string
  10. language?: string
  11. onInputChange?: OnChange
  12. queryId?: string
  13. readOnly?: boolean
  14. }
  15. /**
  16. * @deprecated Use CodeEditor instead
  17. */
  18. const SqlEditor = ({
  19. queryId,
  20. language = 'pgsql',
  21. defaultValue = '',
  22. readOnly = false,
  23. contextmenu = true,
  24. onInputChange = noop,
  25. }: SqlEditorProps) => {
  26. const monaco = useMonaco()
  27. const editorRef = useRef<any>(null)
  28. useEffect(() => {
  29. if (monaco) {
  30. // Enable pgsql format
  31. const formatprovider = monaco.languages.registerDocumentFormattingEditProvider('pgsql', {
  32. async provideDocumentFormattingEdits(model: any) {
  33. const value = model.getValue()
  34. const formatted = formatSql(value)
  35. return [
  36. {
  37. range: model.getFullModelRange(),
  38. text: formatted,
  39. },
  40. ]
  41. },
  42. })
  43. return () => {
  44. formatprovider.dispose()
  45. }
  46. }
  47. }, [monaco])
  48. useEffect(() => {
  49. if (editorRef.current) {
  50. // add margin above first line
  51. editorRef.current?.changeViewZones((accessor: any) => {
  52. accessor.addZone({
  53. afterLineNumber: 0,
  54. heightInPx: 4,
  55. domNode: document.createElement('div'),
  56. })
  57. })
  58. }
  59. }, [queryId])
  60. const onMount = (editor: any, _monaco: any) => {
  61. editorRef.current = editor
  62. // Add margin above first line
  63. editor.changeViewZones((accessor: any) => {
  64. accessor.addZone({
  65. afterLineNumber: 0,
  66. heightInPx: 4,
  67. domNode: document.createElement('div'),
  68. })
  69. })
  70. }
  71. return (
  72. <Editor
  73. className="monaco-editor"
  74. theme="briven"
  75. defaultLanguage={language}
  76. defaultValue={defaultValue}
  77. path={queryId}
  78. loading={<LogoLoader />}
  79. options={{
  80. readOnly,
  81. tabSize: 2,
  82. fontSize: 13,
  83. minimap: {
  84. enabled: false,
  85. },
  86. wordWrap: 'on',
  87. fixedOverflowWidgets: true,
  88. contextmenu: contextmenu,
  89. }}
  90. onMount={onMount}
  91. onChange={onInputChange}
  92. />
  93. )
  94. }
  95. export default SqlEditor