codemirror-view.tsx 1020 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. import { memo, useCallback, useEffect } from 'react'
  2. import { useCodeMirrorViewContext } from './codemirror-context'
  3. import useCodeMirrorScope from '../hooks/use-codemirror-scope'
  4. import useScopeValueSetterOnly from '@/shared/hooks/use-scope-value-setter-only'
  5. function CodeMirrorView() {
  6. const view = useCodeMirrorViewContext()
  7. const [, setView] = useScopeValueSetterOnly('editor.view')
  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 editor view to the scope value store, so it can be accessed by external extensions
  24. useEffect(() => {
  25. setView(view)
  26. }, [setView, view])
  27. useCodeMirrorScope(view)
  28. return <div ref={containerRef} style={{ height: '100%' }} />
  29. }
  30. export default memo(CodeMirrorView)