editor-selection-context.tsx 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import {
  2. createContext,
  3. type Dispatch,
  4. type FC,
  5. type PropsWithChildren,
  6. type SetStateAction,
  7. useContext,
  8. useMemo,
  9. useState,
  10. } from 'react'
  11. import type { EditorSelection } from '@codemirror/state'
  12. export const EditorSelectionContext = createContext<
  13. | {
  14. editorSelection: EditorSelection | undefined
  15. setEditorSelection: Dispatch<SetStateAction<EditorSelection | undefined>>
  16. }
  17. | undefined
  18. >(undefined)
  19. export const EditorSelectionProvider: FC<PropsWithChildren> = ({
  20. children,
  21. }) => {
  22. const [editorSelection, setEditorSelection] = useState<EditorSelection>()
  23. const value = useMemo(() => {
  24. return { editorSelection, setEditorSelection }
  25. }, [editorSelection])
  26. return (
  27. <EditorSelectionContext.Provider value={value}>
  28. {children}
  29. </EditorSelectionContext.Provider>
  30. )
  31. }
  32. export const useEditorSelectionContext = () => {
  33. const context = useContext(EditorSelectionContext)
  34. if (!context) {
  35. throw new Error(
  36. 'useEditorSelectionContext is only available inside EditorSelectionProvider'
  37. )
  38. }
  39. return context
  40. }