editor-open-doc-context.tsx 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import {
  2. createContext,
  3. Dispatch,
  4. FC,
  5. PropsWithChildren,
  6. SetStateAction,
  7. useContext,
  8. useState,
  9. } from 'react'
  10. import { DocId } from '../../../../../types/project-settings'
  11. import useExposedState from '@/shared/hooks/use-exposed-state'
  12. import { DocumentContainer } from '@/features/ide-react/editor/document-container'
  13. type EditorOpenDocContextValue = {
  14. currentDocumentId: DocId | null
  15. setCurrentDocumentId: Dispatch<SetStateAction<DocId | null>>
  16. openDocName: string | null
  17. setOpenDocName: Dispatch<SetStateAction<string | null>>
  18. currentDocument: DocumentContainer | null
  19. setCurrentDocument: Dispatch<SetStateAction<DocumentContainer | null>>
  20. }
  21. export const EditorOpenDocContext = createContext<
  22. EditorOpenDocContextValue | undefined
  23. >(undefined)
  24. export const EditorOpenDocProvider: FC<PropsWithChildren> = ({ children }) => {
  25. const [currentDocumentId, setCurrentDocumentId] =
  26. useExposedState<DocId | null>(null, 'editor.open_doc_id')
  27. const [openDocName, setOpenDocName] = useExposedState<string | null>(
  28. null,
  29. 'editor.open_doc_name'
  30. )
  31. const [currentDocument, setCurrentDocument] =
  32. useState<DocumentContainer | null>(null)
  33. const value = {
  34. currentDocumentId,
  35. setCurrentDocumentId,
  36. openDocName,
  37. setOpenDocName,
  38. currentDocument,
  39. setCurrentDocument,
  40. }
  41. return (
  42. <EditorOpenDocContext.Provider value={value}>
  43. {children}
  44. </EditorOpenDocContext.Provider>
  45. )
  46. }
  47. export const useEditorOpenDocContext = (): EditorOpenDocContextValue => {
  48. const context = useContext(EditorOpenDocContext)
  49. if (!context) {
  50. throw new Error(
  51. 'useEditorOpenDocContext is only available inside EditorOpenDocContext.Provider'
  52. )
  53. }
  54. return context
  55. }