group.tsx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654
  1. import {Fragment, useCallback, useMemo, useRef} from 'react';
  2. import {css, Theme} from '@emotion/react';
  3. import styled from '@emotion/styled';
  4. import type {LocationDescriptor} from 'history';
  5. import AssigneeSelector from 'sentry/components/assigneeSelector';
  6. import GuideAnchor from 'sentry/components/assistant/guideAnchor';
  7. import Checkbox from 'sentry/components/checkbox';
  8. import Count from 'sentry/components/count';
  9. import EventOrGroupExtraDetails from 'sentry/components/eventOrGroupExtraDetails';
  10. import EventOrGroupHeader from 'sentry/components/eventOrGroupHeader';
  11. import {GroupListColumn} from 'sentry/components/issues/groupList';
  12. import Link from 'sentry/components/links/link';
  13. import {getRelativeSummary} from 'sentry/components/organizations/timeRangeSelector/utils';
  14. import {PanelItem} from 'sentry/components/panels';
  15. import Placeholder from 'sentry/components/placeholder';
  16. import ProgressBar from 'sentry/components/progressBar';
  17. import {joinQuery, parseSearch, Token} from 'sentry/components/searchSyntax/parser';
  18. import GroupChart from 'sentry/components/stream/groupChart';
  19. import TimeSince from 'sentry/components/timeSince';
  20. import {Tooltip} from 'sentry/components/tooltip';
  21. import {DEFAULT_STATS_PERIOD} from 'sentry/constants';
  22. import {t} from 'sentry/locale';
  23. import DemoWalkthroughStore from 'sentry/stores/demoWalkthroughStore';
  24. import GroupStore from 'sentry/stores/groupStore';
  25. import SelectedGroupStore from 'sentry/stores/selectedGroupStore';
  26. import {useLegacyStore} from 'sentry/stores/useLegacyStore';
  27. import {space} from 'sentry/styles/space';
  28. import {
  29. Group,
  30. GroupReprocessing,
  31. InboxDetails,
  32. IssueCategory,
  33. NewQuery,
  34. Organization,
  35. User,
  36. } from 'sentry/types';
  37. import {defined, percent} from 'sentry/utils';
  38. import {trackAnalytics} from 'sentry/utils/analytics';
  39. import {isDemoWalkthrough} from 'sentry/utils/demoMode';
  40. import EventView from 'sentry/utils/discover/eventView';
  41. import usePageFilters from 'sentry/utils/usePageFilters';
  42. import withOrganization from 'sentry/utils/withOrganization';
  43. import {TimePeriodType} from 'sentry/views/alerts/rules/metric/details/constants';
  44. import {
  45. DISCOVER_EXCLUSION_FIELDS,
  46. getTabs,
  47. isForReviewQuery,
  48. } from 'sentry/views/issueList/utils';
  49. export const DEFAULT_STREAM_GROUP_STATS_PERIOD = '24h';
  50. type Props = {
  51. id: string;
  52. organization: Organization;
  53. canSelect?: boolean;
  54. customStatsPeriod?: TimePeriodType;
  55. displayReprocessingLayout?: boolean;
  56. hasGuideAnchor?: boolean;
  57. index?: number;
  58. memberList?: User[];
  59. narrowGroups?: boolean;
  60. query?: string;
  61. queryFilterDescription?: string;
  62. showInboxTime?: boolean;
  63. showLastTriggered?: boolean;
  64. source?: string;
  65. statsPeriod?: string;
  66. useFilteredStats?: boolean;
  67. useTintRow?: boolean;
  68. withChart?: boolean;
  69. withColumns?: GroupListColumn[];
  70. };
  71. function BaseGroupRow({
  72. id,
  73. organization,
  74. customStatsPeriod,
  75. displayReprocessingLayout,
  76. hasGuideAnchor,
  77. index,
  78. memberList,
  79. query,
  80. queryFilterDescription,
  81. showInboxTime,
  82. source,
  83. statsPeriod = DEFAULT_STREAM_GROUP_STATS_PERIOD,
  84. canSelect = true,
  85. withChart = true,
  86. withColumns = ['graph', 'event', 'users', 'assignee', 'lastTriggered'],
  87. useFilteredStats = false,
  88. useTintRow = true,
  89. narrowGroups = false,
  90. showLastTriggered = false,
  91. }: Props) {
  92. const groups = useLegacyStore(GroupStore);
  93. const group = groups.find(item => item.id === id) as Group;
  94. const selectedGroups = useLegacyStore(SelectedGroupStore);
  95. const isSelected = selectedGroups[id];
  96. const {selection} = usePageFilters();
  97. const originalInboxState = useRef(group.inbox as InboxDetails | null);
  98. const referrer = source ? `${source}-issue-stream` : 'issue-stream';
  99. const reviewed =
  100. // Original state had an inbox reason
  101. originalInboxState.current?.reason !== undefined &&
  102. // Updated state has been removed from inbox
  103. !group.inbox &&
  104. // Only apply reviewed on the "for review" tab
  105. isForReviewQuery(query);
  106. const {period, start, end} = selection.datetime || {};
  107. const summary =
  108. customStatsPeriod?.label.toLowerCase() ??
  109. (!!start && !!end
  110. ? 'time range'
  111. : getRelativeSummary(period || DEFAULT_STATS_PERIOD).toLowerCase());
  112. const sharedAnalytics = useMemo(() => {
  113. const tab = getTabs(organization).find(([tabQuery]) => tabQuery === query)?.[1];
  114. const owners = group.owners ?? [];
  115. return {
  116. organization,
  117. group_id: group.id,
  118. tab: tab?.analyticsName || 'other',
  119. was_shown_suggestion: owners.length > 0,
  120. };
  121. }, [organization, group.id, group.owners, query]);
  122. const trackAssign: React.ComponentProps<typeof AssigneeSelector>['onAssign'] =
  123. useCallback(
  124. (type, _assignee, suggestedAssignee) => {
  125. if (query !== undefined) {
  126. trackAnalytics('issues_stream.issue_assigned', {
  127. ...sharedAnalytics,
  128. did_assign_suggestion: !!suggestedAssignee,
  129. assigned_suggestion_reason: suggestedAssignee?.suggestedReason,
  130. assigned_type: type,
  131. });
  132. }
  133. },
  134. [query, sharedAnalytics]
  135. );
  136. const wrapperToggle = useCallback(
  137. (evt: React.MouseEvent<HTMLDivElement>) => {
  138. const targetElement = evt.target as Partial<HTMLElement>;
  139. // Ignore clicks on links
  140. if (targetElement?.tagName?.toLowerCase() === 'a') {
  141. return;
  142. }
  143. // Ignore clicks on the selection checkbox
  144. if (targetElement?.tagName?.toLowerCase() === 'input') {
  145. return;
  146. }
  147. let e = targetElement;
  148. while (e.parentElement) {
  149. if (e?.tagName?.toLowerCase() === 'a') {
  150. return;
  151. }
  152. e = e.parentElement!;
  153. }
  154. if (evt.shiftKey) {
  155. SelectedGroupStore.shiftToggleItems(group.id);
  156. window.getSelection()?.removeAllRanges();
  157. } else {
  158. SelectedGroupStore.toggleSelect(group.id);
  159. }
  160. },
  161. [group.id]
  162. );
  163. const checkboxToggle = useCallback(
  164. (evt: React.ChangeEvent<HTMLInputElement>) => {
  165. const mouseEvent = evt.nativeEvent as MouseEvent;
  166. if (mouseEvent.shiftKey) {
  167. SelectedGroupStore.shiftToggleItems(group.id);
  168. } else {
  169. SelectedGroupStore.toggleSelect(group.id);
  170. }
  171. },
  172. [group.id]
  173. );
  174. const getDiscoverUrl = (isFiltered?: boolean): LocationDescriptor => {
  175. // when there is no discover feature open events page
  176. const hasDiscoverQuery = organization.features.includes('discover-basic');
  177. const parsedResult = parseSearch(
  178. isFiltered && typeof query === 'string' ? query : ''
  179. );
  180. const filteredTerms = parsedResult?.filter(
  181. p => !(p.type === Token.FILTER && DISCOVER_EXCLUSION_FIELDS.includes(p.key.text))
  182. );
  183. const filteredQuery = joinQuery(filteredTerms, true);
  184. const commonQuery = {projects: [Number(group.project.id)]};
  185. if (hasDiscoverQuery) {
  186. const stats = customStatsPeriod ?? (selection.datetime || {});
  187. const discoverQuery: NewQuery = {
  188. ...commonQuery,
  189. id: undefined,
  190. name: group.title || group.type,
  191. fields: ['title', 'release', 'environment', 'user', 'timestamp'],
  192. orderby: '-timestamp',
  193. query: `issue:${group.shortId}${filteredQuery}`,
  194. version: 2,
  195. };
  196. if (!!stats.start && !!stats.end) {
  197. discoverQuery.start = new Date(stats.start).toISOString();
  198. discoverQuery.end = new Date(stats.end).toISOString();
  199. if (stats.utc) {
  200. discoverQuery.utc = true;
  201. }
  202. } else {
  203. discoverQuery.range = stats.period || DEFAULT_STATS_PERIOD;
  204. }
  205. const discoverView = EventView.fromSavedQuery(discoverQuery);
  206. return discoverView.getResultsViewUrlTarget(organization.slug);
  207. }
  208. return {
  209. pathname: `/organizations/${organization.slug}/issues/${group.id}/events/`,
  210. query: {
  211. referrer,
  212. stream_index: index,
  213. ...commonQuery,
  214. query: filteredQuery,
  215. },
  216. };
  217. };
  218. const renderReprocessingColumns = () => {
  219. const {statusDetails, count} = group as GroupReprocessing;
  220. const {info, pendingEvents} = statusDetails;
  221. if (!info) {
  222. return null;
  223. }
  224. const {totalEvents, dateCreated} = info;
  225. const remainingEventsToReprocess = totalEvents - pendingEvents;
  226. const remainingEventsToReprocessPercent = percent(
  227. remainingEventsToReprocess,
  228. totalEvents
  229. );
  230. return (
  231. <Fragment>
  232. <StartedColumn>
  233. <TimeSince date={dateCreated} />
  234. </StartedColumn>
  235. <EventsReprocessedColumn>
  236. {!defined(count) ? (
  237. <Placeholder height="17px" />
  238. ) : (
  239. <Fragment>
  240. <Count value={remainingEventsToReprocess} />
  241. {'/'}
  242. <Count value={totalEvents} />
  243. </Fragment>
  244. )}
  245. </EventsReprocessedColumn>
  246. <ProgressColumn>
  247. <ProgressBar value={remainingEventsToReprocessPercent} />
  248. </ProgressColumn>
  249. </Fragment>
  250. );
  251. };
  252. // Use data.filtered to decide on which value to use
  253. // In case of the query has filters but we avoid showing both sets of filtered/unfiltered stats
  254. // we use useFilteredStats param passed to Group for deciding
  255. const primaryCount = group.filtered ? group.filtered.count : group.count;
  256. const secondaryCount = group.filtered ? group.count : undefined;
  257. const primaryUserCount = group.filtered ? group.filtered.userCount : group.userCount;
  258. const secondaryUserCount = group.filtered ? group.userCount : undefined;
  259. // preview stats
  260. const lastTriggeredDate = group.lastTriggered;
  261. const showSecondaryPoints = Boolean(
  262. withChart && group && group.filtered && statsPeriod && useFilteredStats
  263. );
  264. const groupCategoryCountTitles: Record<IssueCategory, string> = {
  265. [IssueCategory.ERROR]: t('Error Events'),
  266. [IssueCategory.PERFORMANCE]: t('Transaction Events'),
  267. [IssueCategory.PROFILE]: t('Profile Events'),
  268. [IssueCategory.CRON]: t('Cron Events'),
  269. };
  270. const groupCount = !defined(primaryCount) ? (
  271. <Placeholder height="18px" />
  272. ) : (
  273. <GuideAnchor target="dynamic_counts" disabled={!hasGuideAnchor}>
  274. <Tooltip
  275. disabled={!useFilteredStats}
  276. isHoverable
  277. title={
  278. <CountTooltipContent>
  279. <h4>{groupCategoryCountTitles[group.issueCategory]}</h4>
  280. {group.filtered && (
  281. <Fragment>
  282. <div>{queryFilterDescription ?? t('Matching filters')}</div>
  283. <Link to={getDiscoverUrl(true)}>
  284. <Count value={group.filtered?.count} />
  285. </Link>
  286. </Fragment>
  287. )}
  288. <Fragment>
  289. <div>{t('Total in %s', summary)}</div>
  290. <Link to={getDiscoverUrl()}>
  291. <Count value={group.count} />
  292. </Link>
  293. </Fragment>
  294. {group.lifetime && (
  295. <Fragment>
  296. <div>{t('Since issue began')}</div>
  297. <Count value={group.lifetime.count} />
  298. </Fragment>
  299. )}
  300. </CountTooltipContent>
  301. }
  302. >
  303. <PrimaryCount value={primaryCount} />
  304. {secondaryCount !== undefined && useFilteredStats && (
  305. <SecondaryCount value={secondaryCount} />
  306. )}
  307. </Tooltip>
  308. </GuideAnchor>
  309. );
  310. const groupUsersCount = !defined(primaryUserCount) ? (
  311. <Placeholder height="18px" />
  312. ) : (
  313. <Tooltip
  314. isHoverable
  315. disabled={!usePageFilters}
  316. title={
  317. <CountTooltipContent>
  318. <h4>{t('Affected Users')}</h4>
  319. {group.filtered && (
  320. <Fragment>
  321. <div>{queryFilterDescription ?? t('Matching filters')}</div>
  322. <Link to={getDiscoverUrl(true)}>
  323. <Count value={group.filtered?.userCount} />
  324. </Link>
  325. </Fragment>
  326. )}
  327. <Fragment>
  328. <div>{t('Total in %s', summary)}</div>
  329. <Link to={getDiscoverUrl()}>
  330. <Count value={group.userCount} />
  331. </Link>
  332. </Fragment>
  333. {group.lifetime && (
  334. <Fragment>
  335. <div>{t('Since issue began')}</div>
  336. <Count value={group.lifetime.userCount} />
  337. </Fragment>
  338. )}
  339. </CountTooltipContent>
  340. }
  341. >
  342. <PrimaryCount value={primaryUserCount} />
  343. {secondaryUserCount !== undefined && useFilteredStats && (
  344. <SecondaryCount dark value={secondaryUserCount} />
  345. )}
  346. </Tooltip>
  347. );
  348. const lastTriggered = !defined(lastTriggeredDate) ? (
  349. <Placeholder height="18px" />
  350. ) : (
  351. <TimeSince
  352. tooltipPrefix={t('Last Triggered')}
  353. date={lastTriggeredDate}
  354. suffix={t('ago')}
  355. unitStyle="short"
  356. />
  357. );
  358. const issueStreamAnchor = isDemoWalkthrough() ? (
  359. <GuideAnchor target="issue_stream" disabled={!DemoWalkthroughStore.get('issue')} />
  360. ) : (
  361. <GuideAnchor target="issue_stream" />
  362. );
  363. return (
  364. <Wrapper
  365. data-test-id="group"
  366. data-test-reviewed={reviewed}
  367. onClick={displayReprocessingLayout || !canSelect ? undefined : wrapperToggle}
  368. reviewed={reviewed}
  369. useTintRow={useTintRow ?? true}
  370. >
  371. {canSelect && (
  372. <GroupCheckBoxWrapper>
  373. <Checkbox
  374. id={group.id}
  375. aria-label={t('Select Issue')}
  376. checked={isSelected}
  377. disabled={!!displayReprocessingLayout}
  378. onChange={checkboxToggle}
  379. />
  380. </GroupCheckBoxWrapper>
  381. )}
  382. <GroupSummary canSelect={canSelect}>
  383. <EventOrGroupHeader
  384. index={index}
  385. organization={organization}
  386. data={group}
  387. query={query}
  388. size="normal"
  389. source={referrer}
  390. />
  391. <EventOrGroupExtraDetails data={group} showInboxTime={showInboxTime} />
  392. </GroupSummary>
  393. {hasGuideAnchor && issueStreamAnchor}
  394. {withChart && !displayReprocessingLayout && (
  395. <ChartWrapper narrowGroups={narrowGroups}>
  396. {!group.filtered?.stats && !group.stats ? (
  397. <Placeholder height="24px" />
  398. ) : (
  399. <GroupChart
  400. statsPeriod={statsPeriod!}
  401. data={group}
  402. showSecondaryPoints={showSecondaryPoints}
  403. showMarkLine
  404. />
  405. )}
  406. </ChartWrapper>
  407. )}
  408. {displayReprocessingLayout ? (
  409. renderReprocessingColumns()
  410. ) : (
  411. <Fragment>
  412. {withColumns.includes('event') && (
  413. <EventCountsWrapper>{groupCount}</EventCountsWrapper>
  414. )}
  415. {withColumns.includes('users') && (
  416. <EventCountsWrapper>{groupUsersCount}</EventCountsWrapper>
  417. )}
  418. {withColumns.includes('assignee') && (
  419. <AssigneeWrapper narrowGroups={narrowGroups}>
  420. <AssigneeSelector
  421. id={group.id}
  422. memberList={memberList}
  423. onAssign={trackAssign}
  424. />
  425. </AssigneeWrapper>
  426. )}
  427. {showLastTriggered && <EventCountsWrapper>{lastTriggered}</EventCountsWrapper>}
  428. </Fragment>
  429. )}
  430. </Wrapper>
  431. );
  432. }
  433. const StreamGroup = withOrganization(BaseGroupRow);
  434. export default StreamGroup;
  435. // Position for wrapper is relative for overlay actions
  436. const Wrapper = styled(PanelItem)<{
  437. reviewed: boolean;
  438. useTintRow: boolean;
  439. }>`
  440. position: relative;
  441. padding: ${space(1.5)} 0;
  442. line-height: 1.1;
  443. ${p =>
  444. p.useTintRow &&
  445. p.reviewed &&
  446. css`
  447. animation: tintRow 0.2s linear forwards;
  448. position: relative;
  449. /*
  450. * A mask that fills the entire row and makes the text opaque. Doing this because
  451. * opacity adds a stacking context in CSS so we need to apply it to another element.
  452. */
  453. &:after {
  454. content: '';
  455. pointer-events: none;
  456. position: absolute;
  457. left: 0;
  458. right: 0;
  459. top: 0;
  460. bottom: 0;
  461. width: 100%;
  462. height: 100%;
  463. background-color: ${p.theme.bodyBackground};
  464. opacity: 0.4;
  465. }
  466. @keyframes tintRow {
  467. 0% {
  468. background-color: ${p.theme.bodyBackground};
  469. }
  470. 100% {
  471. background-color: ${p.theme.backgroundSecondary};
  472. }
  473. }
  474. `};
  475. `;
  476. const GroupSummary = styled('div')<{canSelect: boolean}>`
  477. overflow: hidden;
  478. margin-left: ${p => space(p.canSelect ? 1 : 2)};
  479. margin-right: ${space(1)};
  480. flex: 1;
  481. width: 66.66%;
  482. @media (min-width: ${p => p.theme.breakpoints.medium}) {
  483. width: 50%;
  484. }
  485. `;
  486. const GroupCheckBoxWrapper = styled('div')`
  487. margin-left: ${space(2)};
  488. align-self: flex-start;
  489. height: 15px;
  490. display: flex;
  491. align-items: center;
  492. `;
  493. const primaryStatStyle = (theme: Theme) => css`
  494. font-size: ${theme.fontSizeLarge};
  495. font-variant-numeric: tabular-nums;
  496. `;
  497. const PrimaryCount = styled(Count)`
  498. ${p => primaryStatStyle(p.theme)};
  499. `;
  500. const secondaryStatStyle = (theme: Theme) => css`
  501. font-size: ${theme.fontSizeLarge};
  502. font-variant-numeric: tabular-nums;
  503. :before {
  504. content: '/';
  505. padding-left: ${space(0.25)};
  506. padding-right: 2px;
  507. color: ${theme.gray300};
  508. }
  509. `;
  510. const SecondaryCount = styled(({value, ...p}) => <Count {...p} value={value} />)`
  511. ${p => secondaryStatStyle(p.theme)}
  512. `;
  513. const CountTooltipContent = styled('div')`
  514. display: grid;
  515. grid-template-columns: 1fr max-content;
  516. gap: ${space(1)} ${space(3)};
  517. text-align: left;
  518. font-size: ${p => p.theme.fontSizeMedium};
  519. align-items: center;
  520. h4 {
  521. color: ${p => p.theme.gray300};
  522. font-size: ${p => p.theme.fontSizeExtraSmall};
  523. text-transform: uppercase;
  524. grid-column: 1 / -1;
  525. margin-bottom: ${space(0.25)};
  526. }
  527. `;
  528. const ChartWrapper = styled('div')<{narrowGroups: boolean}>`
  529. width: 200px;
  530. align-self: center;
  531. @media (max-width: ${p =>
  532. p.narrowGroups ? p.theme.breakpoints.xlarge : p.theme.breakpoints.large}) {
  533. display: none;
  534. }
  535. `;
  536. const EventCountsWrapper = styled('div')`
  537. display: flex;
  538. justify-content: flex-end;
  539. align-self: center;
  540. width: 60px;
  541. margin: 0 ${space(2)};
  542. @media (min-width: ${p => p.theme.breakpoints.xlarge}) {
  543. width: 80px;
  544. }
  545. `;
  546. const AssigneeWrapper = styled('div')<{narrowGroups: boolean}>`
  547. width: 80px;
  548. margin: 0 ${space(2)};
  549. align-self: center;
  550. @media (max-width: ${p =>
  551. p.narrowGroups ? p.theme.breakpoints.large : p.theme.breakpoints.medium}) {
  552. display: none;
  553. }
  554. `;
  555. // Reprocessing
  556. const StartedColumn = styled('div')`
  557. align-self: center;
  558. margin: 0 ${space(2)};
  559. color: ${p => p.theme.gray500};
  560. ${p => p.theme.overflowEllipsis};
  561. width: 85px;
  562. @media (min-width: ${p => p.theme.breakpoints.small}) {
  563. display: block;
  564. width: 140px;
  565. }
  566. `;
  567. const EventsReprocessedColumn = styled('div')`
  568. align-self: center;
  569. margin: 0 ${space(2)};
  570. color: ${p => p.theme.gray500};
  571. ${p => p.theme.overflowEllipsis};
  572. width: 75px;
  573. @media (min-width: ${p => p.theme.breakpoints.small}) {
  574. width: 140px;
  575. }
  576. `;
  577. const ProgressColumn = styled('div')`
  578. margin: 0 ${space(2)};
  579. align-self: center;
  580. display: none;
  581. @media (min-width: ${p => p.theme.breakpoints.small}) {
  582. display: block;
  583. width: 160px;
  584. }
  585. `;