editor-open-doc-context.tsx 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. export interface EditorOpenDocContextState {
  14. currentDocumentId: DocId | null
  15. openDocName: string | null
  16. currentDocument: DocumentContainer | null
  17. }
  18. interface EditorOpenDocContextValue extends EditorOpenDocContextState {
  19. setCurrentDocumentId: Dispatch<SetStateAction<DocId | null>>
  20. setOpenDocName: Dispatch<SetStateAction<string | null>>
  21. setCurrentDocument: Dispatch<SetStateAction<DocumentContainer | null>>
  22. }
  23. export const EditorOpenDocContext = createContext<
  24. EditorOpenDocContextValue | undefined
  25. >(undefined)
  26. export const EditorOpenDocProvider: FC<PropsWithChildren> = ({ children }) => {
  27. const [currentDocumentId, setCurrentDocumentId] =
  28. useExposedState<DocId | null>(null, 'editor.open_doc_id')
  29. const [openDocName, setOpenDocName] = useExposedState<string | null>(
  30. null,
  31. 'editor.open_doc_name'
  32. )
  33. const [currentDocument, setCurrentDocument] =
  34. useState<DocumentContainer | null>(null)
  35. const value = {
  36. currentDocumentId,
  37. setCurrentDocumentId,
  38. openDocName,
  39. setOpenDocName,
  40. currentDocument,
  41. setCurrentDocument,
  42. }
  43. return (
  44. <EditorOpenDocContext.Provider value={value}>
  45. {children}
  46. </EditorOpenDocContext.Provider>
  47. )
  48. }
  49. export const useEditorOpenDocContext = (): EditorOpenDocContextValue => {
  50. const context = useContext(EditorOpenDocContext)
  51. if (!context) {
  52. throw new Error(
  53. 'useEditorOpenDocContext is only available inside EditorOpenDocContext.Provider'
  54. )
  55. }
  56. return context
  57. }