contextPickerModal.tsx 16 KB

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