editor-view-context.tsx 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import {
  2. createContext,
  3. Dispatch,
  4. FC,
  5. PropsWithChildren,
  6. SetStateAction,
  7. useContext,
  8. } from 'react'
  9. import { EditorView } from '@codemirror/view'
  10. import useExposedState from '@/shared/hooks/use-exposed-state'
  11. export type EditorContextValue = {
  12. view: EditorView | null
  13. setView: Dispatch<SetStateAction<EditorView | null>>
  14. }
  15. // This provides access to the CodeMirror EditorView instance outside the editor
  16. // component itself, including external extensions (in particular, Writefull)
  17. export const EditorViewContext = createContext<EditorContextValue | undefined>(
  18. undefined
  19. )
  20. export const EditorViewProvider: FC<PropsWithChildren> = ({ children }) => {
  21. const [view, setView] = useExposedState<EditorView | null>(
  22. null,
  23. 'editor.view'
  24. )
  25. const value = {
  26. view,
  27. setView,
  28. }
  29. return (
  30. <EditorViewContext.Provider value={value}>
  31. {children}
  32. </EditorViewContext.Provider>
  33. )
  34. }
  35. export const useEditorViewContext = (): EditorContextValue => {
  36. const context = useContext(EditorViewContext)
  37. if (!context) {
  38. throw new Error(
  39. 'useEditorViewContext is only available inside EditorViewProvider'
  40. )
  41. }
  42. return context
  43. }