projectContext.tsx 7.8 KB

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