123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468 |
- import React from 'react';
- import ReactDOM from 'react-dom';
- import {components, StylesConfig} from 'react-select';
- import styled from '@emotion/styled';
- import {ModalRenderProps} from 'app/actionCreators/modal';
- import SelectControl from 'app/components/forms/selectControl';
- import IdBadge from 'app/components/idBadge';
- import Link from 'app/components/links/link';
- import LoadingIndicator from 'app/components/loadingIndicator';
- import {t, tct} from 'app/locale';
- import ConfigStore from 'app/stores/configStore';
- import OrganizationsStore from 'app/stores/organizationsStore';
- import OrganizationStore from 'app/stores/organizationStore';
- import space from 'app/styles/space';
- import {Organization, Project} from 'app/types';
- import Projects from 'app/utils/projects';
- import replaceRouterParams from 'app/utils/replaceRouterParams';
- type Props = ModalRenderProps & {
- /**
- * The destination route
- */
- nextPath: string;
- /**
- * List of available organizations
- */
- organizations: Organization[];
- /**
- * Does modal need to prompt for organization.
- * TODO(billy): This can be derived from `nextPath`
- */
- needOrg: boolean;
- /**
- * Does modal need to prompt for project
- */
- needProject: boolean;
- /**
- * Organization slug
- */
- organization: string;
- projects: Project[];
- loading: boolean;
- /**
- * Finish callback
- */
- onFinish: (path: string) => void;
- /**
- * Callback for when organization is selected
- */
- onSelectOrganization: (orgSlug: string) => void;
- /**
- * Id of the project (most likely from the URL)
- * on which the modal was opened
- */
- comingFromProjectId?: string;
- };
- const selectStyles = {
- menu: (provided: StylesConfig) => ({
- ...provided,
- position: 'auto',
- boxShadow: 'none',
- marginBottom: 0,
- }),
- option: (provided: StylesConfig, state: any) => ({
- ...provided,
- opacity: state.isDisabled ? 0.6 : 1,
- cursor: state.isDisabled ? 'not-allowed' : 'pointer',
- pointerEvents: state.isDisabled ? 'none' : 'auto',
- }),
- };
- class ContextPickerModal extends React.Component<Props> {
- componentDidMount() {
- const {organization, projects, organizations} = this.props;
- // Don't make any assumptions if there are multiple organizations
- if (organizations.length !== 1) {
- return;
- }
- // If there is an org in context (and there's only 1 org available),
- // attempt to see if we need more info from user and redirect otherwise
- if (organization) {
- // This will handle if we can intelligently move the user forward
- this.navigateIfFinish([{slug: organization}], projects);
- return;
- }
- }
- componentDidUpdate(prevProps: Props) {
- // Component may be mounted before projects is fetched, check if we can finish when
- // component is updated with projects
- if (JSON.stringify(prevProps.projects) !== JSON.stringify(this.props.projects)) {
- this.navigateIfFinish(this.props.organizations, this.props.projects);
- }
- }
- // TODO(ts) The various generics in react-select types make getting this
- // right hard.
- orgSelect: any | null = null;
- projectSelect: any | null = null;
- // Performs checks to see if we need to prompt user
- // i.e. When there is only 1 org and no project is needed or
- // there is only 1 org and only 1 project (which should be rare)
- navigateIfFinish = (
- organizations: Array<{slug: string}>,
- projects: Array<{slug: string}>,
- latestOrg: string = this.props.organization
- ) => {
- const {needProject, onFinish, nextPath} = this.props;
- // If no project is needed and theres only 1 org OR
- // if we need a project and there's only 1 project
- // then return because we can't navigate anywhere yet
- if (
- (!needProject && organizations.length !== 1) ||
- (needProject && projects.length !== 1)
- ) {
- return;
- }
- // If there is only one org and we dont need a project slug, then call finish callback
- if (!needProject) {
- onFinish(
- replaceRouterParams(nextPath, {
- orgId: organizations[0].slug,
- })
- );
- return;
- }
- // Use latest org or if only 1 org, use that
- let org = latestOrg;
- if (!org && organizations.length === 1) {
- org = organizations[0].slug;
- }
- onFinish(
- replaceRouterParams(nextPath, {
- orgId: org,
- projectId: projects[0].slug,
- project: this.props.projects.find(p => p.slug === projects[0].slug)?.id,
- })
- );
- };
- doFocus = (ref: any | null) => {
- if (!ref || this.props.loading) {
- return;
- }
- // eslint-disable-next-line react/no-find-dom-node
- const el = ReactDOM.findDOMNode(ref) as HTMLElement;
- if (el !== null) {
- const input = el.querySelector('input');
- input && input.focus();
- }
- };
- focusProjectSelector = () => {
- this.doFocus(this.projectSelect);
- };
- focusOrganizationSelector = () => {
- this.doFocus(this.orgSelect);
- };
- handleSelectOrganization = ({value}: {value: string}) => {
- // If we do not need to select a project, we can early return after selecting an org
- // No need to fetch org details
- if (!this.props.needProject) {
- this.navigateIfFinish([{slug: value}], []);
- return;
- }
- this.props.onSelectOrganization(value);
- };
- handleSelectProject = ({value}: {value: string}) => {
- const {organization} = this.props;
- if (!value || !organization) {
- return;
- }
- this.navigateIfFinish([{slug: organization}], [{slug: value}]);
- };
- getMemberProjects = () => {
- const {projects} = this.props;
- const nonMemberProjects: Project[] = [];
- const memberProjects: Project[] = [];
- projects.forEach(project =>
- project.isMember ? memberProjects.push(project) : nonMemberProjects.push(project)
- );
- return [memberProjects, nonMemberProjects];
- };
- onProjectMenuOpen = () => {
- const {projects, comingFromProjectId} = this.props;
- // Hacky way to pre-focus to an item with newer versions of react select
- // See https://github.com/JedWatson/react-select/issues/3648
- setTimeout(() => {
- const ref = this.projectSelect;
- if (ref) {
- const projectChoices = ref.select.state.menuOptions.focusable;
- const projectToBeFocused = projects.find(({id}) => id === comingFromProjectId);
- const selectedIndex = projectChoices.findIndex(
- option => option.value === projectToBeFocused?.slug
- );
- if (selectedIndex >= 0 && projectToBeFocused) {
- // Focusing selected option only if it exists
- ref.select.scrollToFocusedOptionOnUpdate = true;
- ref.select.inputIsHiddenAfterUpdate = false;
- ref.select.setState({
- focusedValue: null,
- focusedOption: projectChoices[selectedIndex],
- });
- }
- }
- });
- };
- //TODO(TS): Fix typings
- customOptionProject = ({label, ...props}: any) => {
- const project = this.props.projects.find(({slug}) => props.value === slug);
- if (!project) {
- return null;
- }
- return (
- <components.Option label={label} {...props}>
- <IdBadge
- project={project}
- avatarSize={20}
- displayName={label}
- avatarProps={{consistentWidth: true}}
- />
- </components.Option>
- );
- };
- get headerText() {
- const {needOrg, needProject} = this.props;
- if (needOrg && needProject) {
- return t('Select an organization and a project to continue');
- }
- if (needOrg) {
- return t('Select an organization to continue');
- }
- if (needProject) {
- return t('Select a project to continue');
- }
- //if neither project nor org needs to be selected, nothing will render anyways
- return '';
- }
- renderProjectSelectOrMessage() {
- const {organization, projects} = this.props;
- const [memberProjects, nonMemberProjects] = this.getMemberProjects();
- const {isSuperuser} = ConfigStore.get('user') || {};
- const projectOptions = [
- {
- label: t('Projects I belong to'),
- options: memberProjects.map(p => ({
- value: p.slug,
- label: t(`${p.slug}`),
- isDisabled: false,
- })),
- },
- {
- label: t("Projects I don't belong to"),
- options: nonMemberProjects.map(p => ({
- value: p.slug,
- label: t(`${p.slug}`),
- isDisabled: isSuperuser ? false : true,
- })),
- },
- ];
- if (!projects.length) {
- return (
- <div>
- {tct('You have no projects. Click [link] to make one.', {
- link: (
- <Link to={`/organizations/${organization}/projects/new/`}>{t('here')}</Link>
- ),
- })}
- </div>
- );
- }
- return (
- <StyledSelectControl
- ref={(ref: any) => {
- this.projectSelect = ref;
- this.focusProjectSelector();
- }}
- placeholder={t('Select a Project to continue')}
- name="project"
- options={projectOptions}
- onChange={this.handleSelectProject}
- onMenuOpen={this.onProjectMenuOpen}
- components={{Option: this.customOptionProject, DropdownIndicator: null}}
- styles={selectStyles}
- menuIsOpen
- />
- );
- }
- render() {
- const {
- needOrg,
- needProject,
- organization,
- organizations,
- loading,
- Header,
- Body,
- } = this.props;
- const shouldShowPicker = needOrg || needProject;
- if (!shouldShowPicker) {
- return null;
- }
- const shouldShowProjectSelector = organization && needProject && !loading;
- const orgChoices = organizations
- .filter(({status}) => status.id !== 'pending_deletion')
- .map(({slug}) => ({label: slug, value: slug}));
- return (
- <React.Fragment>
- <Header closeButton>{this.headerText}</Header>
- <Body>
- {loading && <StyledLoadingIndicator overlay />}
- {needOrg && (
- <StyledSelectControl
- ref={(ref: any) => {
- this.orgSelect = ref;
- if (shouldShowProjectSelector) {
- return;
- }
- this.focusOrganizationSelector();
- }}
- placeholder={t('Select an Organization')}
- name="organization"
- options={orgChoices}
- value={organization}
- onChange={this.handleSelectOrganization}
- components={{DropdownIndicator: null}}
- styles={selectStyles}
- menuIsOpen
- />
- )}
- {shouldShowProjectSelector && this.renderProjectSelectOrMessage()}
- </Body>
- </React.Fragment>
- );
- }
- }
- type ContainerProps = Omit<
- Props,
- 'projects' | 'loading' | 'organizations' | 'organization' | 'onSelectOrganization'
- > & {
- /**
- * List of slugs we want to be able to choose from
- */
- projectSlugs?: string[];
- };
- type ContainerState = {
- selectedOrganization?: string;
- organizations: Organization[];
- };
- class ContextPickerModalContainer extends React.Component<
- ContainerProps,
- ContainerState
- > {
- state = this.getInitialState();
- getInitialState(): ContainerState {
- const storeState = OrganizationStore.get();
- return {
- organizations: OrganizationsStore.getAll(),
- selectedOrganization: storeState.organization?.slug,
- };
- }
- componentWillUnmount() {
- this.unlistener?.();
- }
- unlistener = OrganizationsStore.listen(
- (organizations: Organization[]) => this.setState({organizations}),
- undefined
- );
- handleSelectOrganization = (organizationSlug: string) => {
- this.setState({selectedOrganization: organizationSlug});
- };
- renderModal({
- projects,
- initiallyLoaded,
- }: {
- projects?: Project[];
- initiallyLoaded?: boolean;
- }) {
- return (
- <ContextPickerModal
- {...this.props}
- projects={projects || []}
- loading={!initiallyLoaded}
- organizations={this.state.organizations}
- organization={this.state.selectedOrganization!}
- onSelectOrganization={this.handleSelectOrganization}
- />
- );
- }
- render() {
- const {projectSlugs} = this.props;
- if (this.state.selectedOrganization) {
- return (
- <Projects
- orgId={this.state.selectedOrganization}
- allProjects={!projectSlugs?.length}
- slugs={projectSlugs}
- >
- {({projects, initiallyLoaded}) =>
- this.renderModal({projects: projects as Project[], initiallyLoaded})
- }
- </Projects>
- );
- }
- return this.renderModal({});
- }
- }
- export default ContextPickerModalContainer;
- const StyledSelectControl = styled(SelectControl)`
- margin-top: ${space(1)};
- `;
- const StyledLoadingIndicator = styled(LoadingIndicator)`
- z-index: 1;
- `;
|