environmentSelector.tsx 7.6 KB

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