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