summaryTable.tsx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  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. .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. // @ts-expect-error TS(7053): Element implicitly has an 'any' type because expre... Remove this comment to see the full error message
  155. const aValue = a[name] ?? 0;
  156. // @ts-expect-error TS(7053): Element implicitly has an 'any' type because expre... Remove this comment to see the full error message
  157. const bValue = b[name] ?? 0;
  158. return order === 'asc' ? aValue - bValue : bValue - aValue;
  159. });
  160. // We do not want to render the table if there is no data to display
  161. // If the data is being loaded, then the whole chart will be in a loading state and this is being handled by the parent component
  162. if (!rows.length) {
  163. return null;
  164. }
  165. return (
  166. <SummaryTableWrapper
  167. hasActions={hasActions}
  168. totalColumnsCount={totalColumns.length}
  169. data-test-id="summary-table"
  170. >
  171. <HeaderCell disabled />
  172. <HeaderCell disabled />
  173. <SortableHeaderCell onClick={changeSort} sortState={sort} name="name">
  174. {t('Name')}
  175. </SortableHeaderCell>
  176. {totalColumns.map(aggregate => (
  177. <SortableHeaderCell
  178. key={aggregate}
  179. onClick={changeSort}
  180. sortState={sort}
  181. name={aggregate}
  182. right
  183. >
  184. {aggregate}
  185. </SortableHeaderCell>
  186. ))}
  187. {hasActions && <HeaderCell disabled right />}
  188. <HeaderCell disabled />
  189. <TableBodyWrapper
  190. hasActions={hasActions}
  191. onMouseLeave={() => {
  192. if (hasMultipleSeries) {
  193. onRowHover?.('');
  194. }
  195. }}
  196. >
  197. {rows.map(row => {
  198. return (
  199. <Fragment key={row.id}>
  200. <Row
  201. onClick={() => {
  202. if (hasMultipleSeries) {
  203. onRowClick({id: row.id, groupBy: row.groupBy});
  204. }
  205. }}
  206. onMouseEnter={() => {
  207. if (hasMultipleSeries) {
  208. onRowHover?.(row.id);
  209. }
  210. }}
  211. >
  212. <PaddingCell />
  213. <Cell
  214. onClick={event => {
  215. event.stopPropagation();
  216. if (hasMultipleSeries) {
  217. onColorDotClick?.(row);
  218. }
  219. }}
  220. >
  221. <ColorDot
  222. color={row.color}
  223. isHidden={!!row.hidden}
  224. style={{
  225. backgroundColor: row.hidden
  226. ? 'transparent'
  227. : colorFn(row.color).alpha(1).string(),
  228. }}
  229. />
  230. </Cell>
  231. <TextOverflowCell>
  232. <Tooltip
  233. title={
  234. <FullSeriesName seriesName={row.seriesName} groupBy={row.groupBy} />
  235. }
  236. delay={500}
  237. overlayStyle={{maxWidth: '80vw'}}
  238. >
  239. <TextOverflow>{row.seriesName}</TextOverflow>
  240. </Tooltip>
  241. </TextOverflowCell>
  242. {totalColumns.map(aggregate => (
  243. <NumberCell key={aggregate}>
  244. {row[aggregate as keyof typeof row]
  245. ? formatMetricUsingUnit(
  246. row[aggregate as keyof typeof row] as number | null,
  247. row.unit
  248. )
  249. : '\u2014'}
  250. </NumberCell>
  251. ))}
  252. {hasActions && (
  253. <CenterCell>
  254. <ButtonBar gap={0.5}>
  255. {row.transaction && (
  256. <div>
  257. <Tooltip title={t('Open Transaction Summary')}>
  258. <LinkButton
  259. to={transactionTo(row.transaction)}
  260. size="zero"
  261. borderless
  262. >
  263. <IconLightning size="sm" />
  264. </LinkButton>
  265. </Tooltip>
  266. </div>
  267. )}
  268. {row.release && (
  269. <div>
  270. <Tooltip title={t('Open Release Details')}>
  271. <LinkButton
  272. to={releaseTo(row.release)}
  273. size="zero"
  274. borderless
  275. >
  276. <IconReleases size="sm" />
  277. </LinkButton>
  278. </Tooltip>
  279. </div>
  280. )}
  281. {/* do not show add/exclude filter if there's no groupby or if this is an equation */}
  282. {Object.keys(row.groupBy ?? {}).length > 0 &&
  283. !row.isEquationSeries && (
  284. <DropdownMenu
  285. items={[
  286. {
  287. key: 'add-to-filter',
  288. label: t('Add to filter'),
  289. size: 'sm',
  290. onAction: () => {
  291. handleRowFilter(
  292. row.queryIndex,
  293. row,
  294. MetricSeriesFilterUpdateType.ADD
  295. );
  296. },
  297. },
  298. {
  299. key: 'exclude-from-filter',
  300. label: t('Exclude from filter'),
  301. size: 'sm',
  302. onAction: () => {
  303. handleRowFilter(
  304. row.queryIndex,
  305. row,
  306. MetricSeriesFilterUpdateType.EXCLUDE
  307. );
  308. },
  309. },
  310. ]}
  311. trigger={triggerProps => (
  312. <Button
  313. {...triggerProps}
  314. aria-label={t('Quick Context Action Menu')}
  315. data-test-id="quick-context-action-trigger"
  316. borderless
  317. size="zero"
  318. onClick={e => {
  319. e.stopPropagation();
  320. e.preventDefault();
  321. triggerProps.onClick?.(e);
  322. }}
  323. icon={<IconFilter size="sm" />}
  324. />
  325. )}
  326. />
  327. )}
  328. </ButtonBar>
  329. </CenterCell>
  330. )}
  331. <PaddingCell />
  332. </Row>
  333. </Fragment>
  334. );
  335. })}
  336. </TableBodyWrapper>
  337. </SummaryTableWrapper>
  338. );
  339. });
  340. function FullSeriesName({
  341. seriesName,
  342. groupBy,
  343. }: {
  344. seriesName: string;
  345. groupBy?: Record<string, string>;
  346. }) {
  347. if (!groupBy || Object.keys(groupBy).length === 0) {
  348. return <Fragment>{seriesName}</Fragment>;
  349. }
  350. const goupByEntries = Object.entries(groupBy);
  351. return (
  352. <Fragment>
  353. {goupByEntries.map(([key, value], index) => {
  354. const formattedValue = value || t('(none)');
  355. return (
  356. <span key={key}>
  357. <strong>{`${key}:`}</strong>
  358. &nbsp;
  359. {index === goupByEntries.length - 1 ? formattedValue : `${formattedValue}, `}
  360. </span>
  361. );
  362. })}
  363. </Fragment>
  364. );
  365. }
  366. function SortableHeaderCell({
  367. sortState,
  368. name,
  369. right,
  370. children,
  371. onClick,
  372. }: {
  373. children: React.ReactNode;
  374. name: SortState['name'];
  375. onClick: (name: SortState['name']) => void;
  376. sortState: SortState;
  377. right?: boolean;
  378. }) {
  379. const sortIcon =
  380. sortState.name === name ? (
  381. <IconArrow size="xs" direction={sortState.order === 'asc' ? 'up' : 'down'} />
  382. ) : (
  383. ''
  384. );
  385. if (right) {
  386. return (
  387. <HeaderCell
  388. onClick={() => {
  389. onClick(name);
  390. }}
  391. right
  392. >
  393. {sortIcon} {children}
  394. </HeaderCell>
  395. );
  396. }
  397. return (
  398. <HeaderCell
  399. onClick={() => {
  400. onClick(name);
  401. }}
  402. >
  403. {children} {sortIcon}
  404. </HeaderCell>
  405. );
  406. }
  407. // These aggregates can always be shown as we can calculate them on the frontend
  408. const DEFAULT_TOTALS: MetricAggregation[] = ['avg', 'min', 'max', 'sum'];
  409. // Count and count_unique will always match the sum column
  410. const TOTALS_BLOCKLIST: MetricAggregation[] = ['count', 'count_unique'];
  411. function getTotalColumns(series: Series[]) {
  412. const totals = new Set<MetricAggregation>();
  413. series.forEach(({aggregate}) => {
  414. if (!DEFAULT_TOTALS.includes(aggregate) && !TOTALS_BLOCKLIST.includes(aggregate)) {
  415. totals.add(aggregate);
  416. }
  417. });
  418. return DEFAULT_TOTALS.concat(Array.from(totals).sort((a, b) => a.localeCompare(b)));
  419. }
  420. function getTotals(series: Series) {
  421. const {data, total, aggregate} = series;
  422. if (!data) {
  423. return {min: null, max: null, avg: null, sum: null};
  424. }
  425. const res = data.reduce(
  426. (acc, {value}) => {
  427. if (value === null) {
  428. return acc;
  429. }
  430. acc.min = Math.min(acc.min, value);
  431. acc.max = Math.max(acc.max, value);
  432. acc.sum += value;
  433. acc.definedDatapoints += 1;
  434. return acc;
  435. },
  436. {min: Infinity, max: -Infinity, sum: 0, definedDatapoints: 0}
  437. );
  438. const values: Partial<Record<MetricAggregation, number>> = {
  439. min: res.min,
  440. max: res.max,
  441. sum: res.sum,
  442. avg: res.sum / res.definedDatapoints,
  443. };
  444. values[aggregate] = total;
  445. return values;
  446. }
  447. const SummaryTableWrapper = styled(`div`)<{
  448. hasActions: boolean;
  449. totalColumnsCount: number;
  450. }>`
  451. display: grid;
  452. /* padding | color dot | name | avg | min | max | sum | total | actions | padding */
  453. grid-template-columns:
  454. ${space(0.75)} ${space(3)} 8fr repeat(
  455. ${p => (p.hasActions ? p.totalColumnsCount + 1 : p.totalColumnsCount)},
  456. max-content
  457. )
  458. ${space(0.75)};
  459. max-height: 200px;
  460. overflow-x: hidden;
  461. overflow-y: auto;
  462. border: 1px solid ${p => p.theme.border};
  463. border-radius: ${p => p.theme.borderRadius};
  464. font-size: ${p => p.theme.fontSizeSmall};
  465. `;
  466. const TableBodyWrapper = styled(`div`)<{hasActions: boolean}>`
  467. display: contents;
  468. `;
  469. const HeaderCell = styled('div')<{disabled?: boolean; right?: boolean}>`
  470. display: flex;
  471. flex-direction: row;
  472. text-transform: uppercase;
  473. justify-content: ${p => (p.right ? 'flex-end' : 'flex-start')};
  474. align-items: center;
  475. gap: ${space(0.5)};
  476. padding: ${space(0.25)} ${space(0.75)};
  477. line-height: ${p => p.theme.text.lineHeightBody};
  478. font-weight: ${p => p.theme.fontWeightBold};
  479. font-family: ${p => p.theme.text.family};
  480. color: ${p => p.theme.subText};
  481. user-select: none;
  482. background-color: ${p => p.theme.backgroundSecondary};
  483. border-radius: 0;
  484. border-bottom: 1px solid ${p => p.theme.border};
  485. top: 0;
  486. position: sticky;
  487. z-index: 1;
  488. &:hover {
  489. cursor: ${p => (p.disabled ? 'default' : 'pointer')};
  490. }
  491. `;
  492. const Cell = styled('div')<{right?: boolean}>`
  493. display: flex;
  494. padding: ${space(0.25)} ${space(0.75)};
  495. align-items: center;
  496. justify-content: flex-start;
  497. white-space: nowrap;
  498. `;
  499. const NumberCell = styled(Cell)`
  500. justify-content: flex-end;
  501. font-variant-numeric: tabular-nums;
  502. `;
  503. const CenterCell = styled(Cell)`
  504. justify-content: center;
  505. `;
  506. const TextOverflowCell = styled(Cell)`
  507. min-width: 0;
  508. `;
  509. const ColorDot = styled(`div`)<{color: string; isHidden: boolean}>`
  510. border: 1px solid ${p => p.color};
  511. border-radius: 50%;
  512. width: ${space(1)};
  513. height: ${space(1)};
  514. `;
  515. const PaddingCell = styled(Cell)`
  516. padding: 0;
  517. `;
  518. const Row = styled('div')`
  519. display: contents;
  520. &:hover {
  521. cursor: pointer;
  522. ${Cell}, ${NumberCell}, ${CenterCell}, ${PaddingCell}, ${TextOverflowCell} {
  523. background-color: ${p => p.theme.bodyBackground};
  524. }
  525. }
  526. `;