project-context.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. 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. }),
  25. publicAccesLevel: PropTypes.string,
  26. tokens: PropTypes.shape({
  27. readOnly: PropTypes.string,
  28. readAndWrite: PropTypes.string,
  29. }),
  30. owner: PropTypes.shape({
  31. _id: PropTypes.string.isRequired,
  32. email: PropTypes.string.isRequired,
  33. }),
  34. }),
  35. }
  36. export function useProjectContext(propTypes) {
  37. const context = useContext(ProjectContext)
  38. if (!context) {
  39. throw new Error(
  40. 'useProjectContext is only available inside ProjectProvider'
  41. )
  42. }
  43. PropTypes.checkPropTypes(
  44. propTypes,
  45. context,
  46. 'data',
  47. 'ProjectContext.Provider'
  48. )
  49. return context
  50. }
  51. export function ProjectProvider({ children }) {
  52. const [project] = useScopeValue('project', true)
  53. // when the provider is created the project is still not added to the Angular scope.
  54. // Name is also populated to prevent errors in existing React components
  55. const value = project || { _id: window.project_id, name: '', features: {} }
  56. return (
  57. <ProjectContext.Provider value={value}>{children}</ProjectContext.Provider>
  58. )
  59. }
  60. ProjectProvider.propTypes = {
  61. children: PropTypes.any,
  62. }