project-context.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. ProjectContext.Provider.propTypes = {
  6. value: PropTypes.shape({
  7. _id: PropTypes.string.isRequired,
  8. name: PropTypes.string.isRequired,
  9. rootDoc_id: PropTypes.string,
  10. members: PropTypes.arrayOf(
  11. PropTypes.shape({
  12. _id: PropTypes.string.isRequired,
  13. })
  14. ),
  15. invites: PropTypes.arrayOf(
  16. PropTypes.shape({
  17. _id: PropTypes.string.isRequired,
  18. })
  19. ),
  20. features: PropTypes.shape({
  21. collaborators: PropTypes.number,
  22. compileGroup: PropTypes.oneOf(['alpha', 'standard', 'priority']),
  23. trackChangesVisible: PropTypes.bool,
  24. references: PropTypes.bool,
  25. mendeley: PropTypes.bool,
  26. zotero: PropTypes.bool,
  27. }),
  28. publicAccesLevel: PropTypes.string,
  29. tokens: PropTypes.shape({
  30. readOnly: PropTypes.string,
  31. readAndWrite: PropTypes.string,
  32. }),
  33. owner: PropTypes.shape({
  34. _id: PropTypes.string.isRequired,
  35. email: PropTypes.string.isRequired,
  36. }),
  37. }),
  38. }
  39. export function useProjectContext(propTypes) {
  40. const context = useContext(ProjectContext)
  41. if (!context) {
  42. throw new Error(
  43. 'useProjectContext is only available inside ProjectProvider'
  44. )
  45. }
  46. PropTypes.checkPropTypes(
  47. propTypes,
  48. context,
  49. 'data',
  50. 'ProjectContext.Provider'
  51. )
  52. return context
  53. }
  54. // when the provider is created the project is still not added to the Angular
  55. // scope. A few props are populated to prevent errors in existing React
  56. // components
  57. const projectFallback = {
  58. _id: window.project_id,
  59. name: '',
  60. features: {},
  61. }
  62. export function ProjectProvider({ children }) {
  63. const [project] = useScopeValue('project', true)
  64. const value = useMemo(() => {
  65. return {
  66. ...projectFallback,
  67. ...project,
  68. }
  69. }, [project])
  70. return (
  71. <ProjectContext.Provider value={value}>{children}</ProjectContext.Provider>
  72. )
  73. }
  74. ProjectProvider.propTypes = {
  75. children: PropTypes.any,
  76. }