index.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. import {Fragment, useEffect, useState} from 'react';
  2. import styled from '@emotion/styled';
  3. import {AnimatePresence, type AnimationProps, motion} from 'framer-motion';
  4. import {bulkDelete, bulkUpdate, mergeGroups} from 'sentry/actionCreators/group';
  5. import {
  6. addErrorMessage,
  7. addLoadingMessage,
  8. clearIndicators,
  9. } from 'sentry/actionCreators/indicator';
  10. import {Alert} from 'sentry/components/alert';
  11. import Checkbox from 'sentry/components/checkbox';
  12. import {Sticky} from 'sentry/components/sticky';
  13. import {t, tct, tn} from 'sentry/locale';
  14. import GroupStore from 'sentry/stores/groupStore';
  15. import ProjectsStore from 'sentry/stores/projectsStore';
  16. import SelectedGroupStore from 'sentry/stores/selectedGroupStore';
  17. import {useLegacyStore} from 'sentry/stores/useLegacyStore';
  18. import {space} from 'sentry/styles/space';
  19. import type {PageFilters} from 'sentry/types/core';
  20. import type {Group} from 'sentry/types/group';
  21. import {trackAnalytics} from 'sentry/utils/analytics';
  22. import {uniq} from 'sentry/utils/array/uniq';
  23. import {useQueryClient} from 'sentry/utils/queryClient';
  24. import theme from 'sentry/utils/theme';
  25. import useApi from 'sentry/utils/useApi';
  26. import useMedia from 'sentry/utils/useMedia';
  27. import useOrganization from 'sentry/utils/useOrganization';
  28. import {useSyncedLocalStorageState} from 'sentry/utils/useSyncedLocalStorageState';
  29. import type {IssueUpdateData} from 'sentry/views/issueList/types';
  30. import {SAVED_SEARCHES_SIDEBAR_OPEN_LOCALSTORAGE_KEY} from 'sentry/views/issueList/utils';
  31. import ActionSet from './actionSet';
  32. import Headers from './headers';
  33. import IssueListSortOptions from './sortOptions';
  34. import {BULK_LIMIT, BULK_LIMIT_STR, ConfirmAction} from './utils';
  35. type IssueListActionsProps = {
  36. allResultsVisible: boolean;
  37. displayReprocessingActions: boolean;
  38. groupIds: string[];
  39. onDelete: () => void;
  40. onSelectStatsPeriod: (period: string) => void;
  41. onSortChange: (sort: string) => void;
  42. query: string;
  43. queryCount: number;
  44. selection: PageFilters;
  45. sort: string;
  46. statsPeriod: string;
  47. onActionTaken?: (itemIds: string[], data: IssueUpdateData) => void;
  48. };
  49. const animationProps: AnimationProps = {
  50. initial: {translateY: 8, opacity: 0},
  51. animate: {translateY: 0, opacity: 1},
  52. exit: {translateY: -8, opacity: 0},
  53. transition: {duration: 0.1},
  54. };
  55. function ActionsBarPriority({
  56. anySelected,
  57. narrowViewport,
  58. displayReprocessingActions,
  59. pageSelected,
  60. queryCount,
  61. selectedIdsSet,
  62. multiSelected,
  63. allInQuerySelected,
  64. query,
  65. handleDelete,
  66. handleMerge,
  67. handleUpdate,
  68. sort,
  69. selectedProjectSlug,
  70. onSortChange,
  71. onSelectStatsPeriod,
  72. isSavedSearchesOpen,
  73. statsPeriod,
  74. selection,
  75. }: {
  76. allInQuerySelected: boolean;
  77. anySelected: boolean;
  78. displayReprocessingActions: boolean;
  79. handleDelete: () => void;
  80. handleMerge: () => void;
  81. handleUpdate: (data: IssueUpdateData) => void;
  82. isSavedSearchesOpen: boolean;
  83. multiSelected: boolean;
  84. narrowViewport: boolean;
  85. onSelectStatsPeriod: (period: string) => void;
  86. onSortChange: (sort: string) => void;
  87. pageSelected: boolean;
  88. query: string;
  89. queryCount: number;
  90. selectedIdsSet: Set<string>;
  91. selectedProjectSlug: string | undefined;
  92. selection: PageFilters;
  93. sort: string;
  94. statsPeriod: string;
  95. }) {
  96. const shouldDisplayActions = anySelected && !narrowViewport;
  97. return (
  98. <ActionsBarContainer>
  99. {!narrowViewport && (
  100. <ActionsCheckbox isReprocessingQuery={displayReprocessingActions}>
  101. <Checkbox
  102. onChange={() => SelectedGroupStore.toggleSelectAll()}
  103. checked={pageSelected || (anySelected ? 'indeterminate' : false)}
  104. aria-label={pageSelected ? t('Deselect all') : t('Select all')}
  105. disabled={displayReprocessingActions}
  106. />
  107. </ActionsCheckbox>
  108. )}
  109. {!displayReprocessingActions && (
  110. <AnimatePresence initial={false} mode="wait">
  111. {shouldDisplayActions && (
  112. <HeaderButtonsWrapper key="actions" {...animationProps}>
  113. <ActionSet
  114. queryCount={queryCount}
  115. query={query}
  116. issues={selectedIdsSet}
  117. allInQuerySelected={allInQuerySelected}
  118. anySelected={anySelected}
  119. multiSelected={multiSelected}
  120. selectedProjectSlug={selectedProjectSlug}
  121. onShouldConfirm={action =>
  122. shouldConfirm(action, {pageSelected, selectedIdsSet})
  123. }
  124. onDelete={handleDelete}
  125. onMerge={handleMerge}
  126. onUpdate={handleUpdate}
  127. />
  128. </HeaderButtonsWrapper>
  129. )}
  130. {!anySelected && (
  131. <HeaderButtonsWrapper key="sort" {...animationProps}>
  132. <IssueListSortOptions sort={sort} query={query} onSelect={onSortChange} />
  133. </HeaderButtonsWrapper>
  134. )}
  135. </AnimatePresence>
  136. )}
  137. <AnimatePresence initial={false} mode="wait">
  138. {!anySelected ? (
  139. <AnimatedHeaderItemsContainer key="headers" {...animationProps}>
  140. <Headers
  141. onSelectStatsPeriod={onSelectStatsPeriod}
  142. selection={selection}
  143. statsPeriod={statsPeriod}
  144. isReprocessingQuery={displayReprocessingActions}
  145. isSavedSearchesOpen={isSavedSearchesOpen}
  146. />
  147. </AnimatedHeaderItemsContainer>
  148. ) : (
  149. <motion.div key="sort" {...animationProps}>
  150. <SortDropdownMargin>
  151. <IssueListSortOptions sort={sort} query={query} onSelect={onSortChange} />
  152. </SortDropdownMargin>
  153. </motion.div>
  154. )}
  155. </AnimatePresence>
  156. </ActionsBarContainer>
  157. );
  158. }
  159. function IssueListActions({
  160. allResultsVisible,
  161. displayReprocessingActions,
  162. groupIds,
  163. onActionTaken,
  164. onDelete,
  165. onSelectStatsPeriod,
  166. onSortChange,
  167. queryCount,
  168. query,
  169. selection,
  170. sort,
  171. statsPeriod,
  172. }: IssueListActionsProps) {
  173. const api = useApi();
  174. const queryClient = useQueryClient();
  175. const organization = useOrganization();
  176. const {
  177. pageSelected,
  178. multiSelected,
  179. anySelected,
  180. allInQuerySelected,
  181. selectedIdsSet,
  182. selectedProjectSlug,
  183. setAllInQuerySelected,
  184. } = useSelectedGroupsState();
  185. const [isSavedSearchesOpen] = useSyncedLocalStorageState(
  186. SAVED_SEARCHES_SIDEBAR_OPEN_LOCALSTORAGE_KEY,
  187. false
  188. );
  189. const disableActions = useMedia(
  190. `(max-width: ${
  191. isSavedSearchesOpen ? theme.breakpoints.xlarge : theme.breakpoints.medium
  192. })`
  193. );
  194. const numIssues = selectedIdsSet.size;
  195. function actionSelectedGroups(callback: (itemIds: string[] | undefined) => void) {
  196. const selectedIds = allInQuerySelected
  197. ? undefined // undefined means "all"
  198. : groupIds.filter(itemId => selectedIdsSet.has(itemId));
  199. callback(selectedIds);
  200. SelectedGroupStore.deselectAll();
  201. }
  202. // TODO: Remove issue.category:error filter when merging/deleting performance issues is supported
  203. // This silently avoids performance issues for bulk actions
  204. const queryExcludingPerformanceIssues = `${query ?? ''} issue.category:error`;
  205. function handleDelete() {
  206. actionSelectedGroups(itemIds => {
  207. bulkDelete(
  208. api,
  209. {
  210. orgId: organization.slug,
  211. itemIds,
  212. query: queryExcludingPerformanceIssues,
  213. project: selection.projects,
  214. environment: selection.environments,
  215. ...selection.datetime,
  216. },
  217. {
  218. complete: () => {
  219. onDelete();
  220. },
  221. }
  222. );
  223. });
  224. }
  225. function handleMerge() {
  226. actionSelectedGroups(itemIds => {
  227. mergeGroups(
  228. api,
  229. {
  230. orgId: organization.slug,
  231. itemIds,
  232. query: queryExcludingPerformanceIssues,
  233. project: selection.projects,
  234. environment: selection.environments,
  235. ...selection.datetime,
  236. },
  237. {}
  238. );
  239. if (selection.projects[0]) {
  240. const trackProject = ProjectsStore.getById(`${selection.projects[0]}`);
  241. trackAnalytics('issues_stream.merged', {
  242. organization,
  243. project_id: trackProject?.id,
  244. platform: trackProject?.platform,
  245. items_merged: allInQuerySelected ? 'all_in_query' : itemIds?.length,
  246. });
  247. }
  248. });
  249. }
  250. function handleUpdate(data: IssueUpdateData) {
  251. if ('status' in data && data.status === 'ignored') {
  252. const statusDetails =
  253. 'ignoreCount' in data.statusDetails
  254. ? 'ignoreCount'
  255. : 'ignoreDuration' in data.statusDetails
  256. ? 'ignoreDuration'
  257. : 'ignoreUserCount' in data.statusDetails
  258. ? 'ignoreUserCount'
  259. : undefined;
  260. trackAnalytics('issues_stream.archived', {
  261. action_status_details: statusDetails,
  262. action_substatus: data.substatus,
  263. organization,
  264. });
  265. }
  266. if ('priority' in data) {
  267. trackAnalytics('issues_stream.updated_priority', {
  268. organization,
  269. priority: data.priority,
  270. });
  271. }
  272. actionSelectedGroups(itemIds => {
  273. // If `itemIds` is undefined then it means we expect to bulk update all items
  274. // that match the query.
  275. //
  276. // We need to always respect the projects selected in the global selection header:
  277. // * users with no global views requires a project to be specified
  278. // * users with global views need to be explicit about what projects the query will run against
  279. const projectConstraints = {project: selection.projects};
  280. if (itemIds?.length) {
  281. addLoadingMessage(t('Saving changes\u2026'));
  282. }
  283. bulkUpdate(
  284. api,
  285. {
  286. orgId: organization.slug,
  287. itemIds,
  288. data,
  289. query,
  290. environment: selection.environments,
  291. failSilently: true,
  292. ...projectConstraints,
  293. ...selection.datetime,
  294. },
  295. {
  296. success: () => {
  297. clearIndicators();
  298. onActionTaken?.(itemIds ?? [], data);
  299. // Prevents stale data on issue details
  300. if (itemIds?.length) {
  301. for (const itemId of itemIds) {
  302. queryClient.invalidateQueries({
  303. queryKey: [`/organizations/${organization.slug}/issues/${itemId}/`],
  304. exact: false,
  305. });
  306. }
  307. } else {
  308. // If we're doing a full query update we invalidate all issue queries to be safe
  309. queryClient.invalidateQueries({
  310. predicate: apiQuery =>
  311. typeof apiQuery.queryKey[0] === 'string' &&
  312. apiQuery.queryKey[0].startsWith(
  313. `/organizations/${organization.slug}/issues/`
  314. ),
  315. });
  316. }
  317. },
  318. error: () => {
  319. clearIndicators();
  320. addErrorMessage(t('Unable to update issues'));
  321. },
  322. }
  323. );
  324. });
  325. }
  326. return (
  327. <StickyActions>
  328. <ActionsBarPriority
  329. query={query}
  330. queryCount={queryCount}
  331. selection={selection}
  332. statsPeriod={statsPeriod}
  333. onSortChange={onSortChange}
  334. allInQuerySelected={allInQuerySelected}
  335. pageSelected={pageSelected}
  336. selectedIdsSet={selectedIdsSet}
  337. displayReprocessingActions={displayReprocessingActions}
  338. handleDelete={handleDelete}
  339. handleMerge={handleMerge}
  340. handleUpdate={handleUpdate}
  341. multiSelected={multiSelected}
  342. narrowViewport={disableActions}
  343. selectedProjectSlug={selectedProjectSlug}
  344. isSavedSearchesOpen={isSavedSearchesOpen}
  345. sort={sort}
  346. anySelected={anySelected}
  347. onSelectStatsPeriod={onSelectStatsPeriod}
  348. />
  349. {!allResultsVisible && pageSelected && (
  350. <Alert type="warning" system>
  351. <SelectAllNotice data-test-id="issue-list-select-all-notice">
  352. {allInQuerySelected ? (
  353. queryCount >= BULK_LIMIT ? (
  354. tct(
  355. 'Selected up to the first [count] issues that match this search query.',
  356. {
  357. count: BULK_LIMIT_STR,
  358. }
  359. )
  360. ) : (
  361. tct('Selected all [count] issues that match this search query.', {
  362. count: queryCount,
  363. })
  364. )
  365. ) : (
  366. <Fragment>
  367. {tn(
  368. '%s issue on this page selected.',
  369. '%s issues on this page selected.',
  370. numIssues
  371. )}
  372. <SelectAllLink
  373. onClick={() => setAllInQuerySelected(true)}
  374. data-test-id="issue-list-select-all-notice-link"
  375. >
  376. {queryCount >= BULK_LIMIT
  377. ? tct(
  378. 'Select the first [count] issues that match this search query.',
  379. {
  380. count: BULK_LIMIT_STR,
  381. }
  382. )
  383. : tct('Select all [count] issues that match this search query.', {
  384. count: queryCount,
  385. })}
  386. </SelectAllLink>
  387. </Fragment>
  388. )}
  389. </SelectAllNotice>
  390. </Alert>
  391. )}
  392. </StickyActions>
  393. );
  394. }
  395. function useSelectedGroupsState() {
  396. const [allInQuerySelected, setAllInQuerySelected] = useState(false);
  397. const selectedGroupState = useLegacyStore(SelectedGroupStore);
  398. const selectedIds = SelectedGroupStore.getSelectedIds();
  399. const projects = [...selectedIds]
  400. .map(id => GroupStore.get(id))
  401. .filter((group): group is Group => !!group?.project)
  402. .map(group => group.project.slug);
  403. const uniqProjects = uniq(projects);
  404. // we only want selectedProjectSlug set if there is 1 project
  405. // more or fewer should result in a null so that the action toolbar
  406. // can behave correctly.
  407. const selectedProjectSlug = uniqProjects.length === 1 ? uniqProjects[0] : undefined;
  408. const pageSelected = SelectedGroupStore.allSelected();
  409. const multiSelected = SelectedGroupStore.multiSelected();
  410. const anySelected = SelectedGroupStore.anySelected();
  411. const selectedIdsSet = SelectedGroupStore.getSelectedIds();
  412. useEffect(() => {
  413. setAllInQuerySelected(false);
  414. }, [selectedGroupState]);
  415. return {
  416. pageSelected,
  417. multiSelected,
  418. anySelected,
  419. allInQuerySelected,
  420. selectedIdsSet,
  421. selectedProjectSlug,
  422. setAllInQuerySelected,
  423. };
  424. }
  425. function shouldConfirm(
  426. action: ConfirmAction,
  427. {pageSelected, selectedIdsSet}: {pageSelected: boolean; selectedIdsSet: Set<string>}
  428. ) {
  429. switch (action) {
  430. case ConfirmAction.RESOLVE:
  431. case ConfirmAction.UNRESOLVE:
  432. case ConfirmAction.ARCHIVE:
  433. case ConfirmAction.SET_PRIORITY:
  434. case ConfirmAction.UNBOOKMARK: {
  435. return pageSelected && selectedIdsSet.size > 1;
  436. }
  437. case ConfirmAction.BOOKMARK:
  438. return selectedIdsSet.size > 1;
  439. case ConfirmAction.MERGE:
  440. case ConfirmAction.DELETE:
  441. default:
  442. return true; // By default, should confirm ...
  443. }
  444. }
  445. const StickyActions = styled(Sticky)`
  446. z-index: ${p => p.theme.zIndex.issuesList.stickyHeader};
  447. /* Remove border radius from the action bar when stuck. Without this there is
  448. * a small gap where color can peek through. */
  449. &[data-stuck] > div {
  450. border-radius: 0;
  451. }
  452. `;
  453. const ActionsBarContainer = styled('div')`
  454. display: flex;
  455. min-height: 45px;
  456. padding-top: ${space(1)};
  457. padding-bottom: ${space(1)};
  458. align-items: center;
  459. background: ${p => p.theme.backgroundSecondary};
  460. border: 1px solid ${p => p.theme.border};
  461. border-top: none;
  462. border-radius: ${p => p.theme.panelBorderRadius} ${p => p.theme.panelBorderRadius} 0 0;
  463. margin: 0 -1px -1px;
  464. `;
  465. const ActionsCheckbox = styled('div')<{isReprocessingQuery: boolean}>`
  466. display: flex;
  467. align-items: center;
  468. padding-left: ${space(2)};
  469. margin-bottom: 1px;
  470. ${p => p.isReprocessingQuery && 'flex: 1'};
  471. `;
  472. const HeaderButtonsWrapper = styled(motion.div)`
  473. @media (min-width: ${p => p.theme.breakpoints.large}) {
  474. width: 50%;
  475. }
  476. flex: 1;
  477. margin: 0 ${space(1)};
  478. display: grid;
  479. gap: ${space(0.5)};
  480. grid-auto-flow: column;
  481. justify-content: flex-start;
  482. white-space: nowrap;
  483. `;
  484. const SelectAllNotice = styled('div')`
  485. display: flex;
  486. flex-wrap: wrap;
  487. justify-content: center;
  488. a:not([role='button']) {
  489. color: ${p => p.theme.linkColor};
  490. border-bottom: none;
  491. }
  492. `;
  493. const SelectAllLink = styled('a')`
  494. margin-left: ${space(1)};
  495. `;
  496. const SortDropdownMargin = styled('div')`
  497. margin-right: ${space(1)};
  498. `;
  499. const AnimatedHeaderItemsContainer = styled(motion.div)`
  500. display: flex;
  501. align-items: center;
  502. `;
  503. export {IssueListActions};
  504. export default IssueListActions;