projectContext.tsx 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. import {Component, createContext} from 'react';
  2. import styled from '@emotion/styled';
  3. import {fetchOrgMembers} from 'sentry/actionCreators/members';
  4. import {setActiveProject} from 'sentry/actionCreators/projects';
  5. import type {Client} from 'sentry/api';
  6. import Alert from 'sentry/components/alert';
  7. import * as Layout from 'sentry/components/layouts/thirds';
  8. import LoadingError from 'sentry/components/loadingError';
  9. import LoadingIndicator from 'sentry/components/loadingIndicator';
  10. import MissingProjectMembership from 'sentry/components/projects/missingProjectMembership';
  11. import SentryDocumentTitle from 'sentry/components/sentryDocumentTitle';
  12. import {t} from 'sentry/locale';
  13. import MemberListStore from 'sentry/stores/memberListStore';
  14. import ProjectsStore from 'sentry/stores/projectsStore';
  15. import {space} from 'sentry/styles/space';
  16. import type {Organization} from 'sentry/types/organization';
  17. import type {Project} from 'sentry/types/project';
  18. import type {User} from 'sentry/types/user';
  19. import withApi from 'sentry/utils/withApi';
  20. import withOrganization from 'sentry/utils/withOrganization';
  21. import withProjects from 'sentry/utils/withProjects';
  22. enum ErrorTypes {
  23. MISSING_MEMBERSHIP = 'MISSING_MEMBERSHIP',
  24. PROJECT_NOT_FOUND = 'PROJECT_NOT_FOUND',
  25. UNKNOWN = 'UNKNOWN',
  26. }
  27. type ChildFuncProps = {
  28. project: Project;
  29. };
  30. type Props = {
  31. api: Client;
  32. children: ((props: ChildFuncProps) => React.ReactNode) | React.ReactNode;
  33. loadingProjects: boolean;
  34. organization: Organization;
  35. projectSlug: string;
  36. projects: Project[];
  37. /**
  38. * If true, this will not change `state.loading` during `fetchData` phase
  39. */
  40. skipReload?: boolean;
  41. };
  42. type State = {
  43. error: boolean;
  44. errorType: ErrorTypes | null;
  45. loading: boolean;
  46. memberList: User[];
  47. project: Project | null;
  48. };
  49. const ProjectContext = createContext<Project | null>(null);
  50. /**
  51. * Higher-order component that sets `project` as a child context
  52. * value to be accessed by child elements.
  53. *
  54. * Additionally delays rendering of children until project XHR has finished
  55. * and context is populated.
  56. */
  57. class ProjectContextProvider extends Component<Props, State> {
  58. state = this.getInitialState();
  59. getInitialState(): State {
  60. return {
  61. loading: true,
  62. error: false,
  63. errorType: null,
  64. memberList: [],
  65. project: null,
  66. };
  67. }
  68. componentDidMount() {
  69. // Wait for withProjects to fetch projects before making request
  70. // Once loaded we can fetchData in componentDidUpdate
  71. const {loadingProjects} = this.props;
  72. if (!loadingProjects) {
  73. this.fetchData();
  74. }
  75. }
  76. UNSAFE_componentWillReceiveProps(nextProps: Props) {
  77. if (nextProps.projectSlug === this.props.projectSlug) {
  78. return;
  79. }
  80. if (!nextProps.skipReload) {
  81. this.remountComponent();
  82. }
  83. }
  84. componentDidUpdate(prevProps: Props, _prevState: State) {
  85. if (prevProps.projectSlug !== this.props.projectSlug) {
  86. this.fetchData();
  87. }
  88. // Project list has changed. Likely indicating that a new project has been
  89. // added. Re-fetch project details in case that the new project is the active
  90. // project.
  91. //
  92. // For now, only compare lengths. It is possible that project slugs within
  93. // the list could change, but it doesn't seem to be broken anywhere else at
  94. // the moment that would require deeper checks.
  95. if (prevProps.projects.length !== this.props.projects.length) {
  96. this.fetchData();
  97. }
  98. }
  99. componentWillUnmount() {
  100. this.unsubscribeMembers();
  101. this.unsubscribeProjects();
  102. }
  103. unsubscribeProjects = ProjectsStore.listen(
  104. (projectIds: Set<string>) => this.onProjectChange(projectIds),
  105. undefined
  106. );
  107. unsubscribeMembers = MemberListStore.listen(
  108. ({members}: typeof MemberListStore.state) => this.setState({memberList: members}),
  109. undefined
  110. );
  111. remountComponent() {
  112. this.setState(this.getInitialState());
  113. }
  114. getTitle() {
  115. return this.state.project?.slug ?? 'Sentry';
  116. }
  117. onProjectChange(projectIds: Set<string>) {
  118. if (!this.state.project) {
  119. return;
  120. }
  121. if (!projectIds.has(this.state.project.id)) {
  122. return;
  123. }
  124. this.setState({
  125. project: {...ProjectsStore.getById(this.state.project.id)} as Project,
  126. });
  127. }
  128. identifyProject() {
  129. const {projects, projectSlug} = this.props;
  130. return projects.find(({slug}) => slug === projectSlug) || null;
  131. }
  132. async fetchData() {
  133. const {organization, projectSlug, skipReload} = this.props;
  134. // we fetch core access/information from the global organization data
  135. const activeProject = this.identifyProject();
  136. const hasAccess = activeProject?.hasAccess;
  137. this.setState((state: State) => ({
  138. // if `skipReload` is true, then don't change loading state
  139. loading: skipReload ? state.loading : true,
  140. // we bind project initially, but it'll rebind
  141. project: activeProject,
  142. }));
  143. if (activeProject && hasAccess) {
  144. setActiveProject(null);
  145. const projectRequest = this.props.api.requestPromise(
  146. `/projects/${organization.slug}/${projectSlug}/`
  147. );
  148. try {
  149. const project = await projectRequest;
  150. this.setState({
  151. loading: false,
  152. project,
  153. error: false,
  154. errorType: null,
  155. });
  156. // assuming here that this means the project is considered the active project
  157. setActiveProject(project);
  158. } catch (error) {
  159. this.setState({
  160. loading: false,
  161. error: false,
  162. errorType: ErrorTypes.UNKNOWN,
  163. });
  164. }
  165. fetchOrgMembers(this.props.api, organization.slug, [activeProject.id]);
  166. return;
  167. }
  168. // User is not a memberof the active project
  169. if (activeProject && !activeProject.isMember) {
  170. this.setState({
  171. loading: false,
  172. error: true,
  173. errorType: ErrorTypes.MISSING_MEMBERSHIP,
  174. });
  175. return;
  176. }
  177. // There is no active project. This likely indicates either the project
  178. // *does not exist* or the project has not yet been added to the store.
  179. // Either way, make a request to check for existence of the project.
  180. try {
  181. await this.props.api.requestPromise(
  182. `/projects/${organization.slug}/${projectSlug}/`
  183. );
  184. } catch (error) {
  185. this.setState({
  186. loading: false,
  187. error: true,
  188. errorType: ErrorTypes.PROJECT_NOT_FOUND,
  189. });
  190. }
  191. }
  192. renderBody() {
  193. const {children, organization} = this.props;
  194. const {error, errorType, loading, project} = this.state;
  195. if (loading) {
  196. return (
  197. <div className="loading-full-layout">
  198. <LoadingIndicator />
  199. </div>
  200. );
  201. }
  202. if (!error && project) {
  203. return (
  204. <ProjectContext.Provider value={project}>
  205. {typeof children === 'function' ? children({project}) : children}
  206. </ProjectContext.Provider>
  207. );
  208. }
  209. switch (errorType) {
  210. case ErrorTypes.PROJECT_NOT_FOUND:
  211. // TODO(chrissy): use scale for margin values
  212. return (
  213. <Layout.Page withPadding>
  214. <Alert type="warning">
  215. {t('The project you were looking for was not found.')}
  216. </Alert>
  217. </Layout.Page>
  218. );
  219. case ErrorTypes.MISSING_MEMBERSHIP:
  220. // TODO(dcramer): add various controls to improve this flow and break it
  221. // out into a reusable missing access error component
  222. return (
  223. <ErrorWrapper>
  224. <MissingProjectMembership organization={organization} project={project} />
  225. </ErrorWrapper>
  226. );
  227. default:
  228. return <LoadingError onRetry={this.remountComponent} />;
  229. }
  230. }
  231. render() {
  232. return (
  233. <SentryDocumentTitle noSuffix title={this.getTitle()}>
  234. {this.renderBody()}
  235. </SentryDocumentTitle>
  236. );
  237. }
  238. }
  239. export {ProjectContext, ProjectContextProvider};
  240. export default withApi(withOrganization(withProjects(ProjectContextProvider)));
  241. const ErrorWrapper = styled('div')`
  242. width: 100%;
  243. margin: ${space(2)} ${space(4)};
  244. `;