project-context.tsx 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import { FC, createContext, useContext, useMemo } from 'react'
  2. import useScopeValue from '../hooks/use-scope-value'
  3. import getMeta from '@/utils/meta'
  4. import { ProjectContextValue } from './types/project-context'
  5. const ProjectContext = createContext<ProjectContextValue | undefined>(undefined)
  6. export function useProjectContext() {
  7. const context = useContext(ProjectContext)
  8. if (!context) {
  9. throw new Error(
  10. 'useProjectContext is only available inside ProjectProvider'
  11. )
  12. }
  13. return context
  14. }
  15. // when the provider is created the project is still not added to the Angular
  16. // scope. A few props are populated to prevent errors in existing React
  17. // components
  18. const projectFallback = {
  19. _id: getMeta('ol-project_id'),
  20. name: '',
  21. features: {},
  22. }
  23. export const ProjectProvider: FC = ({ children }) => {
  24. const [project] = useScopeValue('project')
  25. const {
  26. _id,
  27. compiler,
  28. name,
  29. rootDoc_id: rootDocId,
  30. members,
  31. invites,
  32. features,
  33. publicAccesLevel: publicAccessLevel,
  34. owner,
  35. trackChangesState,
  36. } = project || projectFallback
  37. const tags = useMemo(
  38. () =>
  39. (getMeta('ol-projectTags') || [])
  40. // `tag.name` data may be null for some old users
  41. .map((tag: any) => ({ ...tag, name: tag.name ?? '' })),
  42. []
  43. )
  44. const value = useMemo(() => {
  45. return {
  46. _id,
  47. compiler,
  48. name,
  49. rootDocId,
  50. members,
  51. invites,
  52. features,
  53. publicAccessLevel,
  54. owner,
  55. tags,
  56. trackChangesState,
  57. }
  58. }, [
  59. _id,
  60. compiler,
  61. name,
  62. rootDocId,
  63. members,
  64. invites,
  65. features,
  66. publicAccessLevel,
  67. owner,
  68. tags,
  69. trackChangesState,
  70. ])
  71. return (
  72. <ProjectContext.Provider value={value}>{children}</ProjectContext.Provider>
  73. )
  74. }