summaryTable.tsx 16 KB

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