projectPageFilter.tsx 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. import {useEffect, useState} from 'react';
  2. // eslint-disable-next-line no-restricted-imports
  3. import {withRouter, WithRouterProps} from 'react-router';
  4. import styled from '@emotion/styled';
  5. import isEqual from 'lodash/isEqual';
  6. import partition from 'lodash/partition';
  7. import {updateProjects} from 'sentry/actionCreators/pageFilters';
  8. import GuideAnchor from 'sentry/components/assistant/guideAnchor';
  9. import Badge from 'sentry/components/badge';
  10. import PageFilterDropdownButton from 'sentry/components/organizations/pageFilters/pageFilterDropdownButton';
  11. import PageFilterPinIndicator from 'sentry/components/organizations/pageFilters/pageFilterPinIndicator';
  12. import ProjectSelector from 'sentry/components/organizations/projectSelector';
  13. import PlatformList from 'sentry/components/platformList';
  14. import {ALL_ACCESS_PROJECTS} from 'sentry/constants/pageFilters';
  15. import {IconProject} from 'sentry/icons';
  16. import {t} from 'sentry/locale';
  17. import ConfigStore from 'sentry/stores/configStore';
  18. import space from 'sentry/styles/space';
  19. import {MinimalProject} from 'sentry/types';
  20. import {trimSlug} from 'sentry/utils/trimSlug';
  21. import useOrganization from 'sentry/utils/useOrganization';
  22. import usePageFilters from 'sentry/utils/usePageFilters';
  23. import useProjects from 'sentry/utils/useProjects';
  24. type ProjectSelectorProps = React.ComponentProps<typeof ProjectSelector>;
  25. type Props = WithRouterProps & {
  26. disabled?: ProjectSelectorProps['disabled'];
  27. /**
  28. * Message to display at the bottom of project list
  29. */
  30. footerMessage?: React.ReactNode;
  31. /**
  32. * If a forced project is passed, selection is disabled
  33. */
  34. forceProject?: MinimalProject | null;
  35. /**
  36. * Subject that will be used in a tooltip that is shown on a lock icon hover
  37. * E.g. This 'issue' is unique to a project
  38. */
  39. lockedMessageSubject?: string;
  40. /**
  41. * Max character length for the dropdown title. Default is 20. This number
  42. * is used to determine how many projects to show, and how much to truncate.
  43. */
  44. maxTitleLength?: number;
  45. /**
  46. * Reset these URL params when we fire actions (custom routing only)
  47. */
  48. resetParamsOnChange?: string[];
  49. /**
  50. * A project will be forced from parent component (selection is disabled, and if user
  51. * does not have multi-project support enabled, it will not try to auto select a project).
  52. *
  53. * Project will be specified in the prop `forceProject` (since its data is async)
  54. */
  55. shouldForceProject?: boolean;
  56. /**
  57. * If true, there will be a back to issues stream icon link
  58. */
  59. showIssueStreamLink?: boolean;
  60. /**
  61. * If true, there will be a project settings icon link
  62. * (forceProject prop needs to be present to know the right project slug)
  63. */
  64. showProjectSettingsLink?: boolean;
  65. /**
  66. * Slugs of projects to restrict the project selector to
  67. */
  68. specificProjectSlugs?: string[];
  69. };
  70. function ProjectPageFilter({
  71. router,
  72. specificProjectSlugs,
  73. maxTitleLength = 30,
  74. resetParamsOnChange = [],
  75. disabled,
  76. ...otherProps
  77. }: Props) {
  78. const [currentSelectedProjects, setCurrentSelectedProjects] = useState<number[] | null>(
  79. null
  80. );
  81. const {projects, initiallyLoaded: projectsLoaded} = useProjects();
  82. const organization = useOrganization();
  83. const {selection, isReady, desyncedFilters} = usePageFilters();
  84. useEffect(
  85. () => {
  86. if (!isEqual(selection.projects, currentSelectedProjects)) {
  87. setCurrentSelectedProjects(selection.projects);
  88. }
  89. },
  90. // We only care to update the currentSelectedProjects when the project
  91. // selection has changed
  92. // eslint-disable-next-line react-hooks/exhaustive-deps
  93. [selection.projects]
  94. );
  95. const handleChangeProjects = (newProjects: number[]) => {
  96. setCurrentSelectedProjects(newProjects);
  97. };
  98. const handleApplyChange = (newProjects: number[]) => {
  99. updateProjects(newProjects, router, {
  100. save: true,
  101. resetParams: resetParamsOnChange,
  102. environments: [], // Clear environments when switching projects
  103. });
  104. };
  105. const specifiedProjects = specificProjectSlugs
  106. ? projects.filter(project => specificProjectSlugs.includes(project.slug))
  107. : projects;
  108. const [memberProjects, otherProjects] = partition(
  109. specifiedProjects,
  110. project => project.isMember
  111. );
  112. const {isSuperuser} = ConfigStore.get('user');
  113. const isOrgAdmin = organization.access.includes('org:admin');
  114. const nonMemberProjects = isSuperuser || isOrgAdmin ? otherProjects : [];
  115. const customProjectDropdown: ProjectSelectorProps['customDropdownButton'] = ({
  116. actions,
  117. selectedProjects,
  118. isOpen,
  119. }) => {
  120. const selectedProjectIds = new Set(selection.projects);
  121. const hasSelected = !!selectedProjects.length;
  122. // Show 2 projects only if the combined string does not exceed maxTitleLength.
  123. // Otherwise show only 1 project.
  124. const projectsToShow =
  125. selectedProjects[0]?.slug?.length + selectedProjects[1]?.slug?.length <=
  126. maxTitleLength - 2
  127. ? selectedProjects.slice(0, 2)
  128. : selectedProjects.slice(0, 1);
  129. const title = hasSelected
  130. ? projectsToShow.map(proj => trimSlug(proj.slug, maxTitleLength)).join(', ')
  131. : selectedProjectIds.has(ALL_ACCESS_PROJECTS)
  132. ? t('All Projects')
  133. : t('My Projects');
  134. const icon = hasSelected ? (
  135. <PlatformList
  136. platforms={projectsToShow.map(p => p.platform ?? 'other').reverse()}
  137. />
  138. ) : (
  139. <IconProject />
  140. );
  141. return (
  142. <GuideAnchor
  143. target="new_page_filter_button"
  144. position="bottom"
  145. onStepComplete={actions.open}
  146. >
  147. <PageFilterDropdownButton
  148. isOpen={isOpen}
  149. highlighted={desyncedFilters.has('projects')}
  150. data-test-id="page-filter-project-selector"
  151. disabled={disabled}
  152. >
  153. <DropdownTitle>
  154. <PageFilterPinIndicator filter="projects">{icon}</PageFilterPinIndicator>
  155. <TitleContainer>{title}</TitleContainer>
  156. {selectedProjects.length > projectsToShow.length && (
  157. <StyledBadge text={`+${selectedProjects.length - projectsToShow.length}`} />
  158. )}
  159. </DropdownTitle>
  160. </PageFilterDropdownButton>
  161. </GuideAnchor>
  162. );
  163. };
  164. const customLoadingIndicator = (
  165. <PageFilterDropdownButton
  166. showChevron={false}
  167. disabled
  168. data-test-id="page-filter-project-selector-loading"
  169. >
  170. <DropdownTitle>
  171. <IconProject />
  172. <TitleContainer>{t('Loading\u2026')}</TitleContainer>
  173. </DropdownTitle>
  174. </PageFilterDropdownButton>
  175. );
  176. return (
  177. <ProjectSelector
  178. organization={organization}
  179. memberProjects={memberProjects}
  180. isGlobalSelectionReady={projectsLoaded && isReady}
  181. nonMemberProjects={nonMemberProjects}
  182. value={currentSelectedProjects || selection.projects}
  183. onChange={handleChangeProjects}
  184. onApplyChange={handleApplyChange}
  185. customDropdownButton={customProjectDropdown}
  186. customLoadingIndicator={customLoadingIndicator}
  187. disabled={disabled}
  188. {...otherProps}
  189. />
  190. );
  191. }
  192. const TitleContainer = styled('div')`
  193. overflow: hidden;
  194. white-space: nowrap;
  195. text-overflow: ellipsis;
  196. flex: 1 1 0%;
  197. margin-left: ${space(1)};
  198. text-align: left;
  199. `;
  200. const DropdownTitle = styled('div')`
  201. width: max-content;
  202. display: flex;
  203. align-items: center;
  204. flex: 1;
  205. `;
  206. const StyledBadge = styled(Badge)`
  207. flex-shrink: 0;
  208. `;
  209. export default withRouter(ProjectPageFilter);