contextPickerModal.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  1. import {Component, Fragment} from 'react';
  2. import {findDOMNode} from 'react-dom';
  3. import {components, StylesConfig} from 'react-select';
  4. import styled from '@emotion/styled';
  5. import {ModalRenderProps} from 'sentry/actionCreators/modal';
  6. import AsyncComponent from 'sentry/components/asyncComponent';
  7. import SelectControl from 'sentry/components/forms/selectControl';
  8. import IdBadge from 'sentry/components/idBadge';
  9. import Link from 'sentry/components/links/link';
  10. import LoadingIndicator from 'sentry/components/loadingIndicator';
  11. import {t, tct} from 'sentry/locale';
  12. import ConfigStore from 'sentry/stores/configStore';
  13. import OrganizationsStore from 'sentry/stores/organizationsStore';
  14. import OrganizationStore from 'sentry/stores/organizationStore';
  15. import space from 'sentry/styles/space';
  16. import {Integration, Organization, Project} from 'sentry/types';
  17. import Projects from 'sentry/utils/projects';
  18. import replaceRouterParams from 'sentry/utils/replaceRouterParams';
  19. import IntegrationIcon from 'sentry/views/organizationIntegrations/integrationIcon';
  20. type Props = ModalRenderProps & {
  21. integrationConfigs: Integration[];
  22. loading: boolean;
  23. /**
  24. * Does modal need to prompt for organization.
  25. * TODO(billy): This can be derived from `nextPath`
  26. */
  27. needOrg: boolean;
  28. /**
  29. * Does modal need to prompt for project
  30. */
  31. needProject: boolean;
  32. /**
  33. * The destination route
  34. */
  35. nextPath: string;
  36. /**
  37. * Finish callback
  38. */
  39. onFinish: (path: string) => number | void;
  40. /**
  41. * Callback for when organization is selected
  42. */
  43. onSelectOrganization: (orgSlug: string) => void;
  44. /**
  45. * Organization slug
  46. */
  47. organization: string;
  48. /**
  49. * List of available organizations
  50. */
  51. organizations: Organization[];
  52. projects: Project[];
  53. };
  54. const selectStyles: StylesConfig = {
  55. menu: provided => ({
  56. ...provided,
  57. position: 'initial',
  58. boxShadow: 'none',
  59. marginBottom: 0,
  60. }),
  61. option: (provided, state: any) => ({
  62. ...provided,
  63. opacity: state.isDisabled ? 0.6 : 1,
  64. cursor: state.isDisabled ? 'not-allowed' : 'pointer',
  65. pointerEvents: state.isDisabled ? 'none' : 'auto',
  66. }),
  67. };
  68. class ContextPickerModal extends Component<Props> {
  69. componentDidMount() {
  70. const {organization, projects, organizations} = this.props;
  71. // Don't make any assumptions if there are multiple organizations
  72. if (organizations.length !== 1) {
  73. return;
  74. }
  75. // If there is an org in context (and there's only 1 org available),
  76. // attempt to see if we need more info from user and redirect otherwise
  77. if (organization) {
  78. // This will handle if we can intelligently move the user forward
  79. this.navigateIfFinish([{slug: organization}], projects);
  80. return;
  81. }
  82. }
  83. componentDidUpdate(prevProps: Props) {
  84. // Component may be mounted before projects is fetched, check if we can finish when
  85. // component is updated with projects
  86. if (JSON.stringify(prevProps.projects) !== JSON.stringify(this.props.projects)) {
  87. this.navigateIfFinish(this.props.organizations, this.props.projects);
  88. }
  89. }
  90. componentWillUnmount() {
  91. window.clearTimeout(this.onFinishTimeout);
  92. }
  93. onFinishTimeout: number | undefined = undefined;
  94. // TODO(ts) The various generics in react-select types make getting this
  95. // right hard.
  96. orgSelect: any | null = null;
  97. projectSelect: any | null = null;
  98. configSelect: any | null = null;
  99. // Performs checks to see if we need to prompt user
  100. // i.e. When there is only 1 org and no project is needed or
  101. // there is only 1 org and only 1 project (which should be rare)
  102. navigateIfFinish = (
  103. organizations: Array<{slug: string}>,
  104. projects: Array<{slug: string}>,
  105. latestOrg: string = this.props.organization
  106. ) => {
  107. const {needProject, onFinish, nextPath, integrationConfigs} = this.props;
  108. const {isSuperuser} = ConfigStore.get('user') || {};
  109. // If no project is needed and theres only 1 org OR
  110. // if we need a project and there's only 1 project
  111. // then return because we can't navigate anywhere yet
  112. if (
  113. (!needProject && organizations.length !== 1) ||
  114. (needProject && projects.length !== 1) ||
  115. (integrationConfigs.length && isSuperuser)
  116. ) {
  117. return;
  118. }
  119. window.clearTimeout(this.onFinishTimeout);
  120. // If there is only one org and we don't need a project slug, then call finish callback
  121. if (!needProject) {
  122. this.onFinishTimeout =
  123. onFinish(
  124. replaceRouterParams(nextPath, {
  125. orgId: organizations[0].slug,
  126. })
  127. ) ?? undefined;
  128. return;
  129. }
  130. // Use latest org or if only 1 org, use that
  131. let org = latestOrg;
  132. if (!org && organizations.length === 1) {
  133. org = organizations[0].slug;
  134. }
  135. this.onFinishTimeout =
  136. onFinish(
  137. replaceRouterParams(nextPath, {
  138. orgId: org,
  139. projectId: projects[0].slug,
  140. project: this.props.projects.find(p => p.slug === projects[0].slug)?.id,
  141. })
  142. ) ?? undefined;
  143. };
  144. doFocus = (ref: any | null) => {
  145. if (!ref || this.props.loading) {
  146. return;
  147. }
  148. // eslint-disable-next-line react/no-find-dom-node
  149. const el = findDOMNode(ref) as HTMLElement;
  150. if (el !== null) {
  151. const input = el.querySelector('input');
  152. input && input.focus();
  153. }
  154. };
  155. handleSelectOrganization = ({value}: {value: string}) => {
  156. // If we do not need to select a project, we can early return after selecting an org
  157. // No need to fetch org details
  158. if (!this.props.needProject) {
  159. this.navigateIfFinish([{slug: value}], []);
  160. return;
  161. }
  162. this.props.onSelectOrganization(value);
  163. };
  164. handleSelectProject = ({value}: {value: string}) => {
  165. const {organization} = this.props;
  166. if (!value || !organization) {
  167. return;
  168. }
  169. this.navigateIfFinish([{slug: organization}], [{slug: value}]);
  170. };
  171. handleSelectConfiguration = ({value}: {value: string}) => {
  172. const {onFinish, nextPath} = this.props;
  173. if (!value) {
  174. return;
  175. }
  176. onFinish(`${nextPath}${value}/`);
  177. return;
  178. };
  179. getMemberProjects = () => {
  180. const {projects} = this.props;
  181. const nonMemberProjects: Project[] = [];
  182. const memberProjects: Project[] = [];
  183. projects.forEach(project =>
  184. project.isMember ? memberProjects.push(project) : nonMemberProjects.push(project)
  185. );
  186. return [memberProjects, nonMemberProjects];
  187. };
  188. // TODO(TS): Fix typings
  189. customOptionProject = ({label, ...props}: any) => {
  190. const project = this.props.projects.find(({slug}) => props.value === slug);
  191. if (!project) {
  192. return null;
  193. }
  194. return (
  195. <components.Option label={label} {...props}>
  196. <ProjectBadgeOption
  197. project={project}
  198. avatarSize={20}
  199. displayName={label}
  200. avatarProps={{consistentWidth: true}}
  201. disableLink
  202. />
  203. </components.Option>
  204. );
  205. };
  206. get headerText() {
  207. const {needOrg, needProject, integrationConfigs} = this.props;
  208. if (needOrg && needProject) {
  209. return t('Select an organization and a project to continue');
  210. }
  211. if (needOrg) {
  212. return t('Select an organization to continue');
  213. }
  214. if (needProject) {
  215. return t('Select a project to continue');
  216. }
  217. if (integrationConfigs.length) {
  218. return t('Select a configuration to continue');
  219. }
  220. // if neither project nor org needs to be selected, nothing will render anyways
  221. return '';
  222. }
  223. renderProjectSelectOrMessage() {
  224. const {organization, projects} = this.props;
  225. const [memberProjects, nonMemberProjects] = this.getMemberProjects();
  226. const {isSuperuser} = ConfigStore.get('user') || {};
  227. const projectOptions = [
  228. {
  229. label: t('My Projects'),
  230. options: memberProjects.map(p => ({
  231. value: p.slug,
  232. label: t(`${p.slug}`),
  233. disabled: false,
  234. })),
  235. },
  236. {
  237. label: t('All Projects'),
  238. options: nonMemberProjects.map(p => ({
  239. value: p.slug,
  240. label: t(`${p.slug}`),
  241. disabled: isSuperuser ? false : true,
  242. })),
  243. },
  244. ];
  245. if (!projects.length) {
  246. return (
  247. <div>
  248. {tct('You have no projects. Click [link] to make one.', {
  249. link: (
  250. <Link to={`/organizations/${organization}/projects/new/`}>{t('here')}</Link>
  251. ),
  252. })}
  253. </div>
  254. );
  255. }
  256. return (
  257. <StyledSelectControl
  258. ref={(ref: any) => {
  259. this.projectSelect = ref;
  260. this.doFocus(this.projectSelect);
  261. }}
  262. placeholder={t('Select a Project to continue')}
  263. name="project"
  264. options={projectOptions}
  265. onChange={this.handleSelectProject}
  266. components={{Option: this.customOptionProject, DropdownIndicator: null}}
  267. styles={selectStyles}
  268. menuIsOpen
  269. />
  270. );
  271. }
  272. renderIntegrationConfigs() {
  273. const {integrationConfigs} = this.props;
  274. const {isSuperuser} = ConfigStore.get('user') || {};
  275. const options = [
  276. {
  277. label: tct('[providerName] Configurations', {
  278. providerName: integrationConfigs[0].provider.name,
  279. }),
  280. options: integrationConfigs.map(config => ({
  281. value: config.id,
  282. label: (
  283. <StyledIntegrationItem>
  284. <IntegrationIcon size={22} integration={config} />
  285. <span>{config.domainName}</span>
  286. </StyledIntegrationItem>
  287. ),
  288. disabled: isSuperuser ? false : true,
  289. })),
  290. },
  291. ];
  292. return (
  293. <StyledSelectControl
  294. ref={(ref: any) => {
  295. this.configSelect = ref;
  296. this.doFocus(this.configSelect);
  297. }}
  298. placeholder={t('Select a configuration to continue')}
  299. name="configurations"
  300. options={options}
  301. onChange={this.handleSelectConfiguration}
  302. components={{DropdownIndicator: null}}
  303. styles={selectStyles}
  304. menuIsOpen
  305. />
  306. );
  307. }
  308. render() {
  309. const {
  310. needOrg,
  311. needProject,
  312. organization,
  313. organizations,
  314. loading,
  315. Header,
  316. Body,
  317. integrationConfigs,
  318. } = this.props;
  319. const {isSuperuser} = ConfigStore.get('user') || {};
  320. const shouldShowProjectSelector = organization && needProject && !loading;
  321. const shouldShowConfigSelector = integrationConfigs.length > 0 && isSuperuser;
  322. const orgChoices = organizations
  323. .filter(({status}) => status.id !== 'pending_deletion')
  324. .map(({slug}) => ({label: slug, value: slug}));
  325. const shouldShowPicker = needOrg || needProject || shouldShowConfigSelector;
  326. if (!shouldShowPicker) {
  327. return null;
  328. }
  329. return (
  330. <Fragment>
  331. <Header closeButton>{this.headerText}</Header>
  332. <Body>
  333. {loading && <StyledLoadingIndicator overlay />}
  334. {needOrg && (
  335. <StyledSelectControl
  336. ref={(ref: any) => {
  337. this.orgSelect = ref;
  338. if (shouldShowProjectSelector) {
  339. return;
  340. }
  341. this.doFocus(this.orgSelect);
  342. }}
  343. placeholder={t('Select an Organization')}
  344. name="organization"
  345. options={orgChoices}
  346. value={organization}
  347. onChange={this.handleSelectOrganization}
  348. components={{DropdownIndicator: null}}
  349. styles={selectStyles}
  350. menuIsOpen
  351. />
  352. )}
  353. {shouldShowProjectSelector && this.renderProjectSelectOrMessage()}
  354. {shouldShowConfigSelector && this.renderIntegrationConfigs()}
  355. </Body>
  356. </Fragment>
  357. );
  358. }
  359. }
  360. type ContainerProps = Omit<
  361. Props,
  362. | 'projects'
  363. | 'loading'
  364. | 'organizations'
  365. | 'organization'
  366. | 'onSelectOrganization'
  367. | 'integrationConfigs'
  368. > & {
  369. configUrl?: string;
  370. /**
  371. * List of slugs we want to be able to choose from
  372. */
  373. projectSlugs?: string[];
  374. } & AsyncComponent['props'];
  375. type ContainerState = {
  376. organizations: Organization[];
  377. integrationConfigs?: Integration[];
  378. selectedOrganization?: string;
  379. } & AsyncComponent['state'];
  380. class ContextPickerModalContainer extends AsyncComponent<ContainerProps, ContainerState> {
  381. getDefaultState() {
  382. const storeState = OrganizationStore.get();
  383. return {
  384. ...super.getDefaultState(),
  385. organizations: OrganizationsStore.getAll(),
  386. selectedOrganization: storeState.organization?.slug,
  387. };
  388. }
  389. getEndpoints(): ReturnType<AsyncComponent['getEndpoints']> {
  390. const {configUrl} = this.props;
  391. if (configUrl) {
  392. return [['integrationConfigs', configUrl]];
  393. }
  394. return [];
  395. }
  396. componentWillUnmount() {
  397. this.unlistener?.();
  398. }
  399. unlistener = OrganizationsStore.listen(
  400. (organizations: Organization[]) => this.setState({organizations}),
  401. undefined
  402. );
  403. handleSelectOrganization = (organizationSlug: string) => {
  404. this.setState({selectedOrganization: organizationSlug});
  405. };
  406. renderModal({
  407. projects,
  408. initiallyLoaded,
  409. integrationConfigs,
  410. }: {
  411. initiallyLoaded?: boolean;
  412. integrationConfigs?: Integration[];
  413. projects?: Project[];
  414. }) {
  415. return (
  416. <ContextPickerModal
  417. {...this.props}
  418. projects={projects || []}
  419. loading={!initiallyLoaded}
  420. organizations={this.state.organizations}
  421. organization={this.state.selectedOrganization!}
  422. onSelectOrganization={this.handleSelectOrganization}
  423. integrationConfigs={integrationConfigs || []}
  424. />
  425. );
  426. }
  427. render() {
  428. const {projectSlugs, configUrl} = this.props;
  429. if (configUrl && this.state.loading) {
  430. return <LoadingIndicator />;
  431. }
  432. if (this.state.integrationConfigs?.length) {
  433. return this.renderModal({
  434. integrationConfigs: this.state.integrationConfigs,
  435. initiallyLoaded: !this.state.loading,
  436. });
  437. }
  438. if (this.state.selectedOrganization) {
  439. return (
  440. <Projects
  441. orgId={this.state.selectedOrganization}
  442. allProjects={!projectSlugs?.length}
  443. slugs={projectSlugs}
  444. >
  445. {({projects, initiallyLoaded}) =>
  446. this.renderModal({projects: projects as Project[], initiallyLoaded})
  447. }
  448. </Projects>
  449. );
  450. }
  451. return this.renderModal({});
  452. }
  453. }
  454. export default ContextPickerModalContainer;
  455. const StyledSelectControl = styled(SelectControl)`
  456. margin-top: ${space(1)};
  457. `;
  458. const ProjectBadgeOption = styled(IdBadge)`
  459. margin: ${space(1)};
  460. `;
  461. const StyledLoadingIndicator = styled(LoadingIndicator)`
  462. z-index: 1;
  463. `;
  464. const StyledIntegrationItem = styled('div')`
  465. display: grid;
  466. grid-template-columns: ${space(4)} auto;
  467. grid-template-rows: 1fr;
  468. `;