Skip to content

Commit

Permalink
fix(editor): update monaco editor instead of recreate
Browse files Browse the repository at this point in the history
  • Loading branch information
BlackGlory committed Sep 23, 2024
1 parent 5e19c15 commit f25f168
Showing 1 changed file with 33 additions and 23 deletions.
56 changes: 33 additions & 23 deletions src/components/monaco-editor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import { useEffect, useRef } from 'react'
import * as monaco from 'monaco-editor'
import { twMerge } from 'tailwind-merge'
import { useDarkMode } from '@hooks/use-dark-mode.js'
import { assert } from '@blackglory/prelude'
import { useMount } from 'extra-react-hooks'

interface IMonacoEditorProps {
editorRef: React.MutableRefObject<monaco.editor.IStandaloneCodeEditor | null>
Expand All @@ -22,40 +24,48 @@ export function MonacoEditor(
const containerRef = useRef<HTMLDivElement>(null)
const isDarkMode = useDarkMode()

useEffect(() => {
useMount(() => {
const container = containerRef.current
assert(container)

if (container) {
const editor = monaco.editor.create(
container
, {
language: 'javascript'
, minimap: { enabled: false }
, tabSize: 2
, theme: isDarkMode
? 'vs-dark'
: 'vs'
, wordWrap: 'on'
, scrollBeyondLastLine: false
, automaticLayout: true
}
)
const editor = monaco.editor.create(
container
, {
language: 'javascript'
, minimap: { enabled: false }
, tabSize: 2
, wordWrap: 'on'
, scrollBeyondLastLine: false
, automaticLayout: true
}
)

editorRef.current = editor
editorRef.current = editor

onReady?.()
onReady?.()

return () => {
editor.dispose()
editorRef.current = null
}
return () => {
editor.dispose()
editorRef.current = null
}
})

useEffect(() => {
const editor = editorRef.current
assert(editor)

editor.updateOptions({
theme: isDarkMode
? 'vs-dark'
: 'vs'
})
}, [isDarkMode])

useEffect(() => {
const editor = editorRef.current
assert(editor)

if (editor && onChange) {
if (onChange) {
const disposable = editor.onDidChangeModelContent(() => {
onChange(editor.getValue())
})
Expand Down

0 comments on commit f25f168

Please sign in to comment.