project-context.tsx 2.1 KB

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