1+ import { useColorMode } from '@chakra-ui/react' ;
2+ import dynamic from 'next/dynamic' ;
3+ import React from 'react' ;
4+ import _ from 'lodash' ;
5+ import { OnMount } from '@monaco-editor/react' ;
6+
7+ const MonacoEditor = dynamic ( ( ) => import ( '@monaco-editor/react' ) . then ( m => m . default ) , { ssr : false } ) ;
8+
9+ const monacoEditorOptions = {
10+ wordWrap : true ,
11+ }
12+
13+ interface IEditor {
14+ refEditor ?: any ;
15+ value ?: any ;
16+ onChange ?: ( value : string ) => void ;
17+ onSave ?: ( value : string ) => void ;
18+ onClose ?: ( ) => void ;
19+ onExit ?: ( ) => void ;
20+ minimap ?: boolean ;
21+ lineNumbers ?: string ;
22+ defaultLanguage ?: string ;
23+ onMount ?: ( editor : any , monaco : any ) => any ;
24+ }
25+
26+ export const Editor = React . memo ( ( {
27+ refEditor = { current : undefined } ,
28+ value = '' ,
29+ onChange,
30+ onSave,
31+ onClose,
32+ onExit,
33+ minimap = true ,
34+ lineNumbers = 'on' ,
35+ defaultLanguage= "javascript" ,
36+ onMount,
37+ } :IEditor ) => {
38+ const refValue = React . useRef ( value ) ;
39+ refValue . current = value ;
40+
41+ const { colorMode } = useColorMode ( ) ;
42+ const handleEditorDidMount : OnMount = ( editor , monaco ) => {
43+ refEditor . current = { editor, monaco } ;
44+ editor . getModel ( ) . updateOptions ( { tabSize : 2 } ) ;
45+ editor . addCommand ( monaco . KeyMod . CtrlCmd | monaco . KeyCode . KeyS , ( ) => {
46+ onSave && onSave ( refValue . current ) ;
47+ } ) ;
48+ editor . addCommand ( monaco . KeyMod . CtrlCmd | monaco . KeyCode . KeyE , ( ) => {
49+ onClose && onClose ( ) ;
50+ } ) ;
51+ editor . addCommand ( monaco . KeyMod . CtrlCmd | monaco . KeyCode . Escape , ( ) => {
52+ onExit && onExit ( ) ;
53+ } ) ;
54+ onMount && onMount ( editor , monaco ) ;
55+ }
56+
57+ return ( < MonacoEditor
58+ options = { {
59+ ...monacoEditorOptions ,
60+ minimap : {
61+ enabled : minimap
62+ } ,
63+ // @ts -ignore
64+ lineNumbers : lineNumbers ,
65+ } }
66+ height = "100%"
67+ width = "100%"
68+ theme = { colorMode === 'light' ? 'light' : "vs-dark" }
69+ defaultLanguage = { defaultLanguage }
70+ defaultValue = { _ . toString ( value ) || '' }
71+ onChange = { onChange }
72+ onMount = { handleEditorDidMount }
73+ /> )
74+ } )
0 commit comments