contextPickerModal.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. import React from 'react';
  2. import ReactDOM from 'react-dom';
  3. import {components, StylesConfig} from 'react-select';
  4. import styled from '@emotion/styled';
  5. import createReactClass from 'create-react-class';
  6. import Reflux from 'reflux';
  7. import {ModalRenderProps} from 'app/actionCreators/modal';
  8. import SelectControl from 'app/components/forms/selectControl';
  9. import IdBadge from 'app/components/idBadge';
  10. import Link from 'app/components/links/link';
  11. import LoadingIndicator from 'app/components/loadingIndicator';
  12. import {t, tct} from 'app/locale';
  13. import OrganizationsStore from 'app/stores/organizationsStore';
  14. import OrganizationStore from 'app/stores/organizationStore';
  15. import space from 'app/styles/space';
  16. import {Organization, Project} from 'app/types';
  17. import Projects from 'app/utils/projects';
  18. import replaceRouterParams from 'app/utils/replaceRouterParams';
  19. type Props = ModalRenderProps & {
  20. /**
  21. * The destination route
  22. */
  23. nextPath: string;
  24. /**
  25. * List of available organizations
  26. */
  27. organizations: Organization[];
  28. /**
  29. * Does modal need to prompt for organization.
  30. * TODO(billy): This can be derived from `nextPath`
  31. */
  32. needOrg: boolean;
  33. /**
  34. * Does modal need to prompt for project
  35. */
  36. needProject: boolean;
  37. /**
  38. * Organization slug
  39. */
  40. organization: string;
  41. projects: Project[];
  42. loading: boolean;
  43. /**
  44. * Finish callback
  45. */
  46. onFinish: (path: string) => void;
  47. /**
  48. * Callback for when organization is selected
  49. */
  50. onSelectOrganization: (orgSlug: string) => void;
  51. /**
  52. * Id of the project (most likely from the URL)
  53. * on which the modal was opened
  54. */
  55. comingFromProjectId?: string;
  56. };
  57. const selectStyles = {
  58. menu: (provided: StylesConfig) => ({
  59. ...provided,
  60. position: 'auto',
  61. boxShadow: 'none',
  62. marginBottom: 0,
  63. }),
  64. };
  65. class ContextPickerModal extends React.Component<Props> {
  66. componentDidMount() {
  67. const {organization, projects, organizations} = this.props;
  68. // Don't make any assumptions if there are multiple organizations
  69. if (organizations.length !== 1) {
  70. return;
  71. }
  72. // If there is an org in context (and there's only 1 org available),
  73. // attempt to see if we need more info from user and redirect otherwise
  74. if (organization) {
  75. // This will handle if we can intelligently move the user forward
  76. this.navigateIfFinish([{slug: organization}], projects);
  77. return;
  78. }
  79. }
  80. componentDidUpdate(prevProps: Props) {
  81. // Component may be mounted before projects is fetched, check if we can finish when
  82. // component is updated with projects
  83. if (JSON.stringify(prevProps.projects) !== JSON.stringify(this.props.projects)) {
  84. this.navigateIfFinish(this.props.organizations, this.props.projects);
  85. }
  86. }
  87. // TODO(ts) The various generics in react-select types make getting this
  88. // right hard.
  89. orgSelect: any | null = null;
  90. projectSelect: any | null = null;
  91. // Performs checks to see if we need to prompt user
  92. // i.e. When there is only 1 org and no project is needed or
  93. // there is only 1 org and only 1 project (which should be rare)
  94. navigateIfFinish = (
  95. organizations: Array<{slug: string}>,
  96. projects: Array<{slug: string}>,
  97. latestOrg: string = this.props.organization
  98. ) => {
  99. const {needProject, onFinish, nextPath} = this.props;
  100. // If no project is needed and theres only 1 org OR
  101. // if we need a project and there's only 1 project
  102. // then return because we can't navigate anywhere yet
  103. if (
  104. (!needProject && organizations.length !== 1) ||
  105. (needProject && projects.length !== 1)
  106. ) {
  107. return;
  108. }
  109. // If there is only one org and we dont need a project slug, then call finish callback
  110. if (!needProject) {
  111. onFinish(
  112. replaceRouterParams(nextPath, {
  113. orgId: organizations[0].slug,
  114. })
  115. );
  116. return;
  117. }
  118. // Use latest org or if only 1 org, use that
  119. let org = latestOrg;
  120. if (!org && organizations.length === 1) {
  121. org = organizations[0].slug;
  122. }
  123. onFinish(
  124. replaceRouterParams(nextPath, {
  125. orgId: org,
  126. projectId: projects[0].slug,
  127. project: this.props.projects.find(p => p.slug === projects[0].slug)?.id,
  128. })
  129. );
  130. };
  131. doFocus = (ref: any | null) => {
  132. if (!ref || this.props.loading) {
  133. return;
  134. }
  135. // eslint-disable-next-line react/no-find-dom-node
  136. const el = ReactDOM.findDOMNode(ref) as HTMLElement;
  137. if (el !== null) {
  138. const input = el.querySelector('input');
  139. input && input.focus();
  140. }
  141. };
  142. focusProjectSelector = () => {
  143. this.doFocus(this.projectSelect);
  144. };
  145. focusOrganizationSelector = () => {
  146. this.doFocus(this.orgSelect);
  147. };
  148. handleSelectOrganization = ({value}: {value: string}) => {
  149. // If we do not need to select a project, we can early return after selecting an org
  150. // No need to fetch org details
  151. if (!this.props.needProject) {
  152. this.navigateIfFinish([{slug: value}], []);
  153. return;
  154. }
  155. this.props.onSelectOrganization(value);
  156. };
  157. handleSelectProject = ({value}: {value: string}) => {
  158. const {organization} = this.props;
  159. if (!value || !organization) {
  160. return;
  161. }
  162. this.navigateIfFinish([{slug: organization}], [{slug: value}]);
  163. };
  164. onProjectMenuOpen = () => {
  165. const {projects, comingFromProjectId} = this.props;
  166. // Hacky way to pre-focus to an item with newer versions of react select
  167. // See https://github.com/JedWatson/react-select/issues/3648
  168. setTimeout(() => {
  169. const ref = this.projectSelect;
  170. if (ref) {
  171. const projectChoices = ref.select.state.menuOptions.focusable;
  172. const projectToBeFocused = projects.find(({id}) => id === comingFromProjectId);
  173. const selectedIndex = projectChoices.findIndex(
  174. option => option.value === projectToBeFocused?.slug
  175. );
  176. if (selectedIndex >= 0 && projectToBeFocused) {
  177. // Focusing selected option only if it exists
  178. ref.select.scrollToFocusedOptionOnUpdate = true;
  179. ref.select.inputIsHiddenAfterUpdate = false;
  180. ref.select.setState({
  181. focusedValue: null,
  182. focusedOption: projectChoices[selectedIndex],
  183. });
  184. }
  185. }
  186. });
  187. };
  188. //TODO(TS): Fix typings
  189. customOptionProject = ({label, ...props}: any) => {
  190. const project = this.props.projects.find(({slug}) => props.value === slug);
  191. if (!project) {
  192. return null;
  193. }
  194. return (
  195. <components.Option label={label} {...props}>
  196. <IdBadge
  197. project={project}
  198. avatarSize={20}
  199. displayName={label}
  200. avatarProps={{consistentWidth: true}}
  201. />
  202. </components.Option>
  203. );
  204. };
  205. get headerText() {
  206. const {needOrg, needProject} = this.props;
  207. if (needOrg && needProject) {
  208. return t('Select an organization and a project to continue');
  209. }
  210. if (needOrg) {
  211. return t('Select an organization to continue');
  212. }
  213. if (needProject) {
  214. return t('Select a project to continue');
  215. }
  216. //if neither project nor org needs to be selected, nothing will render anyways
  217. return '';
  218. }
  219. renderProjectSelectOrMessage() {
  220. const {organization, projects} = this.props;
  221. // only show projects the user is a part of
  222. const memberProjects = projects.filter(project => project.isMember);
  223. const projectOptions = memberProjects.map(({slug}) => ({label: slug, value: slug}));
  224. if (!projects.length) {
  225. return (
  226. <div>
  227. {tct('You have no projects. Click [link] to make one.', {
  228. link: (
  229. <Link to={`/organizations/${organization}/projects/new/`}>{t('here')}</Link>
  230. ),
  231. })}
  232. </div>
  233. );
  234. }
  235. return (
  236. <StyledSelectControl
  237. ref={(ref: any) => {
  238. this.projectSelect = ref;
  239. this.focusProjectSelector();
  240. }}
  241. placeholder={t('Select a Project to continue')}
  242. name="project"
  243. options={projectOptions}
  244. onChange={this.handleSelectProject}
  245. onMenuOpen={this.onProjectMenuOpen}
  246. components={{Option: this.customOptionProject, DropdownIndicator: null}}
  247. styles={selectStyles}
  248. menuIsOpen
  249. />
  250. );
  251. }
  252. render() {
  253. const {
  254. needOrg,
  255. needProject,
  256. organization,
  257. organizations,
  258. loading,
  259. Header,
  260. Body,
  261. } = this.props;
  262. const shouldShowPicker = needOrg || needProject;
  263. if (!shouldShowPicker) {
  264. return null;
  265. }
  266. const shouldShowProjectSelector = organization && needProject && !loading;
  267. const orgChoices = organizations
  268. .filter(({status}) => status.id !== 'pending_deletion')
  269. .map(({slug}) => ({label: slug, value: slug}));
  270. return (
  271. <React.Fragment>
  272. <Header closeButton>{this.headerText}</Header>
  273. <Body>
  274. {loading && <StyledLoadingIndicator overlay />}
  275. {needOrg && (
  276. <StyledSelectControl
  277. ref={(ref: any) => {
  278. this.orgSelect = ref;
  279. if (shouldShowProjectSelector) {
  280. return;
  281. }
  282. this.focusOrganizationSelector();
  283. }}
  284. placeholder={t('Select an Organization')}
  285. name="organization"
  286. options={orgChoices}
  287. value={organization}
  288. onChange={this.handleSelectOrganization}
  289. components={{DropdownIndicator: null}}
  290. styles={selectStyles}
  291. menuIsOpen
  292. />
  293. )}
  294. {shouldShowProjectSelector && this.renderProjectSelectOrMessage()}
  295. </Body>
  296. </React.Fragment>
  297. );
  298. }
  299. }
  300. type ContainerProps = Omit<
  301. Props,
  302. 'projects' | 'loading' | 'organizations' | 'organization' | 'onSelectOrganization'
  303. > & {
  304. /**
  305. * List of slugs we want to be able to choose from
  306. */
  307. projectSlugs?: string[];
  308. };
  309. type ContainerState = {
  310. selectedOrganization?: string;
  311. organizations?: Organization[];
  312. };
  313. const ContextPickerModalContainer = createReactClass<ContainerProps, ContainerState>({
  314. displayName: 'ContextPickerModalContainer',
  315. mixins: [Reflux.connect(OrganizationsStore, 'organizations') as any],
  316. getInitialState() {
  317. const storeState = OrganizationStore.get();
  318. return {
  319. selectedOrganization: storeState.organization?.slug,
  320. };
  321. },
  322. handleSelectOrganization(organizationSlug: string) {
  323. this.setState({selectedOrganization: organizationSlug});
  324. },
  325. renderModal({projects, initiallyLoaded}) {
  326. return (
  327. <ContextPickerModal
  328. {...this.props}
  329. projects={projects || []}
  330. loading={!initiallyLoaded}
  331. organizations={this.state.organizations}
  332. organization={this.state.selectedOrganization}
  333. onSelectOrganization={this.handleSelectOrganization}
  334. />
  335. );
  336. },
  337. render() {
  338. const {projectSlugs} = this.props; // eslint-disable-line react/prop-types
  339. if (this.state.selectedOrganization) {
  340. return (
  341. <Projects
  342. orgId={this.state.selectedOrganization}
  343. allProjects={!projectSlugs?.length}
  344. slugs={projectSlugs}
  345. >
  346. {renderProps => this.renderModal(renderProps)}
  347. </Projects>
  348. );
  349. }
  350. return this.renderModal({});
  351. },
  352. });
  353. export default ContextPickerModalContainer;
  354. const StyledSelectControl = styled(SelectControl)`
  355. margin-top: ${space(1)};
  356. `;
  357. const StyledLoadingIndicator = styled(LoadingIndicator)`
  358. z-index: 1;
  359. `;