summaryTable.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  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 {trackAnalytics} from 'sentry/utils/analytics';
  15. import {getUtcDateString} from 'sentry/utils/dates';
  16. import {DEFAULT_SORT_STATE} from 'sentry/utils/metrics/constants';
  17. import {formatMetricUsingUnit} from 'sentry/utils/metrics/formatters';
  18. import {
  19. type FocusedMetricsSeries,
  20. MetricSeriesFilterUpdateType,
  21. type SortState,
  22. } from 'sentry/utils/metrics/types';
  23. import useOrganization from 'sentry/utils/useOrganization';
  24. import usePageFilters from 'sentry/utils/usePageFilters';
  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),
  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. <Tooltip title={t('Selected aggregation over the whole time period')}>
  179. {t('Value')}
  180. </Tooltip>
  181. </SortableHeaderCell>
  182. {hasActions && <HeaderCell disabled right />}
  183. <HeaderCell disabled />
  184. <TableBodyWrapper
  185. hasActions={hasActions}
  186. onMouseLeave={() => {
  187. if (hasMultipleSeries) {
  188. onRowHover?.('');
  189. }
  190. }}
  191. >
  192. {rows.map(
  193. ({
  194. seriesName,
  195. id,
  196. groupBy,
  197. color,
  198. hidden,
  199. unit,
  200. transaction,
  201. release,
  202. avg,
  203. min,
  204. max,
  205. sum,
  206. total,
  207. isEquationSeries,
  208. queryIndex,
  209. }) => {
  210. return (
  211. <Fragment key={id}>
  212. <Row
  213. onClick={() => {
  214. if (hasMultipleSeries) {
  215. onRowClick({
  216. id,
  217. groupBy,
  218. });
  219. }
  220. }}
  221. onMouseEnter={() => {
  222. if (hasMultipleSeries) {
  223. onRowHover?.(id);
  224. }
  225. }}
  226. >
  227. <PaddingCell />
  228. <Cell
  229. onClick={event => {
  230. event.stopPropagation();
  231. if (hasMultipleSeries) {
  232. onColorDotClick?.({
  233. id,
  234. groupBy,
  235. });
  236. }
  237. }}
  238. >
  239. <ColorDot
  240. color={color}
  241. isHidden={!!hidden}
  242. style={{
  243. backgroundColor: hidden
  244. ? 'transparent'
  245. : colorFn(color).alpha(1).string(),
  246. }}
  247. />
  248. </Cell>
  249. <TextOverflowCell>
  250. <Tooltip
  251. title={<FullSeriesName seriesName={seriesName} groupBy={groupBy} />}
  252. delay={500}
  253. overlayStyle={{maxWidth: '80vw'}}
  254. >
  255. <TextOverflow>{seriesName}</TextOverflow>
  256. </Tooltip>
  257. </TextOverflowCell>
  258. <NumberCell>{formatMetricUsingUnit(avg, unit)}</NumberCell>
  259. <NumberCell>{formatMetricUsingUnit(min, unit)}</NumberCell>
  260. <NumberCell>{formatMetricUsingUnit(max, unit)}</NumberCell>
  261. <NumberCell>{formatMetricUsingUnit(sum, unit)}</NumberCell>
  262. <NumberCell>{formatMetricUsingUnit(total, unit)}</NumberCell>
  263. {hasActions && (
  264. <CenterCell>
  265. <ButtonBar gap={0.5}>
  266. {transaction && (
  267. <div>
  268. <Tooltip title={t('Open Transaction Summary')}>
  269. <LinkButton
  270. to={transactionTo(transaction)}
  271. size="zero"
  272. borderless
  273. >
  274. <IconLightning size="sm" />
  275. </LinkButton>
  276. </Tooltip>
  277. </div>
  278. )}
  279. {release && (
  280. <div>
  281. <Tooltip title={t('Open Release Details')}>
  282. <LinkButton to={releaseTo(release)} size="zero" borderless>
  283. <IconReleases size="sm" />
  284. </LinkButton>
  285. </Tooltip>
  286. </div>
  287. )}
  288. {/* do not show add/exclude filter if there's no groupby or if this is an equation */}
  289. {Object.keys(groupBy ?? {}).length > 0 && !isEquationSeries && (
  290. <DropdownMenu
  291. items={[
  292. {
  293. key: 'add-to-filter',
  294. label: t('Add to filter'),
  295. size: 'sm',
  296. onAction: () => {
  297. handleRowFilter(
  298. queryIndex,
  299. {
  300. id,
  301. groupBy,
  302. },
  303. MetricSeriesFilterUpdateType.ADD
  304. );
  305. },
  306. },
  307. {
  308. key: 'exclude-from-filter',
  309. label: t('Exclude from filter'),
  310. size: 'sm',
  311. onAction: () => {
  312. handleRowFilter(
  313. queryIndex,
  314. {
  315. id,
  316. groupBy,
  317. },
  318. MetricSeriesFilterUpdateType.EXCLUDE
  319. );
  320. },
  321. },
  322. ]}
  323. trigger={triggerProps => (
  324. <Button
  325. {...triggerProps}
  326. aria-label={t('Quick Context Action Menu')}
  327. data-test-id="quick-context-action-trigger"
  328. borderless
  329. size="zero"
  330. onClick={e => {
  331. e.stopPropagation();
  332. e.preventDefault();
  333. triggerProps.onClick?.(e);
  334. }}
  335. icon={<IconFilter size="sm" />}
  336. />
  337. )}
  338. />
  339. )}
  340. </ButtonBar>
  341. </CenterCell>
  342. )}
  343. <PaddingCell />
  344. </Row>
  345. </Fragment>
  346. );
  347. }
  348. )}
  349. </TableBodyWrapper>
  350. </SummaryTableWrapper>
  351. );
  352. });
  353. function FullSeriesName({
  354. seriesName,
  355. groupBy,
  356. }: {
  357. seriesName: string;
  358. groupBy?: Record<string, string>;
  359. }) {
  360. if (!groupBy || Object.keys(groupBy).length === 0) {
  361. return <Fragment>{seriesName}</Fragment>;
  362. }
  363. const goupByEntries = Object.entries(groupBy);
  364. return (
  365. <Fragment>
  366. {goupByEntries.map(([key, value], index) => {
  367. const formattedValue = value || t('(none)');
  368. return (
  369. <span key={key}>
  370. <strong>{`${key}:`}</strong>
  371. &nbsp;
  372. {index === goupByEntries.length - 1 ? formattedValue : `${formattedValue}, `}
  373. </span>
  374. );
  375. })}
  376. </Fragment>
  377. );
  378. }
  379. function SortableHeaderCell({
  380. sortState,
  381. name,
  382. right,
  383. children,
  384. onClick,
  385. }: {
  386. children: React.ReactNode;
  387. name: SortState['name'];
  388. onClick: (name: SortState['name']) => void;
  389. sortState: SortState;
  390. right?: boolean;
  391. }) {
  392. const sortIcon =
  393. sortState.name === name ? (
  394. <IconArrow size="xs" direction={sortState.order === 'asc' ? 'up' : 'down'} />
  395. ) : (
  396. ''
  397. );
  398. if (right) {
  399. return (
  400. <HeaderCell
  401. onClick={() => {
  402. onClick(name);
  403. }}
  404. right
  405. >
  406. {sortIcon} {children}
  407. </HeaderCell>
  408. );
  409. }
  410. return (
  411. <HeaderCell
  412. onClick={() => {
  413. onClick(name);
  414. }}
  415. >
  416. {children} {sortIcon}
  417. </HeaderCell>
  418. );
  419. }
  420. function getValues(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 = {
  439. min: res.min,
  440. max: res.max,
  441. sum: res.sum,
  442. avg: res.sum / res.definedDatapoints,
  443. };
  444. if (aggregate in values) {
  445. values[aggregate] = total;
  446. }
  447. return values;
  448. }
  449. const SummaryTableWrapper = styled(`div`)<{hasActions: boolean}>`
  450. display: grid;
  451. /* padding | color dot | name | avg | min | max | sum | total | actions | padding */
  452. grid-template-columns:
  453. ${space(0.75)} ${space(3)} 8fr repeat(${p => (p.hasActions ? 6 : 5)}, max-content)
  454. ${space(0.75)};
  455. max-height: 200px;
  456. overflow-x: hidden;
  457. overflow-y: auto;
  458. border: 1px solid ${p => p.theme.border};
  459. border-radius: ${p => p.theme.borderRadius};
  460. font-size: ${p => p.theme.fontSizeSmall};
  461. `;
  462. const TableBodyWrapper = styled(`div`)<{hasActions: boolean}>`
  463. display: contents;
  464. `;
  465. const HeaderCell = styled('div')<{disabled?: boolean; right?: boolean}>`
  466. display: flex;
  467. flex-direction: row;
  468. text-transform: uppercase;
  469. justify-content: ${p => (p.right ? 'flex-end' : 'flex-start')};
  470. align-items: center;
  471. gap: ${space(0.5)};
  472. padding: ${space(0.25)} ${space(0.75)};
  473. line-height: ${p => p.theme.text.lineHeightBody};
  474. font-weight: ${p => p.theme.fontWeightBold};
  475. font-family: ${p => p.theme.text.family};
  476. color: ${p => p.theme.subText};
  477. user-select: none;
  478. background-color: ${p => p.theme.backgroundSecondary};
  479. border-radius: 0;
  480. border-bottom: 1px solid ${p => p.theme.border};
  481. top: 0;
  482. position: sticky;
  483. z-index: 1;
  484. &:hover {
  485. cursor: ${p => (p.disabled ? 'default' : 'pointer')};
  486. }
  487. `;
  488. const Cell = styled('div')<{right?: boolean}>`
  489. display: flex;
  490. padding: ${space(0.25)} ${space(0.75)};
  491. align-items: center;
  492. justify-content: flex-start;
  493. white-space: nowrap;
  494. `;
  495. const NumberCell = styled(Cell)`
  496. justify-content: flex-end;
  497. font-variant-numeric: tabular-nums;
  498. `;
  499. const CenterCell = styled(Cell)`
  500. justify-content: center;
  501. `;
  502. const TextOverflowCell = styled(Cell)`
  503. min-width: 0;
  504. `;
  505. const ColorDot = styled(`div`)<{color: string; isHidden: boolean}>`
  506. border: 1px solid ${p => p.color};
  507. border-radius: 50%;
  508. width: ${space(1)};
  509. height: ${space(1)};
  510. `;
  511. const PaddingCell = styled(Cell)`
  512. padding: 0;
  513. `;
  514. const Row = styled('div')`
  515. display: contents;
  516. &:hover {
  517. cursor: pointer;
  518. ${Cell}, ${NumberCell}, ${CenterCell}, ${PaddingCell}, ${TextOverflowCell} {
  519. background-color: ${p => p.theme.bodyBackground};
  520. }
  521. }
  522. `;