contextPickerModal.tsx 14 KB

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