index.tsx 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import MonacoEditor from 'react-monaco-editor';
  2. import { connect, mapProps } from '@formily/react';
  3. import { useCallback, useEffect, useRef, useState } from 'react';
  4. import type { MonacoEditorProps } from 'react-monaco-editor/lib/types';
  5. interface Props extends MonacoEditorProps {}
  6. export const JMonacoEditor = (props: Props) => {
  7. const [loading, setLoading] = useState(false);
  8. const formatLock = useRef<boolean>(false);
  9. const monacoRef = useRef<any>();
  10. const monacoEditorRef = useRef<any>();
  11. const editorFormat = (editor: any) => {
  12. editor.getAction('editor.action.formatDocument').run();
  13. };
  14. useEffect(() => {
  15. if (formatLock.current === false && monacoEditorRef.current) {
  16. setTimeout(() => {
  17. editorFormat(monacoEditorRef.current);
  18. }, 300);
  19. formatLock.current = true;
  20. }
  21. }, [props.value, loading, monacoEditorRef.current]);
  22. const editorDidMountHandle = useCallback((editor: any, monaco: any) => {
  23. monacoEditorRef.current = editor;
  24. props.editorDidMount?.(editor, monaco);
  25. }, []);
  26. return (
  27. <div
  28. ref={() => {
  29. setTimeout(() => {
  30. setLoading(true);
  31. }, 100);
  32. }}
  33. style={{ height: '100%', width: '100%' }}
  34. >
  35. {loading && (
  36. <MonacoEditor
  37. ref={(r: any) => {
  38. monacoRef.current = r;
  39. if (r && formatLock.current === false) {
  40. editorFormat(r.editor);
  41. }
  42. }}
  43. {...props}
  44. options={{ wordWrap: 'on', automaticLayout: true }}
  45. editorDidMount={editorDidMountHandle}
  46. />
  47. )}
  48. </div>
  49. );
  50. };
  51. const FMonacoEditor = connect(JMonacoEditor, mapProps());
  52. export default FMonacoEditor;