summaryTable.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  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. {/* TODO(ddm): Add a tooltip with the full value, don't add on click in case users want to copy the value */}
  257. <NumberCell>{formatMetricUsingUnit(avg, unit)}</NumberCell>
  258. <NumberCell>{formatMetricUsingUnit(min, unit)}</NumberCell>
  259. <NumberCell>{formatMetricUsingUnit(max, unit)}</NumberCell>
  260. <NumberCell>{formatMetricUsingUnit(sum, unit)}</NumberCell>
  261. <NumberCell>{formatMetricUsingUnit(total, unit)}</NumberCell>
  262. {hasActions && (
  263. <CenterCell>
  264. <ButtonBar gap={0.5}>
  265. {transaction && (
  266. <div>
  267. <Tooltip title={t('Open Transaction Summary')}>
  268. <LinkButton
  269. to={transactionTo(transaction)}
  270. size="zero"
  271. borderless
  272. >
  273. <IconLightning size="sm" />
  274. </LinkButton>
  275. </Tooltip>
  276. </div>
  277. )}
  278. {release && (
  279. <div>
  280. <Tooltip title={t('Open Release Details')}>
  281. <LinkButton to={releaseTo(release)} size="zero" borderless>
  282. <IconReleases size="sm" />
  283. </LinkButton>
  284. </Tooltip>
  285. </div>
  286. )}
  287. <DropdownMenu
  288. items={[
  289. {
  290. key: 'add-to-filter',
  291. label: t('Add to filter'),
  292. size: 'sm',
  293. onAction: () => {
  294. handleRowFilter(
  295. queryIndex,
  296. {
  297. id,
  298. groupBy,
  299. },
  300. MetricSeriesFilterUpdateType.ADD
  301. );
  302. },
  303. },
  304. {
  305. key: 'exclude-from-filter',
  306. label: t('Exclude from filter'),
  307. size: 'sm',
  308. onAction: () => {
  309. handleRowFilter(
  310. queryIndex,
  311. {
  312. id,
  313. groupBy,
  314. },
  315. MetricSeriesFilterUpdateType.EXCLUDE
  316. );
  317. },
  318. },
  319. ]}
  320. trigger={triggerProps => (
  321. <Button
  322. {...triggerProps}
  323. aria-label={t('Quick Context Action Menu')}
  324. data-test-id="quick-context-action-trigger"
  325. borderless
  326. size="zero"
  327. disabled={isEquationSeries}
  328. onClick={e => {
  329. e.stopPropagation();
  330. e.preventDefault();
  331. triggerProps.onClick?.(e);
  332. }}
  333. icon={<IconFilter size="sm" />}
  334. />
  335. )}
  336. />
  337. </ButtonBar>
  338. </CenterCell>
  339. )}
  340. <PaddingCell />
  341. </Row>
  342. </Fragment>
  343. );
  344. }
  345. )}
  346. </TableBodyWrapper>
  347. </SummaryTableWrapper>
  348. );
  349. });
  350. function FullSeriesName({
  351. seriesName,
  352. groupBy,
  353. }: {
  354. seriesName: string;
  355. groupBy?: Record<string, string>;
  356. }) {
  357. if (!groupBy || Object.keys(groupBy).length === 0) {
  358. return <Fragment>{seriesName}</Fragment>;
  359. }
  360. const goupByEntries = Object.entries(groupBy);
  361. return (
  362. <Fragment>
  363. {goupByEntries.map(([key, value], index) => {
  364. const formattedValue = value || t('(none)');
  365. return (
  366. <span key={key}>
  367. <strong>{`${key}:`}</strong>
  368. &nbsp;
  369. {index === goupByEntries.length - 1 ? formattedValue : `${formattedValue}, `}
  370. </span>
  371. );
  372. })}
  373. </Fragment>
  374. );
  375. }
  376. function SortableHeaderCell({
  377. sortState,
  378. name,
  379. right,
  380. children,
  381. onClick,
  382. }: {
  383. children: React.ReactNode;
  384. name: SortState['name'];
  385. onClick: (name: SortState['name']) => void;
  386. sortState: SortState;
  387. right?: boolean;
  388. }) {
  389. const sortIcon =
  390. sortState.name === name ? (
  391. <IconArrow size="xs" direction={sortState.order === 'asc' ? 'up' : 'down'} />
  392. ) : (
  393. ''
  394. );
  395. if (right) {
  396. return (
  397. <HeaderCell
  398. onClick={() => {
  399. onClick(name);
  400. }}
  401. right
  402. >
  403. {sortIcon} {children}
  404. </HeaderCell>
  405. );
  406. }
  407. return (
  408. <HeaderCell
  409. onClick={() => {
  410. onClick(name);
  411. }}
  412. >
  413. {children} {sortIcon}
  414. </HeaderCell>
  415. );
  416. }
  417. function getValues(seriesData: Series['data']) {
  418. if (!seriesData) {
  419. return {min: null, max: null, avg: null, sum: null};
  420. }
  421. const res = seriesData.reduce(
  422. (acc, {value}) => {
  423. if (value === null) {
  424. return acc;
  425. }
  426. acc.min = Math.min(acc.min, value);
  427. acc.max = Math.max(acc.max, value);
  428. acc.sum += value;
  429. acc.definedDatapoints += 1;
  430. return acc;
  431. },
  432. {min: Infinity, max: -Infinity, sum: 0, definedDatapoints: 0}
  433. );
  434. return {min: res.min, max: res.max, sum: res.sum, avg: res.sum / res.definedDatapoints};
  435. }
  436. const SummaryTableWrapper = styled(`div`)<{hasActions: boolean}>`
  437. display: grid;
  438. /* padding | color dot | name | avg | min | max | sum | total | actions | padding */
  439. grid-template-columns:
  440. ${space(0.75)} ${space(3)} 8fr repeat(${p => (p.hasActions ? 6 : 5)}, max-content)
  441. ${space(0.75)};
  442. max-height: 200px;
  443. overflow-x: hidden;
  444. overflow-y: auto;
  445. border: 1px solid ${p => p.theme.border};
  446. border-radius: ${p => p.theme.borderRadius};
  447. font-size: ${p => p.theme.fontSizeSmall};
  448. `;
  449. const TableBodyWrapper = styled(`div`)<{hasActions: boolean}>`
  450. display: contents;
  451. `;
  452. const HeaderCell = styled('div')<{disabled?: boolean; right?: boolean}>`
  453. display: flex;
  454. flex-direction: row;
  455. text-transform: uppercase;
  456. justify-content: ${p => (p.right ? 'flex-end' : 'flex-start')};
  457. align-items: center;
  458. gap: ${space(0.5)};
  459. padding: ${space(0.25)} ${space(0.75)};
  460. line-height: ${p => p.theme.text.lineHeightBody};
  461. font-weight: 600;
  462. font-family: ${p => p.theme.text.family};
  463. color: ${p => p.theme.subText};
  464. user-select: none;
  465. background-color: ${p => p.theme.backgroundSecondary};
  466. border-radius: 0;
  467. border-bottom: 1px solid ${p => p.theme.border};
  468. top: 0;
  469. position: sticky;
  470. z-index: 1;
  471. &:hover {
  472. cursor: ${p => (p.disabled ? 'default' : 'pointer')};
  473. }
  474. `;
  475. const Cell = styled('div')<{right?: boolean}>`
  476. display: flex;
  477. padding: ${space(0.25)} ${space(0.75)};
  478. align-items: center;
  479. justify-content: flex-start;
  480. white-space: nowrap;
  481. `;
  482. const NumberCell = styled(Cell)`
  483. justify-content: flex-end;
  484. font-variant-numeric: tabular-nums;
  485. `;
  486. const CenterCell = styled(Cell)`
  487. justify-content: center;
  488. `;
  489. const TextOverflowCell = styled(Cell)`
  490. min-width: 0;
  491. `;
  492. const ColorDot = styled(`div`)<{color: string; isHidden: boolean}>`
  493. border: 1px solid ${p => p.color};
  494. border-radius: 50%;
  495. width: ${space(1)};
  496. height: ${space(1)};
  497. `;
  498. const PaddingCell = styled(Cell)`
  499. padding: 0;
  500. `;
  501. const Row = styled('div')`
  502. display: contents;
  503. &:hover {
  504. cursor: pointer;
  505. ${Cell}, ${NumberCell}, ${CenterCell}, ${PaddingCell}, ${TextOverflowCell} {
  506. background-color: ${p => p.theme.bodyBackground};
  507. }
  508. }
  509. `;