/
CodeEditor.js
236 lines (216 loc) · 7.36 KB
/
CodeEditor.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
import React, {useEffect, useMemo, useRef, useState} from "react";
import {Box, Button, useClipboard} from "@chakra-ui/react";
import useWindowDimensions from "../utils/windowDimension";
import {saveTextAsFile} from "../utils/download";
import Editor from "@monaco-editor/react";
export const CodeEditor = (
dataCallback,
readOnly = false,
fullFileName = "json_field.json",
languages = ["json"],
defaultWidthPx = 500,
defaultState = languages.includes("json") ? "{\n}" : "",
autoFormat = false,
lineNumbers = false,
id = 0,
showCopyButton = true,
showDownloadButton = true,
showFormatButton = true,
buttonSizes = "sm",
border = "1px"
) => {
// https://github.com/microsoft/monaco-editor/blob/main/webpack-plugin/README.md#options
const [value, setValue] = useState(defaultState)
const contentClipboard = useClipboard("");
const monacoRef = useRef(null);
const dimensions = useWindowDimensions();
const originalReadOnlySetting = useRef(readOnly)
const [readOnlySetting, setReadOnlySetting] = useState(readOnly)
const [formatCode, setFormatCode] = useState(false)
const [monacoReadOnlySettingHasChanged, setMonacoReadOnlySettingHasChangedHasChanged] = useState(false)
// TODO: This could lead to bugs in the future:
// This number depends on the version of Monaco! Use actual enum instead.
const monacoReadOnlyEnumId = 86;
// TODO: Add a promise to getEditor()
const getEditor = () => {
if (!monacoRef.current) return null;
return monacoRef.current.editor.getEditors()[id];
}
const defineAndSetTheme = (name, data) => {
monacoRef.current.editor.defineTheme(name, data);
monacoRef.current.editor.setTheme(name);
}
const isEditorReadOnly = () => {
try {
return getEditor().getOption(monacoReadOnlyEnumId)
} catch (e) {
return undefined
}
}
function attachOptionsChangeListener() {
getEditor().onDidChangeConfiguration((event) => {
if (event.hasChanged(monacoReadOnlyEnumId)) {
setMonacoReadOnlySettingHasChangedHasChanged(true)
}
});
}
useEffect(() => {
if (getEditor()) {
getEditor().updateOptions({
readOnly: readOnlySetting,
})
}
}, [readOnlySetting])
useEffect(() => {
if (formatCode) {
if (isEditorReadOnly()) {
setReadOnlySetting(false)
} else {
if (getEditor()) {
getEditor()
.getAction('editor.action.formatDocument')
.run()
.then(() => {
setReadOnlySetting(originalReadOnlySetting.current)
setFormatCode(false)
});
}
}
}
}, [formatCode, monacoReadOnlySettingHasChanged])
// Start by manually setting the content of the editor. From hereafter user interaction will update it:
useEffect(() => {
handleEditorChange(value)
}, [])
useEffect(() => {
contentClipboard.setValue(value)
// Resize view on content change
updateWindowHeightBasedOnContent();
}, [value])
// Resize view on window change
useEffect(() => {
if (getEditor()) {
getEditor().layout({width: defaultWidthPx, height: getEditor().getContentHeight()});
getEditor().layout()
}
}, [dimensions])
const updateWindowHeightBasedOnContent = () => {
if (getEditor()) {
const contentHeight = Math.min(1000, getEditor().getContentHeight());
getEditor().layout({width: defaultWidthPx, height: contentHeight});
getEditor().layout()
}
};
function handleEditorChange(value) {
setValue(value)
dataCallback(value)
}
function handleEditorDidMount(editor, monaco) {
monacoRef.current = monaco;
updateWindowHeightBasedOnContent();
attachOptionsChangeListener()
if (autoFormat) handleCodeFormat();
defineAndSetTheme('kurtosisTheme', {
base: 'vs-dark',
inherit: true,
rules: [],
colors: {
'editor.background': '#171923',
},
});
}
function handleDownload() {
saveTextAsFile(value, fullFileName)
}
function handleCodeFormat() {
setFormatCode(true)
}
// TODO: We can use this to display error messages
// function handleEditorValidation(markers) {
// // model markers
// // markers.forEach(marker => console.log('onValidate:', marker.message));
// }
const isNotFormattable = () => {
return !languages.includes("json")
}
const highlightLineOption = (readOnly) => {
if (readOnly) {
return "none"
} else {
return "line"
}
}
const scrollbarOption = (readOnly) => {
if (readOnly) {
return 0
} else {
return 10
}
}
return (
<Box
border={border}
borderColor='gray.700'
borderRadius="7"
margin={"1px"}
padding={1}
>
<Editor
margin={1}
defaultLanguage="json"
value={value}
theme={"vs-dark"}
onMount={handleEditorDidMount}
onChange={handleEditorChange}
// onValidate={handleEditorValidation}
options={{
automaticLayout: false, // if this is `true` a ResizeObserver is installed. This causes issues with us managing the container size outside.
selectOnLineNumbers: lineNumbers,
lineNumbers: lineNumbers,
languages: languages,
readOnly: readOnlySetting,
minimap: {
enabled: false
},
scrollBeyondLastLine: false,
scrollbar: {
verticalScrollbarSize: scrollbarOption(readOnly),
},
renderLineHighlight: highlightLineOption(readOnly),
}}
/>
<Box
marginTop={1}
>
{showCopyButton && (
<Button
margin={1}
onClick={contentClipboard.onCopy}
size={buttonSizes}
>
{contentClipboard.hasCopied ? "Copied!" : "Copy"}
</Button>
)}
{showDownloadButton && (
<Button
margin={1}
onClick={handleDownload}
size={buttonSizes}
>
Download
</Button>
)}
{showFormatButton && (
<Button
margin={1}
onClick={handleCodeFormat}
isDisabled={isNotFormattable()}
size={buttonSizes}
>
Format
</Button>
)}
</Box>
</Box>
)
}