Repository navigation
Expand file tree
/
Copy pathEditor.tsx
More file actions
62 lines (54 loc) · 1.75 KB
/
Copy pathEditor.tsx
File metadata and controls
62 lines (54 loc) · 1.75 KB
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
import React, {useEffect} from 'react'
import {EditorView} from '@codemirror/view'
import {Compartment, EditorState} from '@codemirror/state'
import {basicSetup} from '@codemirror/basic-setup'
import {java} from "./java/language";
import {ThemeKey, useTheme} from '../theme/ThemeContext'
import {editorThemes, highlightingThemes} from './themes/themes'
const tabSize = 2
function createView(initialContent: string, element: Element, theme: ThemeKey) {
return new EditorView({
parent: element,
state: EditorState.create({
doc: initialContent,
extensions: [
basicSetup,
EditorState.tabSize.of(tabSize),
java(),
themeState.of(editorThemes[theme]),
highlightingState.of(highlightingThemes[theme])
]
})
})
}
export interface EditorProperties {
code: string
editorRef?: React.MutableRefObject<EditorView | null>
}
const themeState = new Compartment()
const highlightingState = new Compartment()
export default function Editor(properties: EditorProperties) {
const element = React.createRef<HTMLDivElement>()
const editor = React.useRef<{editor: EditorView | undefined}>({editor: undefined})
const [theme] = useTheme()
useEffect(() => {
if (element == null) {
return
}
const created = createView(properties.code, element.current!, theme)
editor.current.editor = created
if (properties.editorRef) {
properties.editorRef.current = created
}
return () => created.destroy()
}, [properties.editorRef])
useEffect(() => {
properties.editorRef?.current?.dispatch({
effects: [
themeState.reconfigure(editorThemes[theme]),
highlightingState.reconfigure(highlightingThemes[theme])
]
})
}, [theme])
return (<div ref={element}/>)
}