project-context.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. import { createContext, useContext, useMemo } from 'react'
  2. import PropTypes from 'prop-types'
  3. import useScopeValue from '../hooks/use-scope-value'
  4. const ProjectContext = createContext()
  5. export const projectShape = {
  6. _id: PropTypes.string.isRequired,
  7. name: PropTypes.string.isRequired,
  8. rootDocId: PropTypes.string,
  9. members: PropTypes.arrayOf(
  10. PropTypes.shape({
  11. _id: PropTypes.string.isRequired,
  12. })
  13. ),
  14. invites: PropTypes.arrayOf(
  15. PropTypes.shape({
  16. _id: PropTypes.string.isRequired,
  17. })
  18. ),
  19. features: PropTypes.shape({
  20. collaborators: PropTypes.number,
  21. compileGroup: PropTypes.oneOf(['alpha', 'standard', 'priority']),
  22. trackChangesVisible: PropTypes.bool,
  23. references: PropTypes.bool,
  24. mendeley: PropTypes.bool,
  25. zotero: PropTypes.bool,
  26. versioning: PropTypes.bool,
  27. gitBridge: PropTypes.bool,
  28. }),
  29. publicAccessLevel: PropTypes.string,
  30. owner: PropTypes.shape({
  31. _id: PropTypes.string.isRequired,
  32. email: PropTypes.string.isRequired,
  33. }),
  34. }
  35. ProjectContext.Provider.propTypes = {
  36. value: PropTypes.shape(projectShape),
  37. }
  38. export function useProjectContext(propTypes) {
  39. const context = useContext(ProjectContext)
  40. if (!context) {
  41. throw new Error(
  42. 'useProjectContext is only available inside ProjectProvider'
  43. )
  44. }
  45. PropTypes.checkPropTypes(
  46. propTypes,
  47. context,
  48. 'data',
  49. 'ProjectContext.Provider'
  50. )
  51. return context
  52. }
  53. // when the provider is created the project is still not added to the Angular
  54. // scope. A few props are populated to prevent errors in existing React
  55. // components
  56. const projectFallback = {
  57. _id: window.project_id,
  58. name: '',
  59. features: {},
  60. }
  61. export function ProjectProvider({ children }) {
  62. const [project] = useScopeValue('project', true)
  63. const {
  64. _id,
  65. name,
  66. rootDoc_id: rootDocId,
  67. members,
  68. invites,
  69. features,
  70. publicAccesLevel: publicAccessLevel,
  71. owner,
  72. } = project || projectFallback
  73. const value = useMemo(() => {
  74. return {
  75. _id,
  76. name,
  77. rootDocId,
  78. members,
  79. invites,
  80. features,
  81. publicAccessLevel,
  82. owner,
  83. }
  84. }, [
  85. _id,
  86. name,
  87. rootDocId,
  88. members,
  89. invites,
  90. features,
  91. publicAccessLevel,
  92. owner,
  93. ])
  94. return (
  95. <ProjectContext.Provider value={value}>{children}</ProjectContext.Provider>
  96. )
  97. }
  98. ProjectProvider.propTypes = {
  99. children: PropTypes.any,
  100. }