contextPickerModal.tsx 15 KB

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