project-context.tsx 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. mainBibliographyDoc_id: mainBibliographyDocId,
  37. } = project || projectFallback
  38. const tags = useMemo(
  39. () =>
  40. (getMeta('ol-projectTags') || [])
  41. // `tag.name` data may be null for some old users
  42. .map((tag: any) => ({ ...tag, name: tag.name ?? '' })),
  43. []
  44. )
  45. const value = useMemo(() => {
  46. return {
  47. _id,
  48. compiler,
  49. name,
  50. rootDocId,
  51. members,
  52. invites,
  53. features,
  54. publicAccessLevel,
  55. owner,
  56. tags,
  57. trackChangesState,
  58. mainBibliographyDocId,
  59. }
  60. }, [
  61. _id,
  62. compiler,
  63. name,
  64. rootDocId,
  65. members,
  66. invites,
  67. features,
  68. publicAccessLevel,
  69. owner,
  70. tags,
  71. trackChangesState,
  72. mainBibliographyDocId,
  73. ])
  74. return (
  75. <ProjectContext.Provider value={value}>{children}</ProjectContext.Provider>
  76. )
  77. }