1
- import MonacoEditor from "@monaco-editor/react" ;
1
+ import MonacoEditor , { Monaco } from "@monaco-editor/react" ;
2
+ import * as monaco from "monaco-editor/esm/vs/editor/editor.api" ;
2
3
import { EditorPropsInterface } from "../../interfaces/index" ;
3
- import React from "react" ;
4
+ import React , { useRef } from "react" ;
5
+ import prettier from "prettier" ;
6
+ import parser from "prettier/parser-babel" ;
4
7
5
8
const Editor : React . FC < EditorPropsInterface > = ( { onChange, initialValue } ) => {
6
- const onEditorDidMount = ( getCurrentValue : any ) => {
7
- console . log ( getCurrentValue ) ;
9
+
10
+
11
+ const monacoEditorRef = useRef < monaco . editor . IStandaloneCodeEditor > ( ) ;
12
+
13
+
14
+ /**
15
+ * On change in model, get the value of it's content and
16
+ * pass it as an argument to onChange to set the input state
17
+ */
18
+ const onEditorDidMount = (
19
+ editor : monaco . editor . IStandaloneCodeEditor ,
20
+ monacoInstance : Monaco
21
+ ) => {
22
+ // console.log(editor.getValue());
23
+ monacoEditorRef . current = editor ;
24
+ editor . onDidChangeModelContent ( ( ) => {
25
+ onChange ( editor . getValue ( ) ) ;
26
+ } ) ;
8
27
} ;
9
28
29
+ /**
30
+ * Get unformatted code, format it and set it to model
31
+ */
32
+ const onFormatClick = ( ) => {
33
+ const rawCode = monacoEditorRef ! . current ! . getModel ( ) ! . getValue ( ) ;
34
+ const formattedCode = prettier . format ( rawCode , {
35
+ parser : "babel" ,
36
+ plugins :[ parser ] ,
37
+ semi : true ,
38
+ singleQuote : true
39
+ } )
40
+
41
+ monacoEditorRef . current ?. setValue ( formattedCode ) ;
42
+ }
43
+
44
+
10
45
return (
11
- < MonacoEditor
46
+ < div >
47
+ < button onClick = { onFormatClick } > Format</ button >
48
+ < MonacoEditor
12
49
onMount = { onEditorDidMount }
13
50
value = { initialValue }
14
51
height = "30vh"
@@ -27,6 +64,8 @@ const Editor: React.FC<EditorPropsInterface> = ({ onChange, initialValue }) => {
27
64
automaticLayout : true ,
28
65
} }
29
66
/>
67
+ </ div >
68
+
30
69
) ;
31
70
} ;
32
71
0 commit comments