summaryTable.tsx 16 KB

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