index.tsx 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  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. disabled={displayReprocessingActions}
  105. />
  106. </ActionsCheckbox>
  107. )}
  108. {!displayReprocessingActions && (
  109. <AnimatePresence initial={false} mode="wait">
  110. {shouldDisplayActions && (
  111. <HeaderButtonsWrapper key="actions" {...animationProps}>
  112. <ActionSet
  113. queryCount={queryCount}
  114. query={query}
  115. issues={selectedIdsSet}
  116. allInQuerySelected={allInQuerySelected}
  117. anySelected={anySelected}
  118. multiSelected={multiSelected}
  119. selectedProjectSlug={selectedProjectSlug}
  120. onShouldConfirm={action =>
  121. shouldConfirm(action, {pageSelected, selectedIdsSet})
  122. }
  123. onDelete={handleDelete}
  124. onMerge={handleMerge}
  125. onUpdate={handleUpdate}
  126. />
  127. </HeaderButtonsWrapper>
  128. )}
  129. {!anySelected && (
  130. <HeaderButtonsWrapper key="sort" {...animationProps}>
  131. <IssueListSortOptions sort={sort} query={query} onSelect={onSortChange} />
  132. </HeaderButtonsWrapper>
  133. )}
  134. </AnimatePresence>
  135. )}
  136. <AnimatePresence initial={false} mode="wait">
  137. {!anySelected ? (
  138. <AnimatedHeaderItemsContainer key="headers" {...animationProps}>
  139. <Headers
  140. onSelectStatsPeriod={onSelectStatsPeriod}
  141. selection={selection}
  142. statsPeriod={statsPeriod}
  143. isReprocessingQuery={displayReprocessingActions}
  144. isSavedSearchesOpen={isSavedSearchesOpen}
  145. />
  146. </AnimatedHeaderItemsContainer>
  147. ) : (
  148. <motion.div key="sort" {...animationProps}>
  149. <SortDropdownMargin>
  150. <IssueListSortOptions sort={sort} query={query} onSelect={onSortChange} />
  151. </SortDropdownMargin>
  152. </motion.div>
  153. )}
  154. </AnimatePresence>
  155. </ActionsBarContainer>
  156. );
  157. }
  158. function IssueListActions({
  159. allResultsVisible,
  160. displayReprocessingActions,
  161. groupIds,
  162. onActionTaken,
  163. onDelete,
  164. onSelectStatsPeriod,
  165. onSortChange,
  166. queryCount,
  167. query,
  168. selection,
  169. sort,
  170. statsPeriod,
  171. }: IssueListActionsProps) {
  172. const api = useApi();
  173. const queryClient = useQueryClient();
  174. const organization = useOrganization();
  175. const {
  176. pageSelected,
  177. multiSelected,
  178. anySelected,
  179. allInQuerySelected,
  180. selectedIdsSet,
  181. selectedProjectSlug,
  182. setAllInQuerySelected,
  183. } = useSelectedGroupsState();
  184. const [isSavedSearchesOpen] = useSyncedLocalStorageState(
  185. SAVED_SEARCHES_SIDEBAR_OPEN_LOCALSTORAGE_KEY,
  186. false
  187. );
  188. const hasIssuePriority = organization.features.includes('issue-priority-ui');
  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. {hasIssuePriority ? (
  329. <ActionsBarPriority
  330. query={query}
  331. queryCount={queryCount}
  332. selection={selection}
  333. statsPeriod={statsPeriod}
  334. onSortChange={onSortChange}
  335. allInQuerySelected={allInQuerySelected}
  336. pageSelected={pageSelected}
  337. selectedIdsSet={selectedIdsSet}
  338. displayReprocessingActions={displayReprocessingActions}
  339. handleDelete={handleDelete}
  340. handleMerge={handleMerge}
  341. handleUpdate={handleUpdate}
  342. multiSelected={multiSelected}
  343. narrowViewport={disableActions}
  344. selectedProjectSlug={selectedProjectSlug}
  345. isSavedSearchesOpen={isSavedSearchesOpen}
  346. sort={sort}
  347. anySelected={anySelected}
  348. onSelectStatsPeriod={onSelectStatsPeriod}
  349. />
  350. ) : (
  351. <ActionsBarContainer>
  352. {!disableActions && (
  353. <ActionsCheckbox isReprocessingQuery={displayReprocessingActions}>
  354. <Checkbox
  355. onChange={() => SelectedGroupStore.toggleSelectAll()}
  356. checked={pageSelected || (anySelected ? 'indeterminate' : false)}
  357. disabled={displayReprocessingActions}
  358. />
  359. </ActionsCheckbox>
  360. )}
  361. {!displayReprocessingActions && (
  362. <HeaderButtonsWrapper>
  363. {!disableActions && (
  364. <ActionSet
  365. queryCount={queryCount}
  366. query={query}
  367. issues={selectedIdsSet}
  368. allInQuerySelected={allInQuerySelected}
  369. anySelected={anySelected}
  370. multiSelected={multiSelected}
  371. selectedProjectSlug={selectedProjectSlug}
  372. onShouldConfirm={action =>
  373. shouldConfirm(action, {pageSelected, selectedIdsSet})
  374. }
  375. onDelete={handleDelete}
  376. onMerge={handleMerge}
  377. onUpdate={handleUpdate}
  378. />
  379. )}
  380. <IssueListSortOptions sort={sort} query={query} onSelect={onSortChange} />
  381. </HeaderButtonsWrapper>
  382. )}
  383. <Headers
  384. onSelectStatsPeriod={onSelectStatsPeriod}
  385. selection={selection}
  386. statsPeriod={statsPeriod}
  387. isReprocessingQuery={displayReprocessingActions}
  388. isSavedSearchesOpen={isSavedSearchesOpen}
  389. />
  390. </ActionsBarContainer>
  391. )}
  392. {!allResultsVisible && pageSelected && (
  393. <Alert type="warning" system>
  394. <SelectAllNotice data-test-id="issue-list-select-all-notice">
  395. {allInQuerySelected ? (
  396. queryCount >= BULK_LIMIT ? (
  397. tct(
  398. 'Selected up to the first [count] issues that match this search query.',
  399. {
  400. count: BULK_LIMIT_STR,
  401. }
  402. )
  403. ) : (
  404. tct('Selected all [count] issues that match this search query.', {
  405. count: queryCount,
  406. })
  407. )
  408. ) : (
  409. <Fragment>
  410. {tn(
  411. '%s issue on this page selected.',
  412. '%s issues on this page selected.',
  413. numIssues
  414. )}
  415. <SelectAllLink
  416. onClick={() => setAllInQuerySelected(true)}
  417. data-test-id="issue-list-select-all-notice-link"
  418. >
  419. {queryCount >= BULK_LIMIT
  420. ? tct(
  421. 'Select the first [count] issues that match this search query.',
  422. {
  423. count: BULK_LIMIT_STR,
  424. }
  425. )
  426. : tct('Select all [count] issues that match this search query.', {
  427. count: queryCount,
  428. })}
  429. </SelectAllLink>
  430. </Fragment>
  431. )}
  432. </SelectAllNotice>
  433. </Alert>
  434. )}
  435. </StickyActions>
  436. );
  437. }
  438. function useSelectedGroupsState() {
  439. const [allInQuerySelected, setAllInQuerySelected] = useState(false);
  440. const selectedIds = useLegacyStore(SelectedGroupStore);
  441. const selected = SelectedGroupStore.getSelectedIds();
  442. const projects = [...selected]
  443. .map(id => GroupStore.get(id))
  444. .filter((group): group is Group => !!group?.project)
  445. .map(group => group.project.slug);
  446. const uniqProjects = uniq(projects);
  447. // we only want selectedProjectSlug set if there is 1 project
  448. // more or fewer should result in a null so that the action toolbar
  449. // can behave correctly.
  450. const selectedProjectSlug = uniqProjects.length === 1 ? uniqProjects[0] : undefined;
  451. const pageSelected = SelectedGroupStore.allSelected();
  452. const multiSelected = SelectedGroupStore.multiSelected();
  453. const anySelected = SelectedGroupStore.anySelected();
  454. const selectedIdsSet = SelectedGroupStore.getSelectedIds();
  455. useEffect(() => {
  456. setAllInQuerySelected(false);
  457. }, [selectedIds]);
  458. return {
  459. pageSelected,
  460. multiSelected,
  461. anySelected,
  462. allInQuerySelected,
  463. selectedIdsSet,
  464. selectedProjectSlug,
  465. setAllInQuerySelected,
  466. };
  467. }
  468. function shouldConfirm(
  469. action: ConfirmAction,
  470. {pageSelected, selectedIdsSet}: {pageSelected: boolean; selectedIdsSet: Set<string>}
  471. ) {
  472. switch (action) {
  473. case ConfirmAction.RESOLVE:
  474. case ConfirmAction.UNRESOLVE:
  475. case ConfirmAction.ARCHIVE:
  476. case ConfirmAction.SET_PRIORITY:
  477. case ConfirmAction.UNBOOKMARK: {
  478. return pageSelected && selectedIdsSet.size > 1;
  479. }
  480. case ConfirmAction.BOOKMARK:
  481. return selectedIdsSet.size > 1;
  482. case ConfirmAction.MERGE:
  483. case ConfirmAction.DELETE:
  484. default:
  485. return true; // By default, should confirm ...
  486. }
  487. }
  488. const StickyActions = styled(Sticky)`
  489. z-index: ${p => p.theme.zIndex.issuesList.stickyHeader};
  490. /* Remove border radius from the action bar when stuck. Without this there is
  491. * a small gap where color can peek through. */
  492. &[data-stuck] > div {
  493. border-radius: 0;
  494. }
  495. `;
  496. const ActionsBarContainer = styled('div')`
  497. display: flex;
  498. min-height: 45px;
  499. padding-top: ${space(1)};
  500. padding-bottom: ${space(1)};
  501. align-items: center;
  502. background: ${p => p.theme.backgroundSecondary};
  503. border: 1px solid ${p => p.theme.border};
  504. border-top: none;
  505. border-radius: ${p => p.theme.panelBorderRadius} ${p => p.theme.panelBorderRadius} 0 0;
  506. margin: 0 -1px -1px;
  507. `;
  508. const ActionsCheckbox = styled('div')<{isReprocessingQuery: boolean}>`
  509. display: flex;
  510. align-items: center;
  511. padding-left: ${space(2)};
  512. margin-bottom: 1px;
  513. ${p => p.isReprocessingQuery && 'flex: 1'};
  514. `;
  515. const HeaderButtonsWrapper = styled(motion.div)`
  516. @media (min-width: ${p => p.theme.breakpoints.large}) {
  517. width: 50%;
  518. }
  519. flex: 1;
  520. margin: 0 ${space(1)};
  521. display: grid;
  522. gap: ${space(0.5)};
  523. grid-auto-flow: column;
  524. justify-content: flex-start;
  525. white-space: nowrap;
  526. `;
  527. const SelectAllNotice = styled('div')`
  528. display: flex;
  529. flex-wrap: wrap;
  530. justify-content: center;
  531. a:not([role='button']) {
  532. color: ${p => p.theme.linkColor};
  533. border-bottom: none;
  534. }
  535. `;
  536. const SelectAllLink = styled('a')`
  537. margin-left: ${space(1)};
  538. `;
  539. const SortDropdownMargin = styled('div')`
  540. margin-right: ${space(1)};
  541. `;
  542. const AnimatedHeaderItemsContainer = styled(motion.div)`
  543. display: flex;
  544. align-items: center;
  545. `;
  546. export {IssueListActions};
  547. export default IssueListActions;