codemirror-view.tsx 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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. type CodeMirrorViewProps = {
  6. hidden: boolean
  7. }
  8. function CodeMirrorView({ hidden = false }: CodeMirrorViewProps) {
  9. const view = useCodeMirrorViewContext()
  10. const { setView } = useEditorViewContext()
  11. // append the editor view dom to the container node when mounted
  12. const containerRef = useCallback(
  13. (node: HTMLDivElement) => {
  14. if (node) {
  15. node.appendChild(view.dom)
  16. }
  17. },
  18. [view]
  19. )
  20. // destroy the editor when unmounted
  21. useEffect(() => {
  22. return () => {
  23. view.destroy()
  24. }
  25. }, [view])
  26. // Add the CodeMirror view to the editor view context so that it can be
  27. // accessed outside the editor component
  28. useEffect(() => {
  29. setView(view)
  30. }, [setView, view])
  31. useCodeMirrorScope(view)
  32. return <div ref={containerRef} style={{ height: '100%' }} hidden={hidden} />
  33. }
  34. export default memo(CodeMirrorView)