projectContext.tsx 8.0 KB

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