editAccessSelector.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. import {useEffect, useState} from 'react';
  2. import styled from '@emotion/styled';
  3. import debounce from 'lodash/debounce';
  4. import isEqual from 'lodash/isEqual';
  5. import {hasEveryAccess} from 'sentry/components/acl/access';
  6. import AvatarList from 'sentry/components/avatar/avatarList';
  7. import TeamAvatar from 'sentry/components/avatar/teamAvatar';
  8. import Badge from 'sentry/components/badge/badge';
  9. import FeatureBadge from 'sentry/components/badge/featureBadge';
  10. import {Button} from 'sentry/components/button';
  11. import ButtonBar from 'sentry/components/buttonBar';
  12. import {CompactSelect} from 'sentry/components/compactSelect';
  13. import {CheckWrap} from 'sentry/components/compactSelect/styles';
  14. import UserBadge from 'sentry/components/idBadge/userBadge';
  15. import {InnerWrap, LeadingItems} from 'sentry/components/menuListItem';
  16. import {Tooltip} from 'sentry/components/tooltip';
  17. import {DEFAULT_DEBOUNCE_DURATION} from 'sentry/constants';
  18. import {t, tct} from 'sentry/locale';
  19. import {space} from 'sentry/styles/space';
  20. import type {Team} from 'sentry/types/organization';
  21. import type {User} from 'sentry/types/user';
  22. import {defined} from 'sentry/utils';
  23. import useOrganization from 'sentry/utils/useOrganization';
  24. import {useTeams} from 'sentry/utils/useTeams';
  25. import {useTeamsById} from 'sentry/utils/useTeamsById';
  26. import {useUser} from 'sentry/utils/useUser';
  27. import type {
  28. DashboardDetails,
  29. DashboardListItem,
  30. DashboardPermissions,
  31. } from 'sentry/views/dashboards/types';
  32. interface EditAccessSelectorProps {
  33. dashboard: DashboardDetails | DashboardListItem;
  34. listOnly?: boolean;
  35. onChangeEditAccess?: (newDashboardPermissions: DashboardPermissions) => void;
  36. }
  37. /**
  38. * Dropdown multiselect button to enable selective Dashboard editing access to
  39. * specific users and teams
  40. */
  41. function EditAccessSelector({
  42. dashboard,
  43. onChangeEditAccess,
  44. listOnly = false,
  45. }: EditAccessSelectorProps) {
  46. const currentUser: User = useUser();
  47. const dashboardCreator: User | undefined = dashboard.createdBy;
  48. const organization = useOrganization();
  49. const userCanEditDashboardPermissions =
  50. dashboardCreator?.id === currentUser.id ||
  51. hasEveryAccess(['org:write'], {organization});
  52. // Retrieves teams from the team store, which may contain only a subset of all teams
  53. const {teams: teamsToRender} = useTeamsById();
  54. const {onSearch} = useTeams();
  55. const teamIds: string[] = Object.values(teamsToRender).map(team => team.id);
  56. const [selectedOptions, setSelectedOptions] = useState<string[]>(getSelectedOptions());
  57. const [isMenuOpen, setMenuOpen] = useState<boolean>(false);
  58. const {teams: selectedTeam} = useTeamsById({ids: [selectedOptions[1]]});
  59. // Effect to update selectedOptions whenever the dashboard changes
  60. useEffect(() => {
  61. const teamIdsList: string[] = Object.values(teamsToRender).map(team => team.id);
  62. if (!defined(dashboard.permissions) || dashboard.permissions.isEditableByEveryone) {
  63. setSelectedOptions(['_creator', '_allUsers', ...teamIdsList]);
  64. } else {
  65. const permittedTeamIds =
  66. dashboard.permissions.teamsWithEditAccess?.map(teamId => String(teamId)) ?? [];
  67. setSelectedOptions(['_creator', ...permittedTeamIds]);
  68. }
  69. }, [dashboard, teamsToRender]);
  70. // Handles state change when dropdown options are selected
  71. const onSelectOptions = newSelectedOptions => {
  72. let newSelectedValues = newSelectedOptions.map(
  73. (option: {value: string}) => option.value
  74. );
  75. const areAllTeamsSelected = teamIds.every(teamId =>
  76. newSelectedValues.includes(teamId)
  77. );
  78. if (
  79. !selectedOptions.includes('_allUsers') &&
  80. newSelectedValues.includes('_allUsers')
  81. ) {
  82. newSelectedValues = ['_creator', '_allUsers', ...teamIds];
  83. } else if (
  84. selectedOptions.includes('_allUsers') &&
  85. !newSelectedValues.includes('_allUsers')
  86. ) {
  87. newSelectedValues = ['_creator'];
  88. } else {
  89. areAllTeamsSelected
  90. ? // selecting all teams deselects 'all users'
  91. (newSelectedValues = ['_creator', '_allUsers', ...teamIds])
  92. : // deselecting any team deselects 'all users'
  93. (newSelectedValues = newSelectedValues.filter(value => value !== '_allUsers'));
  94. }
  95. setSelectedOptions(newSelectedValues);
  96. };
  97. // Creates a permissions object based on the options selected
  98. function getDashboardPermissions() {
  99. return {
  100. isEditableByEveryone: selectedOptions.includes('_allUsers'),
  101. teamsWithEditAccess: selectedOptions.includes('_allUsers')
  102. ? []
  103. : selectedOptions
  104. .filter(option => option !== '_creator')
  105. .map(teamId => parseInt(teamId, 10)),
  106. };
  107. }
  108. // Gets selected options for the dropdown from dashboard object
  109. function getSelectedOptions(): string[] {
  110. if (!defined(dashboard.permissions) || dashboard.permissions.isEditableByEveryone) {
  111. return ['_creator', '_allUsers', ...teamIds];
  112. }
  113. const permittedTeamIds =
  114. dashboard.permissions.teamsWithEditAccess?.map(teamId => String(teamId)) ?? [];
  115. return ['_creator', ...permittedTeamIds];
  116. }
  117. // Dashboard creator option in the dropdown
  118. const makeCreatorOption = () => ({
  119. value: '_creator',
  120. label: (
  121. <UserBadge
  122. avatarSize={18}
  123. user={dashboardCreator}
  124. displayName={
  125. <StyledDisplayName>
  126. {dashboardCreator?.id === currentUser.id
  127. ? tct('You ([email])', {email: currentUser.email})
  128. : dashboardCreator?.email ||
  129. tct('You ([email])', {email: currentUser.email})}
  130. </StyledDisplayName>
  131. }
  132. displayEmail={t('Creator')}
  133. />
  134. ),
  135. textValue: `creator_${currentUser.email}`,
  136. disabled: true,
  137. });
  138. // Single team option in the dropdown
  139. const makeTeamOption = (team: Team) => ({
  140. value: team.id,
  141. label: `#${team.slug}`,
  142. leadingItems: <TeamAvatar team={team} size={18} />,
  143. });
  144. // Avatars/Badges in the Edit Access Selector Button
  145. const triggerAvatars =
  146. selectedOptions.includes('_allUsers') || !dashboardCreator ? (
  147. <StyledBadge key="_all" text={'All'} size={listOnly ? 26 : 20} />
  148. ) : selectedOptions.length === 2 ? (
  149. // Case where we display 1 Creator Avatar + 1 Team Avatar
  150. <StyledAvatarList
  151. key="avatar-list-2-badges"
  152. typeAvatars="users"
  153. users={[dashboardCreator]}
  154. teams={selectedTeam ? selectedTeam : []}
  155. maxVisibleAvatars={1}
  156. avatarSize={listOnly ? 30 : 25}
  157. renderUsersFirst
  158. tooltipOptions={{disabled: !userCanEditDashboardPermissions}}
  159. />
  160. ) : (
  161. // Case where we display 1 Creator Avatar + a Badge with no. of teams selected
  162. <StyledAvatarList
  163. key="avatar-list-many-teams"
  164. typeAvatars="users"
  165. users={Array(selectedOptions.length).fill(dashboardCreator)}
  166. maxVisibleAvatars={1}
  167. avatarSize={listOnly ? 30 : 25}
  168. tooltipOptions={{disabled: !userCanEditDashboardPermissions}}
  169. />
  170. );
  171. const allDropdownOptions = [
  172. makeCreatorOption(),
  173. {
  174. value: '_all_users_section',
  175. options: [
  176. {
  177. value: '_allUsers',
  178. label: t('All users'),
  179. disabled: !userCanEditDashboardPermissions,
  180. },
  181. ],
  182. },
  183. {
  184. value: '_teams',
  185. label: t('Teams'),
  186. options: teamsToRender.map(makeTeamOption),
  187. showToggleAllButton: userCanEditDashboardPermissions,
  188. disabled: !userCanEditDashboardPermissions,
  189. },
  190. ];
  191. // Save and Cancel Buttons
  192. const dropdownFooterButtons = (
  193. <FilterButtons>
  194. <Button
  195. size="sm"
  196. onClick={() => {
  197. setMenuOpen(false);
  198. if (isMenuOpen) {
  199. setSelectedOptions(getSelectedOptions());
  200. }
  201. }}
  202. disabled={!userCanEditDashboardPermissions}
  203. >
  204. {t('Cancel')}
  205. </Button>
  206. <Button
  207. size="sm"
  208. onClick={() => {
  209. const isDefaultState =
  210. !defined(dashboard.permissions) && selectedOptions.includes('_allUsers');
  211. const newDashboardPermissions = getDashboardPermissions();
  212. if (
  213. !isDefaultState &&
  214. !isEqual(newDashboardPermissions, dashboard.permissions)
  215. ) {
  216. onChangeEditAccess?.(newDashboardPermissions);
  217. }
  218. setMenuOpen(!isMenuOpen);
  219. }}
  220. priority="primary"
  221. disabled={
  222. !userCanEditDashboardPermissions ||
  223. isEqual(getDashboardPermissions(), dashboard.permissions)
  224. }
  225. >
  226. {t('Save Changes')}
  227. </Button>
  228. </FilterButtons>
  229. );
  230. const dropdownMenu = (
  231. <StyledCompactSelect
  232. data-test-id={'edit-access-dropdown'}
  233. size="sm"
  234. onChange={newSelectedOptions => {
  235. onSelectOptions(newSelectedOptions);
  236. }}
  237. multiple
  238. searchable
  239. options={allDropdownOptions}
  240. value={selectedOptions}
  241. triggerLabel={
  242. listOnly
  243. ? [triggerAvatars]
  244. : [
  245. <StyledFeatureBadge
  246. key="beta-badge"
  247. type="beta"
  248. title={t('This feature is available for early adopters and may change')}
  249. tooltipProps={{position: 'left', delay: 1000, isHoverable: true}}
  250. />,
  251. t('Edit Access:'),
  252. triggerAvatars,
  253. ]
  254. }
  255. triggerProps={{borderless: listOnly}}
  256. searchPlaceholder={t('Search Teams')}
  257. isOpen={isMenuOpen}
  258. onOpenChange={() => {
  259. setMenuOpen(!isMenuOpen);
  260. if (isMenuOpen) {
  261. setSelectedOptions(getSelectedOptions());
  262. }
  263. }}
  264. menuFooter={dropdownFooterButtons}
  265. onSearch={debounce(val => void onSearch(val), DEFAULT_DEBOUNCE_DURATION)}
  266. />
  267. );
  268. return (
  269. <Tooltip
  270. title={t('Only the creator of the dashboard can edit permissions')}
  271. disabled={userCanEditDashboardPermissions || isMenuOpen}
  272. >
  273. {dropdownMenu}
  274. </Tooltip>
  275. );
  276. }
  277. export default EditAccessSelector;
  278. const StyledCompactSelect = styled(CompactSelect)`
  279. ${InnerWrap} {
  280. align-items: center;
  281. }
  282. ${LeadingItems} {
  283. margin-top: 0;
  284. }
  285. ${CheckWrap} {
  286. padding-bottom: 0;
  287. }
  288. `;
  289. const StyledDisplayName = styled('div')`
  290. font-weight: normal;
  291. `;
  292. const StyledAvatarList = styled(AvatarList)`
  293. margin-left: 10px;
  294. margin-right: -3px;
  295. `;
  296. const StyledFeatureBadge = styled(FeatureBadge)`
  297. margin-left: 0px;
  298. margin-right: 6px;
  299. `;
  300. const StyledBadge = styled(Badge)<{size: number}>`
  301. color: ${p => p.theme.white};
  302. background: ${p => p.theme.purple300};
  303. padding: 0;
  304. height: ${p => p.size}px;
  305. width: ${p => p.size}px;
  306. display: flex;
  307. justify-content: center;
  308. align-items: center;
  309. `;
  310. const FilterButtons = styled(ButtonBar)`
  311. display: grid;
  312. gap: ${space(1.5)};
  313. margin-top: ${space(0.5)};
  314. margin-bottom: ${space(0.5)};
  315. justify-content: flex-end;
  316. `;