editAccessSelector.tsx 10 KB

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