editAccessSelector.tsx 9.4 KB

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