project-context.js 2.2 KB

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