summaryTable.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  1. import {Fragment, memo, useCallback} from 'react';
  2. import styled from '@emotion/styled';
  3. import * as Sentry from '@sentry/react';
  4. import colorFn from 'color';
  5. import {Button, LinkButton} from 'sentry/components/button';
  6. import ButtonBar from 'sentry/components/buttonBar';
  7. import {DropdownMenu} from 'sentry/components/dropdownMenu';
  8. import TextOverflow from 'sentry/components/textOverflow';
  9. import {Tooltip} from 'sentry/components/tooltip';
  10. import {IconArrow, IconFilter, IconLightning, IconReleases} from 'sentry/icons';
  11. import {t} from 'sentry/locale';
  12. import {space} from 'sentry/styles/space';
  13. import {trackAnalytics} from 'sentry/utils/analytics';
  14. import {getUtcDateString} from 'sentry/utils/dates';
  15. import {DEFAULT_SORT_STATE} from 'sentry/utils/metrics/constants';
  16. import {formatMetricUsingUnit} from 'sentry/utils/metrics/formatters';
  17. import {
  18. type FocusedMetricsSeries,
  19. MetricSeriesFilterUpdateType,
  20. type SortState,
  21. } from 'sentry/utils/metrics/types';
  22. import useOrganization from 'sentry/utils/useOrganization';
  23. import usePageFilters from 'sentry/utils/usePageFilters';
  24. import type {Series} from 'sentry/views/metrics/chart/types';
  25. import {transactionSummaryRouteWithQuery} from 'sentry/views/performance/transactionSummary/utils';
  26. export const SummaryTable = memo(function SummaryTable({
  27. series,
  28. onRowClick,
  29. onColorDotClick,
  30. onSortChange,
  31. sort = DEFAULT_SORT_STATE as SortState,
  32. onRowHover,
  33. onRowFilter,
  34. }: {
  35. onRowClick: (series: FocusedMetricsSeries) => void;
  36. onSortChange: (sortState: SortState) => void;
  37. series: Series[];
  38. onColorDotClick?: (series: FocusedMetricsSeries) => void;
  39. onRowFilter?: (
  40. index: number,
  41. series: FocusedMetricsSeries,
  42. updateType: MetricSeriesFilterUpdateType
  43. ) => void;
  44. onRowHover?: (seriesName: string) => void;
  45. sort?: SortState;
  46. }) {
  47. const {selection} = usePageFilters();
  48. const organization = useOrganization();
  49. const canFilter = series.length > 1 && !!onRowFilter;
  50. const hasActions = series.some(s => s.release || s.transaction) || canFilter;
  51. const hasMultipleSeries = series.length > 1;
  52. const changeSort = useCallback(
  53. (name: SortState['name']) => {
  54. trackAnalytics('ddm.widget.sort', {
  55. organization,
  56. by: name ?? '(none)',
  57. order: sort.order,
  58. });
  59. Sentry.metrics.increment('ddm.widget.sort', 1, {
  60. tags: {
  61. by: name ?? '(none)',
  62. order: sort.order,
  63. },
  64. });
  65. if (sort.name === name) {
  66. if (sort.order === 'desc') {
  67. onSortChange(DEFAULT_SORT_STATE as SortState);
  68. } else if (sort.order === 'asc') {
  69. onSortChange({
  70. name,
  71. order: 'desc',
  72. });
  73. } else {
  74. onSortChange({
  75. name,
  76. order: 'asc',
  77. });
  78. }
  79. } else {
  80. onSortChange({
  81. name,
  82. order: 'asc',
  83. });
  84. }
  85. },
  86. [sort, onSortChange, organization]
  87. );
  88. const handleRowFilter = useCallback(
  89. (
  90. index: number | undefined,
  91. row: FocusedMetricsSeries,
  92. updateType: MetricSeriesFilterUpdateType
  93. ) => {
  94. if (index === undefined) {
  95. return;
  96. }
  97. trackAnalytics('ddm.widget.add_row_filter', {
  98. organization,
  99. });
  100. onRowFilter?.(index, row, updateType);
  101. },
  102. [onRowFilter, organization]
  103. );
  104. const releaseTo = (release: string) => {
  105. return {
  106. pathname: `/organizations/${organization.slug}/releases/${encodeURIComponent(
  107. release
  108. )}/`,
  109. query: {
  110. pageStart: selection.datetime.start,
  111. pageEnd: selection.datetime.end,
  112. pageStatsPeriod: selection.datetime.period,
  113. project: selection.projects,
  114. environment: selection.environments,
  115. },
  116. };
  117. };
  118. const transactionTo = (transaction: string) =>
  119. transactionSummaryRouteWithQuery({
  120. orgSlug: organization.slug,
  121. transaction,
  122. projectID: selection.projects.map(p => String(p)),
  123. query: {
  124. query: '',
  125. environment: selection.environments,
  126. start: selection.datetime.start
  127. ? getUtcDateString(selection.datetime.start)
  128. : undefined,
  129. end: selection.datetime.end
  130. ? getUtcDateString(selection.datetime.end)
  131. : undefined,
  132. statsPeriod: selection.datetime.period,
  133. },
  134. });
  135. const rows = series
  136. .map(s => {
  137. return {
  138. ...s,
  139. ...getValues(s.data),
  140. };
  141. })
  142. // Filter series with no data
  143. .filter(s => s.min !== Infinity)
  144. .sort((a, b) => {
  145. const {name, order} = sort;
  146. if (!name) {
  147. return 0;
  148. }
  149. if (name === 'name') {
  150. return order === 'asc'
  151. ? a.seriesName.localeCompare(b.seriesName)
  152. : b.seriesName.localeCompare(a.seriesName);
  153. }
  154. const aValue = a[name] ?? 0;
  155. const bValue = b[name] ?? 0;
  156. return order === 'asc' ? aValue - bValue : bValue - aValue;
  157. });
  158. return (
  159. <SummaryTableWrapper hasActions={hasActions}>
  160. <HeaderCell disabled />
  161. <HeaderCell disabled />
  162. <SortableHeaderCell onClick={changeSort} sortState={sort} name="name">
  163. {t('Name')}
  164. </SortableHeaderCell>
  165. <SortableHeaderCell onClick={changeSort} sortState={sort} name="avg" right>
  166. {t('Avg')}
  167. </SortableHeaderCell>
  168. <SortableHeaderCell onClick={changeSort} sortState={sort} name="min" right>
  169. {t('Min')}
  170. </SortableHeaderCell>
  171. <SortableHeaderCell onClick={changeSort} sortState={sort} name="max" right>
  172. {t('Max')}
  173. </SortableHeaderCell>
  174. <SortableHeaderCell onClick={changeSort} sortState={sort} name="sum" right>
  175. {t('Sum')}
  176. </SortableHeaderCell>
  177. <SortableHeaderCell onClick={changeSort} sortState={sort} name="total" right>
  178. {t('Total')}
  179. </SortableHeaderCell>
  180. {hasActions && <HeaderCell disabled right />}
  181. <HeaderCell disabled />
  182. <TableBodyWrapper
  183. hasActions={hasActions}
  184. onMouseLeave={() => {
  185. if (hasMultipleSeries) {
  186. onRowHover?.('');
  187. }
  188. }}
  189. >
  190. {rows.map(
  191. ({
  192. seriesName,
  193. id,
  194. groupBy,
  195. color,
  196. hidden,
  197. unit,
  198. transaction,
  199. release,
  200. avg,
  201. min,
  202. max,
  203. sum,
  204. total,
  205. isEquationSeries,
  206. queryIndex,
  207. }) => {
  208. return (
  209. <Fragment key={id}>
  210. <Row
  211. onClick={() => {
  212. if (hasMultipleSeries) {
  213. onRowClick({
  214. id,
  215. groupBy,
  216. });
  217. }
  218. }}
  219. onMouseEnter={() => {
  220. if (hasMultipleSeries) {
  221. onRowHover?.(id);
  222. }
  223. }}
  224. >
  225. <PaddingCell />
  226. <Cell
  227. onClick={event => {
  228. event.stopPropagation();
  229. if (hasMultipleSeries) {
  230. onColorDotClick?.({
  231. id,
  232. groupBy,
  233. });
  234. }
  235. }}
  236. >
  237. <ColorDot
  238. color={color}
  239. isHidden={!!hidden}
  240. style={{
  241. backgroundColor: hidden
  242. ? 'transparent'
  243. : colorFn(color).alpha(1).string(),
  244. }}
  245. />
  246. </Cell>
  247. <TextOverflowCell>
  248. <Tooltip
  249. title={<FullSeriesName seriesName={seriesName} groupBy={groupBy} />}
  250. delay={500}
  251. overlayStyle={{maxWidth: '80vw'}}
  252. >
  253. <TextOverflow>{seriesName}</TextOverflow>
  254. </Tooltip>
  255. </TextOverflowCell>
  256. <NumberCell>{formatMetricUsingUnit(avg, unit)}</NumberCell>
  257. <NumberCell>{formatMetricUsingUnit(min, unit)}</NumberCell>
  258. <NumberCell>{formatMetricUsingUnit(max, unit)}</NumberCell>
  259. <NumberCell>{formatMetricUsingUnit(sum, unit)}</NumberCell>
  260. <NumberCell>{formatMetricUsingUnit(total, unit)}</NumberCell>
  261. {hasActions && (
  262. <CenterCell>
  263. <ButtonBar gap={0.5}>
  264. {transaction && (
  265. <div>
  266. <Tooltip title={t('Open Transaction Summary')}>
  267. <LinkButton
  268. to={transactionTo(transaction)}
  269. size="zero"
  270. borderless
  271. >
  272. <IconLightning size="sm" />
  273. </LinkButton>
  274. </Tooltip>
  275. </div>
  276. )}
  277. {release && (
  278. <div>
  279. <Tooltip title={t('Open Release Details')}>
  280. <LinkButton to={releaseTo(release)} size="zero" borderless>
  281. <IconReleases size="sm" />
  282. </LinkButton>
  283. </Tooltip>
  284. </div>
  285. )}
  286. <DropdownMenu
  287. items={[
  288. {
  289. key: 'add-to-filter',
  290. label: t('Add to filter'),
  291. size: 'sm',
  292. onAction: () => {
  293. handleRowFilter(
  294. queryIndex,
  295. {
  296. id,
  297. groupBy,
  298. },
  299. MetricSeriesFilterUpdateType.ADD
  300. );
  301. },
  302. },
  303. {
  304. key: 'exclude-from-filter',
  305. label: t('Exclude from filter'),
  306. size: 'sm',
  307. onAction: () => {
  308. handleRowFilter(
  309. queryIndex,
  310. {
  311. id,
  312. groupBy,
  313. },
  314. MetricSeriesFilterUpdateType.EXCLUDE
  315. );
  316. },
  317. },
  318. ]}
  319. trigger={triggerProps => (
  320. <Button
  321. {...triggerProps}
  322. aria-label={t('Quick Context Action Menu')}
  323. data-test-id="quick-context-action-trigger"
  324. borderless
  325. size="zero"
  326. disabled={isEquationSeries}
  327. onClick={e => {
  328. e.stopPropagation();
  329. e.preventDefault();
  330. triggerProps.onClick?.(e);
  331. }}
  332. icon={<IconFilter size="sm" />}
  333. />
  334. )}
  335. />
  336. </ButtonBar>
  337. </CenterCell>
  338. )}
  339. <PaddingCell />
  340. </Row>
  341. </Fragment>
  342. );
  343. }
  344. )}
  345. </TableBodyWrapper>
  346. </SummaryTableWrapper>
  347. );
  348. });
  349. function FullSeriesName({
  350. seriesName,
  351. groupBy,
  352. }: {
  353. seriesName: string;
  354. groupBy?: Record<string, string>;
  355. }) {
  356. if (!groupBy || Object.keys(groupBy).length === 0) {
  357. return <Fragment>{seriesName}</Fragment>;
  358. }
  359. const goupByEntries = Object.entries(groupBy);
  360. return (
  361. <Fragment>
  362. {goupByEntries.map(([key, value], index) => {
  363. const formattedValue = value || t('(none)');
  364. return (
  365. <span key={key}>
  366. <strong>{`${key}:`}</strong>
  367. &nbsp;
  368. {index === goupByEntries.length - 1 ? formattedValue : `${formattedValue}, `}
  369. </span>
  370. );
  371. })}
  372. </Fragment>
  373. );
  374. }
  375. function SortableHeaderCell({
  376. sortState,
  377. name,
  378. right,
  379. children,
  380. onClick,
  381. }: {
  382. children: React.ReactNode;
  383. name: SortState['name'];
  384. onClick: (name: SortState['name']) => void;
  385. sortState: SortState;
  386. right?: boolean;
  387. }) {
  388. const sortIcon =
  389. sortState.name === name ? (
  390. <IconArrow size="xs" direction={sortState.order === 'asc' ? 'up' : 'down'} />
  391. ) : (
  392. ''
  393. );
  394. if (right) {
  395. return (
  396. <HeaderCell
  397. onClick={() => {
  398. onClick(name);
  399. }}
  400. right
  401. >
  402. {sortIcon} {children}
  403. </HeaderCell>
  404. );
  405. }
  406. return (
  407. <HeaderCell
  408. onClick={() => {
  409. onClick(name);
  410. }}
  411. >
  412. {children} {sortIcon}
  413. </HeaderCell>
  414. );
  415. }
  416. function getValues(seriesData: Series['data']) {
  417. if (!seriesData) {
  418. return {min: null, max: null, avg: null, sum: null};
  419. }
  420. const res = seriesData.reduce(
  421. (acc, {value}) => {
  422. if (value === null) {
  423. return acc;
  424. }
  425. acc.min = Math.min(acc.min, value);
  426. acc.max = Math.max(acc.max, value);
  427. acc.sum += value;
  428. acc.definedDatapoints += 1;
  429. return acc;
  430. },
  431. {min: Infinity, max: -Infinity, sum: 0, definedDatapoints: 0}
  432. );
  433. return {min: res.min, max: res.max, sum: res.sum, avg: res.sum / res.definedDatapoints};
  434. }
  435. const SummaryTableWrapper = styled(`div`)<{hasActions: boolean}>`
  436. display: grid;
  437. /* padding | color dot | name | avg | min | max | sum | total | actions | padding */
  438. grid-template-columns:
  439. ${space(0.75)} ${space(3)} 8fr repeat(${p => (p.hasActions ? 6 : 5)}, max-content)
  440. ${space(0.75)};
  441. max-height: 200px;
  442. overflow-x: hidden;
  443. overflow-y: auto;
  444. border: 1px solid ${p => p.theme.border};
  445. border-radius: ${p => p.theme.borderRadius};
  446. font-size: ${p => p.theme.fontSizeSmall};
  447. `;
  448. const TableBodyWrapper = styled(`div`)<{hasActions: boolean}>`
  449. display: contents;
  450. `;
  451. const HeaderCell = styled('div')<{disabled?: boolean; right?: boolean}>`
  452. display: flex;
  453. flex-direction: row;
  454. text-transform: uppercase;
  455. justify-content: ${p => (p.right ? 'flex-end' : 'flex-start')};
  456. align-items: center;
  457. gap: ${space(0.5)};
  458. padding: ${space(0.25)} ${space(0.75)};
  459. line-height: ${p => p.theme.text.lineHeightBody};
  460. font-weight: 600;
  461. font-family: ${p => p.theme.text.family};
  462. color: ${p => p.theme.subText};
  463. user-select: none;
  464. background-color: ${p => p.theme.backgroundSecondary};
  465. border-radius: 0;
  466. border-bottom: 1px solid ${p => p.theme.border};
  467. top: 0;
  468. position: sticky;
  469. z-index: 1;
  470. &:hover {
  471. cursor: ${p => (p.disabled ? 'default' : 'pointer')};
  472. }
  473. `;
  474. const Cell = styled('div')<{right?: boolean}>`
  475. display: flex;
  476. padding: ${space(0.25)} ${space(0.75)};
  477. align-items: center;
  478. justify-content: flex-start;
  479. white-space: nowrap;
  480. `;
  481. const NumberCell = styled(Cell)`
  482. justify-content: flex-end;
  483. font-variant-numeric: tabular-nums;
  484. `;
  485. const CenterCell = styled(Cell)`
  486. justify-content: center;
  487. `;
  488. const TextOverflowCell = styled(Cell)`
  489. min-width: 0;
  490. `;
  491. const ColorDot = styled(`div`)<{color: string; isHidden: boolean}>`
  492. border: 1px solid ${p => p.color};
  493. border-radius: 50%;
  494. width: ${space(1)};
  495. height: ${space(1)};
  496. `;
  497. const PaddingCell = styled(Cell)`
  498. padding: 0;
  499. `;
  500. const Row = styled('div')`
  501. display: contents;
  502. &:hover {
  503. cursor: pointer;
  504. ${Cell}, ${NumberCell}, ${CenterCell}, ${PaddingCell}, ${TextOverflowCell} {
  505. background-color: ${p => p.theme.bodyBackground};
  506. }
  507. }
  508. `;