contextPickerModal.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  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 SelectControl from 'app/components/forms/selectControl';
  7. import IdBadge from 'app/components/idBadge';
  8. import Link from 'app/components/links/link';
  9. import LoadingIndicator from 'app/components/loadingIndicator';
  10. import {t, tct} from 'app/locale';
  11. import ConfigStore from 'app/stores/configStore';
  12. import OrganizationsStore from 'app/stores/organizationsStore';
  13. import OrganizationStore from 'app/stores/organizationStore';
  14. import space from 'app/styles/space';
  15. import {Organization, Project} from 'app/types';
  16. import Projects from 'app/utils/projects';
  17. import replaceRouterParams from 'app/utils/replaceRouterParams';
  18. type Props = ModalRenderProps & {
  19. /**
  20. * The destination route
  21. */
  22. nextPath: string;
  23. /**
  24. * List of available organizations
  25. */
  26. organizations: Organization[];
  27. /**
  28. * Does modal need to prompt for organization.
  29. * TODO(billy): This can be derived from `nextPath`
  30. */
  31. needOrg: boolean;
  32. /**
  33. * Does modal need to prompt for project
  34. */
  35. needProject: boolean;
  36. /**
  37. * Organization slug
  38. */
  39. organization: string;
  40. projects: Project[];
  41. loading: boolean;
  42. /**
  43. * Finish callback
  44. */
  45. onFinish: (path: string) => void;
  46. /**
  47. * Callback for when organization is selected
  48. */
  49. onSelectOrganization: (orgSlug: string) => void;
  50. /**
  51. * Id of the project (most likely from the URL)
  52. * on which the modal was opened
  53. */
  54. comingFromProjectId?: string;
  55. };
  56. const selectStyles = {
  57. menu: (provided: StylesConfig) => ({
  58. ...provided,
  59. position: 'auto',
  60. boxShadow: 'none',
  61. marginBottom: 0,
  62. }),
  63. option: (provided: StylesConfig, 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. // TODO(ts) The various generics in react-select types make getting this
  93. // right hard.
  94. orgSelect: any | null = null;
  95. projectSelect: any | null = null;
  96. // Performs checks to see if we need to prompt user
  97. // i.e. When there is only 1 org and no project is needed or
  98. // there is only 1 org and only 1 project (which should be rare)
  99. navigateIfFinish = (
  100. organizations: Array<{slug: string}>,
  101. projects: Array<{slug: string}>,
  102. latestOrg: string = this.props.organization
  103. ) => {
  104. const {needProject, onFinish, nextPath} = this.props;
  105. // If no project is needed and theres only 1 org OR
  106. // if we need a project and there's only 1 project
  107. // then return because we can't navigate anywhere yet
  108. if (
  109. (!needProject && organizations.length !== 1) ||
  110. (needProject && projects.length !== 1)
  111. ) {
  112. return;
  113. }
  114. // If there is only one org and we dont need a project slug, then call finish callback
  115. if (!needProject) {
  116. onFinish(
  117. replaceRouterParams(nextPath, {
  118. orgId: organizations[0].slug,
  119. })
  120. );
  121. return;
  122. }
  123. // Use latest org or if only 1 org, use that
  124. let org = latestOrg;
  125. if (!org && organizations.length === 1) {
  126. org = organizations[0].slug;
  127. }
  128. onFinish(
  129. replaceRouterParams(nextPath, {
  130. orgId: org,
  131. projectId: projects[0].slug,
  132. project: this.props.projects.find(p => p.slug === projects[0].slug)?.id,
  133. })
  134. );
  135. };
  136. doFocus = (ref: any | null) => {
  137. if (!ref || this.props.loading) {
  138. return;
  139. }
  140. // eslint-disable-next-line react/no-find-dom-node
  141. const el = ReactDOM.findDOMNode(ref) as HTMLElement;
  142. if (el !== null) {
  143. const input = el.querySelector('input');
  144. input && input.focus();
  145. }
  146. };
  147. focusProjectSelector = () => {
  148. this.doFocus(this.projectSelect);
  149. };
  150. focusOrganizationSelector = () => {
  151. this.doFocus(this.orgSelect);
  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. getMemberProjects = () => {
  170. const {projects} = this.props;
  171. const nonMemberProjects: Project[] = [];
  172. const memberProjects: Project[] = [];
  173. projects.forEach(project =>
  174. project.isMember ? memberProjects.push(project) : nonMemberProjects.push(project)
  175. );
  176. return [memberProjects, nonMemberProjects];
  177. };
  178. onProjectMenuOpen = () => {
  179. const {projects, comingFromProjectId} = this.props;
  180. // Hacky way to pre-focus to an item with newer versions of react select
  181. // See https://github.com/JedWatson/react-select/issues/3648
  182. setTimeout(() => {
  183. const ref = this.projectSelect;
  184. if (ref) {
  185. const projectChoices = ref.select.state.menuOptions.focusable;
  186. const projectToBeFocused = projects.find(({id}) => id === comingFromProjectId);
  187. const selectedIndex = projectChoices.findIndex(
  188. option => option.value === projectToBeFocused?.slug
  189. );
  190. if (selectedIndex >= 0 && projectToBeFocused) {
  191. // Focusing selected option only if it exists
  192. ref.select.scrollToFocusedOptionOnUpdate = true;
  193. ref.select.inputIsHiddenAfterUpdate = false;
  194. ref.select.setState({
  195. focusedValue: null,
  196. focusedOption: projectChoices[selectedIndex],
  197. });
  198. }
  199. }
  200. });
  201. };
  202. //TODO(TS): Fix typings
  203. customOptionProject = ({label, ...props}: any) => {
  204. const project = this.props.projects.find(({slug}) => props.value === slug);
  205. if (!project) {
  206. return null;
  207. }
  208. return (
  209. <components.Option label={label} {...props}>
  210. <IdBadge
  211. project={project}
  212. avatarSize={20}
  213. displayName={label}
  214. avatarProps={{consistentWidth: true}}
  215. />
  216. </components.Option>
  217. );
  218. };
  219. get headerText() {
  220. const {needOrg, needProject} = this.props;
  221. if (needOrg && needProject) {
  222. return t('Select an organization and a project to continue');
  223. }
  224. if (needOrg) {
  225. return t('Select an organization to continue');
  226. }
  227. if (needProject) {
  228. return t('Select a project to continue');
  229. }
  230. //if neither project nor org needs to be selected, nothing will render anyways
  231. return '';
  232. }
  233. renderProjectSelectOrMessage() {
  234. const {organization, projects} = this.props;
  235. const [memberProjects, nonMemberProjects] = this.getMemberProjects();
  236. const {isSuperuser} = ConfigStore.get('user') || {};
  237. const projectOptions = [
  238. {
  239. label: t('My Projects'),
  240. options: memberProjects.map(p => ({
  241. value: p.slug,
  242. label: t(`${p.slug}`),
  243. isDisabled: false,
  244. })),
  245. },
  246. {
  247. label: t('All Projects'),
  248. options: nonMemberProjects.map(p => ({
  249. value: p.slug,
  250. label: t(`${p.slug}`),
  251. isDisabled: isSuperuser ? false : true,
  252. })),
  253. },
  254. ];
  255. if (!projects.length) {
  256. return (
  257. <div>
  258. {tct('You have no projects. Click [link] to make one.', {
  259. link: (
  260. <Link to={`/organizations/${organization}/projects/new/`}>{t('here')}</Link>
  261. ),
  262. })}
  263. </div>
  264. );
  265. }
  266. return (
  267. <StyledSelectControl
  268. ref={(ref: any) => {
  269. this.projectSelect = ref;
  270. this.focusProjectSelector();
  271. }}
  272. placeholder={t('Select a Project to continue')}
  273. name="project"
  274. options={projectOptions}
  275. onChange={this.handleSelectProject}
  276. onMenuOpen={this.onProjectMenuOpen}
  277. components={{Option: this.customOptionProject, DropdownIndicator: null}}
  278. styles={selectStyles}
  279. menuIsOpen
  280. />
  281. );
  282. }
  283. render() {
  284. const {
  285. needOrg,
  286. needProject,
  287. organization,
  288. organizations,
  289. loading,
  290. Header,
  291. Body,
  292. } = this.props;
  293. const shouldShowPicker = needOrg || needProject;
  294. if (!shouldShowPicker) {
  295. return null;
  296. }
  297. const shouldShowProjectSelector = organization && needProject && !loading;
  298. const orgChoices = organizations
  299. .filter(({status}) => status.id !== 'pending_deletion')
  300. .map(({slug}) => ({label: slug, value: slug}));
  301. return (
  302. <Fragment>
  303. <Header closeButton>{this.headerText}</Header>
  304. <Body>
  305. {loading && <StyledLoadingIndicator overlay />}
  306. {needOrg && (
  307. <StyledSelectControl
  308. ref={(ref: any) => {
  309. this.orgSelect = ref;
  310. if (shouldShowProjectSelector) {
  311. return;
  312. }
  313. this.focusOrganizationSelector();
  314. }}
  315. placeholder={t('Select an Organization')}
  316. name="organization"
  317. options={orgChoices}
  318. value={organization}
  319. onChange={this.handleSelectOrganization}
  320. components={{DropdownIndicator: null}}
  321. styles={selectStyles}
  322. menuIsOpen
  323. />
  324. )}
  325. {shouldShowProjectSelector && this.renderProjectSelectOrMessage()}
  326. </Body>
  327. </Fragment>
  328. );
  329. }
  330. }
  331. type ContainerProps = Omit<
  332. Props,
  333. 'projects' | 'loading' | 'organizations' | 'organization' | 'onSelectOrganization'
  334. > & {
  335. /**
  336. * List of slugs we want to be able to choose from
  337. */
  338. projectSlugs?: string[];
  339. };
  340. type ContainerState = {
  341. selectedOrganization?: string;
  342. organizations: Organization[];
  343. };
  344. class ContextPickerModalContainer extends Component<ContainerProps, ContainerState> {
  345. state = this.getInitialState();
  346. getInitialState(): ContainerState {
  347. const storeState = OrganizationStore.get();
  348. return {
  349. organizations: OrganizationsStore.getAll(),
  350. selectedOrganization: storeState.organization?.slug,
  351. };
  352. }
  353. componentWillUnmount() {
  354. this.unlistener?.();
  355. }
  356. unlistener = OrganizationsStore.listen(
  357. (organizations: Organization[]) => this.setState({organizations}),
  358. undefined
  359. );
  360. handleSelectOrganization = (organizationSlug: string) => {
  361. this.setState({selectedOrganization: organizationSlug});
  362. };
  363. renderModal({
  364. projects,
  365. initiallyLoaded,
  366. }: {
  367. projects?: Project[];
  368. initiallyLoaded?: boolean;
  369. }) {
  370. return (
  371. <ContextPickerModal
  372. {...this.props}
  373. projects={projects || []}
  374. loading={!initiallyLoaded}
  375. organizations={this.state.organizations}
  376. organization={this.state.selectedOrganization!}
  377. onSelectOrganization={this.handleSelectOrganization}
  378. />
  379. );
  380. }
  381. render() {
  382. const {projectSlugs} = this.props;
  383. if (this.state.selectedOrganization) {
  384. return (
  385. <Projects
  386. orgId={this.state.selectedOrganization}
  387. allProjects={!projectSlugs?.length}
  388. slugs={projectSlugs}
  389. >
  390. {({projects, initiallyLoaded}) =>
  391. this.renderModal({projects: projects as Project[], initiallyLoaded})
  392. }
  393. </Projects>
  394. );
  395. }
  396. return this.renderModal({});
  397. }
  398. }
  399. export default ContextPickerModalContainer;
  400. const StyledSelectControl = styled(SelectControl)`
  401. margin-top: ${space(1)};
  402. `;
  403. const StyledLoadingIndicator = styled(LoadingIndicator)`
  404. z-index: 1;
  405. `;