codemirror-view.tsx 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. import { memo, useCallback, useEffect } from 'react'
  2. import { useCodeMirrorViewContext } from './codemirror-context'
  3. import useCodeMirrorScope from '../hooks/use-codemirror-scope'
  4. import { useEditorViewContext } from '@/features/ide-react/context/editor-view-context'
  5. function CodeMirrorView() {
  6. const view = useCodeMirrorViewContext()
  7. const { setView } = useEditorViewContext()
  8. // append the editor view dom to the container node when mounted
  9. const containerRef = useCallback(
  10. (node: HTMLDivElement) => {
  11. if (node) {
  12. node.appendChild(view.dom)
  13. }
  14. },
  15. [view]
  16. )
  17. // destroy the editor when unmounted
  18. useEffect(() => {
  19. return () => {
  20. view.destroy()
  21. }
  22. }, [view])
  23. // Add the CodeMirror view to the editor view context so that it can be
  24. // accessed outside the editor component
  25. useEffect(() => {
  26. setView(view)
  27. }, [setView, view])
  28. useCodeMirrorScope(view)
  29. return <div ref={containerRef} style={{ height: '100%' }} />
  30. }
  31. export default memo(CodeMirrorView)