project-context.tsx 2.0 KB

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