environmentSelector.tsx 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. import {Fragment, useEffect, useRef, useState} from 'react';
  2. // eslint-disable-next-line no-restricted-imports
  3. import {withRouter, WithRouterProps} from 'react-router';
  4. import {ClassNames} from '@emotion/react';
  5. import styled from '@emotion/styled';
  6. import isEqual from 'lodash/isEqual';
  7. import sortBy from 'lodash/sortBy';
  8. import DropdownAutoComplete from 'sentry/components/dropdownAutoComplete';
  9. import {MenuFooterChildProps} from 'sentry/components/dropdownAutoComplete/menu';
  10. import {Item} from 'sentry/components/dropdownAutoComplete/types';
  11. import {MenuActions} from 'sentry/components/dropdownMenu';
  12. import Highlight from 'sentry/components/highlight';
  13. import HeaderItem from 'sentry/components/organizations/headerItem';
  14. import MultipleSelectorSubmitRow from 'sentry/components/organizations/multipleSelectorSubmitRow';
  15. import PageFilterRow from 'sentry/components/organizations/pageFilterRow';
  16. import PageFilterPinButton from 'sentry/components/organizations/pageFilters/pageFilterPinButton';
  17. import {ALL_ACCESS_PROJECTS} from 'sentry/constants/pageFilters';
  18. import {IconWindow} from 'sentry/icons';
  19. import {t} from 'sentry/locale';
  20. import ConfigStore from 'sentry/stores/configStore';
  21. import space from 'sentry/styles/space';
  22. import {Organization, Project} from 'sentry/types';
  23. import {analytics} from 'sentry/utils/analytics';
  24. import getRouteStringFromRoutes from 'sentry/utils/getRouteStringFromRoutes';
  25. import theme from 'sentry/utils/theme';
  26. type Props = WithRouterProps & {
  27. loadingProjects: boolean;
  28. /**
  29. * When menu is closed
  30. */
  31. onUpdate: (environments: string[]) => void;
  32. organization: Organization;
  33. projects: Project[];
  34. selectedProjects: number[];
  35. /**
  36. * This component must be controlled using a value array
  37. */
  38. value: string[];
  39. /**
  40. * Aligns dropdown menu to left or right of button
  41. */
  42. alignDropdown?: 'left' | 'right';
  43. customDropdownButton?: (config: {
  44. actions: MenuActions;
  45. isOpen: boolean;
  46. value: string[];
  47. }) => React.ReactElement;
  48. customLoadingIndicator?: React.ReactNode;
  49. detached?: boolean;
  50. disabled?: boolean;
  51. forceEnvironment?: string;
  52. /**
  53. * Show the pin button in the dropdown's header actions
  54. */
  55. showPin?: boolean;
  56. };
  57. /**
  58. * Environment Selector
  59. *
  60. * Note we only fetch environments when this component is mounted
  61. */
  62. function EnvironmentSelector({
  63. loadingProjects,
  64. onUpdate,
  65. organization,
  66. projects,
  67. selectedProjects,
  68. value,
  69. alignDropdown,
  70. customDropdownButton,
  71. customLoadingIndicator,
  72. detached,
  73. disabled,
  74. forceEnvironment,
  75. router,
  76. showPin,
  77. }: Props) {
  78. const [selectedEnvs, setSelectedEnvs] = useState(value);
  79. const hasChanges = !isEqual(selectedEnvs, value);
  80. // Update selected envs value on change
  81. useEffect(() => {
  82. setSelectedEnvs(previousSelectedEnvs => {
  83. lastSelectedEnvs.current = previousSelectedEnvs;
  84. return value;
  85. });
  86. }, [value]);
  87. // We keep a separate list of selected environments to use for sorting. This
  88. // allows us to only update it after the list is closed, to avoid the list
  89. // jumping around while selecting projects.
  90. const lastSelectedEnvs = useRef(value);
  91. // Ref to help avoid updating stale selected values
  92. const didQuickSelect = useRef(false);
  93. /**
  94. * Toggle selected state of an environment
  95. */
  96. const toggleCheckbox = (environment: string) => {
  97. const willRemove = selectedEnvs.includes(environment);
  98. const updatedSelectedEnvs = willRemove
  99. ? selectedEnvs.filter(env => env !== environment)
  100. : [...selectedEnvs, environment];
  101. analytics('environmentselector.toggle', {
  102. action: willRemove ? 'removed' : 'added',
  103. path: getRouteStringFromRoutes(router.routes),
  104. org_id: parseInt(organization.id, 10),
  105. });
  106. setSelectedEnvs(updatedSelectedEnvs);
  107. };
  108. const handleSave = (actions: MenuFooterChildProps['actions']) => {
  109. actions.close();
  110. onUpdate(selectedEnvs);
  111. };
  112. const handleMenuClose = () => {
  113. // Only update if there are changes
  114. if (!hasChanges || didQuickSelect.current) {
  115. didQuickSelect.current = false;
  116. return;
  117. }
  118. analytics('environmentselector.update', {
  119. count: selectedEnvs.length,
  120. path: getRouteStringFromRoutes(router.routes),
  121. org_id: parseInt(organization.id, 10),
  122. });
  123. onUpdate(selectedEnvs);
  124. };
  125. /**
  126. * Clears all selected environments and updates
  127. */
  128. const handleClear = () => {
  129. analytics('environmentselector.clear', {
  130. path: getRouteStringFromRoutes(router.routes),
  131. org_id: parseInt(organization.id, 10),
  132. });
  133. setSelectedEnvs([]);
  134. onUpdate([]);
  135. };
  136. const handleQuickSelect = (item: Item) => {
  137. analytics('environmentselector.direct_selection', {
  138. path: getRouteStringFromRoutes(router.routes),
  139. org_id: parseInt(organization.id, 10),
  140. });
  141. const selectedEnvironments = [item.value];
  142. setSelectedEnvs(selectedEnvironments);
  143. onUpdate(selectedEnvironments);
  144. // Track that we just did a click select so we don't trigger an update in
  145. // the close handler.
  146. didQuickSelect.current = true;
  147. };
  148. const config = ConfigStore.getConfig();
  149. const unsortedEnvironments = projects.flatMap(project => {
  150. const projectId = parseInt(project.id, 10);
  151. // Include environments from:
  152. // - all projects if the user is a superuser
  153. // - the requested projects
  154. // - all member projects if 'my projects' (empty list) is selected.
  155. // - all projects if -1 is the only selected project.
  156. if (
  157. (selectedProjects.length === 1 &&
  158. selectedProjects[0] === ALL_ACCESS_PROJECTS &&
  159. project.hasAccess) ||
  160. (selectedProjects.length === 0 && (project.isMember || config.user.isSuperuser)) ||
  161. selectedProjects.includes(projectId)
  162. ) {
  163. return project.environments;
  164. }
  165. return [];
  166. });
  167. const uniqueEnvironments = Array.from(new Set(unsortedEnvironments));
  168. // Sort with the last selected environments at the top
  169. const environments = sortBy(uniqueEnvironments, env => [
  170. !lastSelectedEnvs.current.find(e => e === env),
  171. env,
  172. ]);
  173. const validatedValue = value.filter(env => environments.includes(env));
  174. const summary = validatedValue.length
  175. ? `${validatedValue.join(', ')}`
  176. : t('All Environments');
  177. if (forceEnvironment !== undefined) {
  178. return (
  179. <StyledHeaderItem
  180. data-test-id="page-filter-environment-selector"
  181. icon={<IconWindow />}
  182. isOpen={false}
  183. locked
  184. >
  185. {forceEnvironment ? forceEnvironment : t('All Environments')}
  186. </StyledHeaderItem>
  187. );
  188. }
  189. if (loadingProjects && customLoadingIndicator) {
  190. return <Fragment>{customLoadingIndicator}</Fragment>;
  191. }
  192. if (loadingProjects) {
  193. return (
  194. <StyledHeaderItem
  195. data-test-id="page-filter-environment-selector"
  196. icon={<IconWindow />}
  197. loading={loadingProjects}
  198. hasChanges={false}
  199. hasSelected={false}
  200. isOpen={false}
  201. locked={false}
  202. >
  203. {t('Loading\u2026')}
  204. </StyledHeaderItem>
  205. );
  206. }
  207. return (
  208. <ClassNames>
  209. {({css}) => (
  210. <StyledDropdownAutoComplete
  211. alignMenu={alignDropdown}
  212. allowActorToggle
  213. closeOnSelect
  214. blendCorner={false}
  215. detached={detached}
  216. disabled={disabled}
  217. searchPlaceholder={t('Filter environments')}
  218. onSelect={handleQuickSelect}
  219. onClose={handleMenuClose}
  220. maxHeight={500}
  221. rootClassName={css`
  222. position: relative;
  223. display: flex;
  224. `}
  225. inputProps={{style: {padding: 8, paddingLeft: 14}}}
  226. emptyMessage={t('You have no environments')}
  227. noResultsMessage={t('No environments found')}
  228. virtualizedHeight={theme.headerSelectorRowHeight}
  229. emptyHidesInput
  230. inputActions={
  231. showPin ? <StyledPinButton size="xs" filter="environments" /> : undefined
  232. }
  233. menuFooter={({actions}) =>
  234. hasChanges ? (
  235. <MultipleSelectorSubmitRow onSubmit={() => handleSave(actions)} />
  236. ) : null
  237. }
  238. items={environments.map(env => ({
  239. value: env,
  240. searchKey: env,
  241. label: ({inputValue}) => (
  242. <PageFilterRow
  243. data-test-id={`environment-${env}`}
  244. checked={selectedEnvs.includes(env)}
  245. onCheckClick={e => {
  246. e.stopPropagation();
  247. toggleCheckbox(env);
  248. }}
  249. >
  250. <Highlight text={inputValue}>{env}</Highlight>
  251. </PageFilterRow>
  252. ),
  253. }))}
  254. >
  255. {({isOpen, actions}) =>
  256. customDropdownButton ? (
  257. customDropdownButton({isOpen, actions, value: validatedValue})
  258. ) : (
  259. <StyledHeaderItem
  260. data-test-id="page-filter-environment-selector"
  261. icon={<IconWindow />}
  262. isOpen={isOpen}
  263. hasSelected={value && !!value.length}
  264. onClear={handleClear}
  265. hasChanges={false}
  266. locked={false}
  267. loading={false}
  268. >
  269. {summary}
  270. </StyledHeaderItem>
  271. )
  272. }
  273. </StyledDropdownAutoComplete>
  274. )}
  275. </ClassNames>
  276. );
  277. }
  278. export default withRouter(EnvironmentSelector);
  279. const StyledHeaderItem = styled(HeaderItem)`
  280. height: 100%;
  281. width: 100%;
  282. `;
  283. const StyledDropdownAutoComplete = styled(DropdownAutoComplete)`
  284. background: ${p => p.theme.background};
  285. border: 1px solid ${p => p.theme.border};
  286. position: absolute;
  287. top: 100%;
  288. ${p =>
  289. !p.detached &&
  290. `
  291. margin-top: 0;
  292. border-radius: ${p.theme.borderRadiusBottom};
  293. `};
  294. `;
  295. const StyledPinButton = styled(PageFilterPinButton)`
  296. margin: 0 ${space(1)};
  297. `;