-
Notifications
You must be signed in to change notification settings - Fork 0
/
CustomCodeMirror.tsx
437 lines (413 loc) · 16.3 KB
/
CustomCodeMirror.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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
import Box from '@mui/material/Box'
import React from 'react'
import {
lineNumbers, highlightActiveLineGutter, highlightSpecialChars,
drawSelection, dropCursor,
rectangularSelection, highlightActiveLine, keymap,
EditorView, highlightWhitespace, tooltips, highlightTrailingWhitespace,
// crosshairCursor,
} from '@codemirror/view'
import {
foldGutter, indentOnInput, syntaxHighlighting,
defaultHighlightStyle, bracketMatching, foldKeymap,
StreamLanguage, LanguageDescription, LanguageSupport, codeFolding,
} from '@codemirror/language'
import { history, defaultKeymap, historyKeymap, indentWithTab } from '@codemirror/commands'
import { highlightSelectionMatches, searchKeymap } from '@codemirror/search'
import { closeBrackets, autocompletion, closeBracketsKeymap, completionKeymap } from '@codemirror/autocomplete'
import { lintKeymap } from '@codemirror/lint'
import { Compartment, EditorState, Extension } from '@codemirror/state'
import { CodeMirrorComponentProps, CodeMirrorProps } from '@ui-schema/kit-codemirror/CodeMirror'
import { EditorThemeCustomStyles, useEditorTheme } from '@ui-schema/material-code/useEditorTheme'
import { useHighlightStyle } from '@ui-schema/material-code/useHighlightStyle'
import { json } from '@codemirror/lang-json'
import { javascript } from '@codemirror/lang-javascript'
import { html } from '@codemirror/lang-html'
import { css } from '@codemirror/lang-css'
import { python } from '@codemirror/lang-python'
import { wast } from '@codemirror/lang-wast'
import { rust } from '@codemirror/lang-rust'
import { xml } from '@codemirror/lang-xml'
import { php } from '@codemirror/lang-php'
import { MariaSQL, Cassandra, MySQL, PostgreSQL, MSSQL, StandardSQL, sql } from '@codemirror/lang-sql'
import { markdown, markdownLanguage } from '@codemirror/lang-markdown'
import { languages } from '@codemirror/language-data'
import { lezer } from '@codemirror/lang-lezer'
import { sCSS } from '@codemirror/legacy-modes/mode/css'
import { shell } from '@codemirror/legacy-modes/mode/shell'
import { csharp } from '@codemirror/legacy-modes/mode/clike'
import { powerShell } from '@codemirror/legacy-modes/mode/powershell'
import { http } from '@codemirror/legacy-modes/mode/http'
import { yaml } from '@codemirror/legacy-modes/mode/yaml'
import { YAMLFrontMatter, Footnote, Mark, Hashtag, Mention, Insert } from './lezerMarkdown'
import { useCodeMirror, useEditorClasses, useExtension } from '@ui-schema/kit-codemirror'
import { MuiCodeMirrorStyleProps } from '@ui-schema/material-code'
import { useTheme } from '@mui/material/styles'
const mdLang0 = markdown({
base: markdownLanguage,
codeLanguages: [
// adding yaml before `languages`, overwrites the included very-basic yaml language
LanguageDescription.of({
name: 'YAML',
alias: ['yaml', 'yml'],
filename: /.(yaml|yml)$/i,
extensions: ['yaml', 'yml'],
support: new LanguageSupport(StreamLanguage.define(yaml)),
}),
],
extensions: [
//GFM, Subscript, Superscript,
YAMLFrontMatter({allBlocks: true}),
Footnote, Mark, Insert, Hashtag, Mention,
],
/*extensions: [
YAMLFrontMatter,
Footnote,
],*/
})
const mdLang = markdown({
base: markdownLanguage,
codeLanguages: [
// adding yaml before `languages`, overwrites the included very-basic yaml language
LanguageDescription.of({
name: 'YAML',
alias: ['yaml', 'yml'],
filename: /.(yaml|yml)$/i,
extensions: ['yaml', 'yml'],
support: new LanguageSupport(StreamLanguage.define(yaml)),
}),
// todo: solve "markdown highlighting in codeblocks inside markdown",
// didn't seem possible without adding a further one,
// nested fence-codeblocks are impossible due to markdown,
// so that should be enough and the nested MD could even be "without nested code support"
// except for yaml/frontmatter
LanguageDescription.of({
name: 'Markdown',
alias: ['md', 'markdown'],
extensions: ['md'],
support: mdLang0,
}),
...languages,
],
extensions: [
//GFM, Subscript, Superscript,
YAMLFrontMatter({allBlocks: true}),
Footnote, Mark, Insert, Hashtag, Mention,
],
/*extensions: [
YAMLFrontMatter,
Footnote,
],*/
})
export const getHighlight = (lang: string | undefined): Extension | undefined => {
switch(lang?.toLowerCase()) {
case 'json':
case 'json5':
return json()
case 'js':
case 'node':
case 'nodejs':
case 'javascript':
return javascript()
case 'jsx':
return javascript({
jsx: true,
})
case 'ts':
case 'typescript':
return javascript({
typescript: true,
})
case 'tsx':
return javascript({
jsx: true,
typescript: true,
})
case 'twig':
case 'html':
return html()
case 'rss':
case 'wsl':
case 'xsd':
case 'xml':
return xml()
case 'bash':
case 'sh':
case 'zsh':
case 'ksh':
case 'shell':
return StreamLanguage.define(shell)
case 'powershell':
return StreamLanguage.define(powerShell)
case 'c#':
case 'cs':
case 'csharp':
return StreamLanguage.define(csharp)
case 'scss':
case 'sass':
return StreamLanguage.define(sCSS)
case 'http':
return StreamLanguage.define(http)
case 'yml':
case 'yaml':
return StreamLanguage.define(yaml)
case 'css':
return css()
case 'python':
return python()
case 'wast':
return wast()
case 'rust':
return rust()
case 'injectablephp':
case 'php':
return php()
case 'mysql':
return sql({dialect: MySQL})
case 'ms sql':
case 'mssql':
return sql({dialect: MSSQL})
case 'mariasql':
return sql({dialect: MariaSQL})
case 'postgresql':
return sql({dialect: PostgreSQL})
case 'cassandra':
case 'cql':
return sql({dialect: Cassandra})
case 'bigquery':
case 'standardsql':
return sql({dialect: StandardSQL})
case 'sql':
return sql()
case 'md':
case 'markdown':
// return markdown()
return mdLang
case 'lezer':
return lezer()
default:
return undefined
}
}
export type CustomCodeMirrorProps = CodeMirrorComponentProps & MuiCodeMirrorStyleProps & {
dense?: boolean
onViewLifecycle?: CodeMirrorProps['onViewLifecycle']
style?: React.CSSProperties
// containerRef?: React.MutableRefObject<HTMLDivElement | null>
lang?: string
extraMods?: boolean
/**
* @todo implement a user notification, if the first tab in the session, remind to use ESC+TAB
* needs sessionStorage/localStorage
*/
enableTabIndent?: boolean
highlightWhitespaces?: boolean
autoFocus?: boolean | number
paddingBottom?: boolean | number | string
id?: string
/**
* @experimental
*/
enableSpellCheck?: boolean
}
export const CustomCodeMirror: React.FC<CustomCodeMirrorProps> = (
{
// values we want to override in this component
value, extensions, lang,
dense, variant: customVariant,
classNamesContent, onChange,
onViewLifecycle, effects,
style,
highlightWhitespaces,
autoFocus,
extraMods = true,
enableTabIndent = true,
paddingBottom = false,
enableSpellCheck = false,
id,
},
) => {
const containerRef = React.useRef<HTMLDivElement | null>(null)
// containerRef.current ||= containerRefProps?.current || null
// refs for extensions need to be created before the extension
const editorAttributesCompartment = React.useRef<Compartment>(new Compartment())
const contentAttributesCompartment = React.useRef<Compartment>(new Compartment())
const keymapCompartment = React.useRef<Compartment>(new Compartment())
const highlightCompartment = React.useRef<Compartment>(new Compartment())
const highlightWhitespaceCompartment = React.useRef<Compartment>(new Compartment())
const highlightTrailingWhitespaceCompartment = React.useRef<Compartment>(new Compartment())
// todo: that `objet.values` here doesn't get changes when value keeps the same but property name has changed
// eslint-disable-next-line react-hooks/exhaustive-deps
const editorStyle = React.useMemo<React.CSSProperties>(() => style || {}, [Object.values(style || {})])
const {palette} = useTheme()
const customStyles = React.useMemo<Partial<EditorThemeCustomStyles>>(() => ({
activeSelection: palette.mode === 'dark' ? '#182f2f' : 'rgba(210,243,239,0.76)',
activeLine: palette.mode === 'dark' ? 'rgba(5, 115, 115, 0.11)' : 'rgba(216,234,231,0.34)',
paddingBottom: paddingBottom,
// activeSelection: '#ffffff',
// activeLine: '#ffffff',
// textColor: '#ffffff',
}), [palette.mode, paddingBottom])
const theme = useEditorTheme(typeof onChange === 'undefined', dense, customVariant, customStyles as EditorThemeCustomStyles)
const highlightStyle = useHighlightStyle({headlineUnderline: false})
const {init: initHighlightExt, effects: effectsHighlightExt} = useExtension(
() => syntaxHighlighting(highlightStyle || defaultHighlightStyle, {fallback: true}),
[highlightStyle],
)
const {init: initThemeExt, effects: effectsThemeExt} = useExtension(
() => theme,
[theme],
)
const effectsRef = React.useRef<((editor: EditorView) => void)[]>(effects || [])
const extensionsAll = React.useMemo(() => [
editorAttributesCompartment.current.of(EditorView.editorAttributes.of({})),
contentAttributesCompartment.current.of(EditorView.contentAttributes.of({})),
lineNumbers(),
EditorView.lineWrapping,
highlightActiveLineGutter(),
highlightSpecialChars(),
history(),
foldGutter(),
drawSelection(),
dropCursor(),
EditorState.allowMultipleSelections.of(true),
indentOnInput(),
bracketMatching(),
closeBrackets(),
autocompletion(),
rectangularSelection(),
highlightActiveLine(),
highlightSelectionMatches(),
keymapCompartment.current.of([]),
highlightCompartment.current.of([]),
highlightWhitespaceCompartment.current.of([]),
highlightTrailingWhitespaceCompartment.current.of([]),
...extraMods ? [
codeFolding(),
// hoverTooltip(),
tooltips(),
] : [],
// indentUnit.of(' '),
// todo: csv with tab requires keeping them as is
new Compartment().of(EditorState.tabSize.of(4)),
initHighlightExt(),
initThemeExt(),
...(extensions || []),
// todo: if any unmounting of these extensions is concurrently with an remote change, it may not be registered
// refactor the whole extensions to a combined part, which is reconciled "manually" in sync and on effects
], [extraMods, initHighlightExt, initThemeExt, extensions])
// attach parent plugin effects first
React.useMemo(() => {
if(!effects) return effectsRef.current
effectsRef.current.push(...effects)
}, [effects])
// attach each plugin effect separately (thus only the one which changes get reconfigured)
React.useMemo(() => {
if(!effectsHighlightExt) return
effectsRef.current.push(...effectsHighlightExt)
}, [effectsHighlightExt])
React.useMemo(() => {
if(!effectsThemeExt) return
effectsRef.current.push(...effectsThemeExt)
}, [effectsThemeExt])
const editor = useCodeMirror(
onChange,
value,
extensionsAll,
effectsRef.current.splice(0, effectsRef.current.length),
containerRef,
undefined,
onViewLifecycle,
)
// but extensions need to receive both: Compartment and Editor (and optionally their values)
// to be able to dispatch the correct effects
useEditorClasses(editorAttributesCompartment.current, editor, classNamesContent)
React.useEffect(() => {
if(!editor || !enableSpellCheck) return
// todo: spell check is working in e.g. Chrome but uses the device lang instead of app/component
const contentAttributesCompartmentTmp = contentAttributesCompartment.current
editor.dispatch({
// https://github.com/codemirror/dev/issues/1020
effects: contentAttributesCompartmentTmp
.reconfigure(
enableSpellCheck ?
EditorView.contentAttributes.of({autocorrect: 'on', autocapitalize: 'on', spellcheck: 'true'}) :
EditorView.contentAttributes.of({}),
),
})
return () => editor.dispatch({
// https://github.com/codemirror/dev/issues/1020
// ...enableSpellCheck ?
// [EditorView.contentAttributes.of({autocorrect: 'on', autocapitalize: 'on', spellcheck: 'true'})] : [],
effects: contentAttributesCompartmentTmp
.reconfigure(EditorView.contentAttributes.of({})),
})
}, [editor, enableSpellCheck])
React.useEffect(() => {
if(!editor) return
editor.dispatch({
effects: highlightWhitespaceCompartment.current
.reconfigure(onChange && highlightWhitespaces ? highlightWhitespace() : []),
})
}, [editor, highlightWhitespaceCompartment, highlightWhitespaces, onChange])
React.useEffect(() => {
if(!editor) return
const highlightExt = lang && getHighlight(lang)
editor.dispatch({
effects: highlightCompartment.current
.reconfigure(highlightExt ? [highlightExt] : []),
})
}, [editor, highlightCompartment, lang])
React.useEffect(() => {
if(!editor) return
editor.dispatch({
effects: keymapCompartment.current
.reconfigure([
keymap.of([
...closeBracketsKeymap,
...defaultKeymap.filter(k => k.key !== 'Mod-Enter'),
...searchKeymap,
...historyKeymap,
...foldKeymap,
...completionKeymap,
...lintKeymap,
...enableTabIndent ? [indentWithTab] : [],
]),
]),
})
}, [editor, keymapCompartment, enableTabIndent])
React.useEffect(() => {
if(!editor) return
editor.dispatch({
effects: highlightTrailingWhitespaceCompartment.current
.reconfigure(onChange && extraMods ? highlightTrailingWhitespace() : []),
})
}, [editor, highlightTrailingWhitespaceCompartment, onChange, extraMods])
React.useEffect(() => {
if(!editor || !autoFocus) return
const autoFocusDelay = typeof autoFocus === 'number' ? autoFocus : 75
const setFocus = () => {
editor.focus()
if(editor.hasFocus) {
const length = editor.state.doc.length
editor.dispatch({selection: {anchor: length, head: length}})
window.clearInterval(timer)
}
}
const timer = window.setInterval(setFocus, autoFocusDelay)
return () => window.clearInterval(timer)
}, [editor, autoFocus])
// todo: optimize font size config at theme ext hook
// return <div ref={containerRef} style={{...editorStyle, fontSize: '0.8784rem'}}/>
return <Box
id={id}
ref={containerRef}
sx={{
fontSize: '0.913rem', ...editorStyle,
position: onChange ? editorStyle?.position : 'relative',
// position: onChange || !showCopyButton ? editorStyle?.position : 'relative',
'.cm__actions': {display: 'none'},
'&:hover .cm__actions': {display: 'flex'},
}}
/>
}