contextPickerModal.tsx 16 KB

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