-
-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathCodeEditor.tsx
238 lines (215 loc) · 6.24 KB
/
CodeEditor.tsx
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
237
238
import CodeMirror, {
type ReactCodeMirrorProps,
type ReactCodeMirrorRef,
} from '@uiw/react-codemirror'
import { StreamLanguage } from '@codemirror/language'
import { parse } from '@prantlf/jsonlint'
import { linter, type Diagnostic } from '@codemirror/lint'
import { useMemo, useRef, useState } from 'react'
import {
ClipboardDocumentCheckIcon,
ClipboardIcon,
XCircleIcon,
} from '@heroicons/react/20/solid'
import { json } from '@codemirror/lang-json'
import { html } from '@codemirror/lang-html'
import { css } from '@codemirror/lang-css'
import { xml } from '@codemirror/lang-xml'
import { sql, PostgreSQL, type SQLConfig } from '@codemirror/lang-sql'
import { spreadsheet } from '@codemirror/legacy-modes/mode/spreadsheet'
import type { EditorView } from '@codemirror/view'
import { copyToClipboard } from '../../lib/utils/copy-to-clipboard'
import { formatJSON } from '../../lib/utils'
interface Props extends ReactCodeMirrorProps {
contentType: string
includeLinters?: boolean
enableCopy?: boolean
sqlSchema?: SQLConfig['schema']
}
function getLineNumber(str: string, index: number) {
let lineNumber = 1
for (let i = 0; i < index; i++) {
if (str[i] === '\n') {
lineNumber++
}
}
return lineNumber
}
function getErrorPosition(
text: string,
lineNum: number,
colNum: number,
): number {
const lines = text.split('\n')
const lineIdx = lineNum - 1
const line = lines[lineIdx].substring(0, colNum)
const prevLinesLength = lines.slice(0, lineIdx).join('\n').length
return prevLinesLength + line.length
}
// Define a custom JSON linter function that uses jsonlint
const jsonLinter = (view: EditorView): Diagnostic[] => {
const errors: Diagnostic[] = []
const value = view.state.doc.toString()
if (!value.trim()) return []
try {
parse(value, {
allowDuplicateObjectKeys: false,
allowSingleQuotedStrings: false,
})
} catch (e: any) {
const errorLocation = e.message.match(/line (\d+), column (\d+)/)
const lineNum = parseInt(errorLocation[1], 10)
const colNum = parseInt(errorLocation[2], 10)
const pos = getErrorPosition(value, lineNum, colNum)
return [
{
from: pos,
message: e.reason,
severity: 'error',
to: pos,
actions: [],
},
]
}
return errors
}
const CodeEditor: React.FC<Props> = ({
contentType,
content,
readOnly,
includeLinters,
onChange,
enableCopy,
sqlSchema,
...props
}) => {
const editor = useRef<ReactCodeMirrorRef>(null)
const [errors, setErrors] = useState<Diagnostic[]>([])
const [copied, setCopied] = useState(false)
const timeoutRef = useRef<any>()
const handleCopyCode = () => {
copyToClipboard(`${props.value}`.trim())
setCopied(true)
if (timeoutRef.current) {
clearTimeout(timeoutRef.current)
}
timeoutRef.current = setTimeout(() => {
setCopied(false)
timeoutRef.current = null
}, 1000)
}
const extensions = useMemo(() => {
switch (contentType) {
case 'text/html':
return [html()]
case 'text/csv':
return [StreamLanguage.define(spreadsheet)]
case 'text/css':
return [css()]
case 'text/sql':
return [
sql({
dialect: PostgreSQL,
schema: sqlSchema,
}),
]
case 'text/xml':
case 'application/xml':
return [xml()]
case 'application/json':
return includeLinters ? [json(), linter(jsonLinter)] : [json()]
}
return []
}, [contentType, sqlSchema])
const handleOnChange: ReactCodeMirrorProps['onChange'] = (
value,
viewUpdate,
) => {
if (typeof onChange === 'function') {
// check validate
if (includeLinters && contentType === 'application/json') {
const errors = jsonLinter(viewUpdate.view)
setErrors(errors)
if (errors.length) {
return // don't update state if in error
}
}
onChange(value, viewUpdate)
}
}
const handleFormat = () => {
if (editor.current?.view && props.value) {
const { view } = editor.current
view.dispatch({
changes: {
from: 0,
to: view.state.doc.length,
insert: formatJSON(view.state.doc.toString()),
},
})
}
}
return (
<div className="relative">
{enableCopy ? (
<button
aria-label="Copy Code"
data-testid="copy-code"
className="absolute right-0 top-0 z-50 m-4 h-4 w-4 text-foreground hover:text-accent-foreground"
onClick={handleCopyCode}
>
{copied ? <ClipboardDocumentCheckIcon /> : <ClipboardIcon />}
</button>
) : null}
{!readOnly && contentType === 'application/json' && (
<div className="flex rounded-lg py-2">
<button
onClick={handleFormat}
type="button"
className="ml-auto rounded bg-background px-2 py-1 text-xs font-semibold text-foreground shadow-sm ring-1 ring-inset ring-border hover:bg-accent"
>
Format
</button>
</div>
)}
<div className="overflow-hidden rounded-lg shadow-md">
<CodeMirror
ref={editor}
height="350px"
theme="dark"
basicSetup={{
foldGutter: true,
lineNumbers: true,
}}
editable={!readOnly}
readOnly={readOnly}
extensions={extensions}
onChange={handleOnChange}
{...props}
/>
{errors.length > 0 && (
<div className="absolute bottom-0 right-0 m-2 rounded-md bg-destructive/10 p-2.5">
<div className="flex items-center">
<div className="flex-shrink-0">
<XCircleIcon
className="h-5 w-5 text-destructive"
aria-hidden="true"
/>
</div>
<div className="ml-1">
<div className="text-sm text-destructive">
Error Invalid JSON at line{' '}
{getLineNumber(
editor.current?.view?.state.doc.toString() || '',
errors[0].from,
)}
</div>
</div>
</div>
</div>
)}
</div>
</div>
)
}
export default CodeEditor