({ text, readonly, language, onChange, onMount, path, options }: CodeEditorProps)
| 23 | }; |
| 24 | |
| 25 | export function MonacoCodeEditor({ text, readonly, language, onChange, onMount, path, options }: CodeEditorProps) { |
| 26 | const divRef = useRef<HTMLDivElement>(null); |
| 27 | const editorRef = useRef<MonacoTypes.editor.IStandaloneCodeEditor | null>(null); |
| 28 | const onUnmountRef = useRef<(() => void) | null>(null); |
| 29 | const applyingFromProps = useRef(false); |
| 30 | |
| 31 | useEffect(() => { |
| 32 | loadMonaco(); |
| 33 | |
| 34 | const el = divRef.current; |
| 35 | if (!el) return; |
| 36 | |
| 37 | const model = createModel(text, path, language); |
| 38 | console.log("[monaco] CREATE MODEL", path, model); |
| 39 | |
| 40 | const editor = monaco.editor.create(el, { |
| 41 | ...options, |
| 42 | readOnly: readonly, |
| 43 | model, |
| 44 | }); |
| 45 | editorRef.current = editor; |
| 46 | |
| 47 | const sub = model.onDidChangeContent(() => { |
| 48 | if (applyingFromProps.current) return; |
| 49 | onChange?.(model.getValue()); |
| 50 | }); |
| 51 | |
| 52 | if (onMount) { |
| 53 | onUnmountRef.current = onMount(editor, monaco); |
| 54 | } |
| 55 | |
| 56 | return () => { |
| 57 | sub.dispose(); |
| 58 | if (onUnmountRef.current) onUnmountRef.current(); |
| 59 | editor.setModel(null); |
| 60 | editor.dispose(); |
| 61 | model.dispose(); |
| 62 | console.log("[monaco] dispose model"); |
| 63 | editorRef.current = null; |
| 64 | }; |
| 65 | // mount/unmount only |
| 66 | }, []); |
| 67 | |
| 68 | useEffect(() => { |
| 69 | const editor = editorRef.current; |
| 70 | const el = divRef.current; |
| 71 | if (!editor || !el) return; |
| 72 | |
| 73 | const debouncedLayout = debounce(100, () => { |
| 74 | editor.layout(); |
| 75 | }); |
| 76 | const resizeObserver = new ResizeObserver(debouncedLayout); |
| 77 | resizeObserver.observe(el); |
| 78 | |
| 79 | return () => { |
| 80 | resizeObserver.disconnect(); |
| 81 | debouncedLayout.cancel(); |
| 82 | }; |
nothing calls this directly
no test coverage detected