contextPickerModal.tsx 15 KB

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