summaryTable.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  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 {LinkButton} from 'sentry/components/button';
  6. import ButtonBar from 'sentry/components/buttonBar';
  7. import TextOverflow from 'sentry/components/textOverflow';
  8. import {Tooltip} from 'sentry/components/tooltip';
  9. import {IconArrow, IconLightning, IconReleases} from 'sentry/icons';
  10. import {t} from 'sentry/locale';
  11. import {space} from 'sentry/styles/space';
  12. import {trackAnalytics} from 'sentry/utils/analytics';
  13. import {getUtcDateString} from 'sentry/utils/dates';
  14. import {DEFAULT_SORT_STATE} from 'sentry/utils/metrics/constants';
  15. import {formatMetricsUsingUnitAndOp} from 'sentry/utils/metrics/formatters';
  16. import type {FocusedMetricsSeries, SortState} from 'sentry/utils/metrics/types';
  17. import useOrganization from 'sentry/utils/useOrganization';
  18. import usePageFilters from 'sentry/utils/usePageFilters';
  19. import type {Series} from 'sentry/views/ddm/chart/types';
  20. import {transactionSummaryRouteWithQuery} from 'sentry/views/performance/transactionSummary/utils';
  21. export const SummaryTable = memo(function SummaryTable({
  22. series,
  23. onRowClick,
  24. onColorDotClick,
  25. onSortChange,
  26. sort = DEFAULT_SORT_STATE as SortState,
  27. onRowHover,
  28. }: {
  29. onRowClick: (series: FocusedMetricsSeries) => void;
  30. onSortChange: (sortState: SortState) => void;
  31. series: Series[];
  32. onColorDotClick?: (series: FocusedMetricsSeries) => void;
  33. onRowHover?: (seriesName: string) => void;
  34. sort?: SortState;
  35. }) {
  36. const {selection} = usePageFilters();
  37. const organization = useOrganization();
  38. const hasActions = series.some(s => s.release || s.transaction);
  39. const hasMultipleSeries = series.length > 1;
  40. const changeSort = useCallback(
  41. (name: SortState['name']) => {
  42. trackAnalytics('ddm.widget.sort', {
  43. organization,
  44. by: name ?? '(none)',
  45. order: sort.order,
  46. });
  47. Sentry.metrics.increment('ddm.widget.sort', 1, {
  48. tags: {
  49. by: name ?? '(none)',
  50. order: sort.order,
  51. },
  52. });
  53. if (sort.name === name) {
  54. if (sort.order === 'desc') {
  55. onSortChange(DEFAULT_SORT_STATE as SortState);
  56. } else if (sort.order === 'asc') {
  57. onSortChange({
  58. name,
  59. order: 'desc',
  60. });
  61. } else {
  62. onSortChange({
  63. name,
  64. order: 'asc',
  65. });
  66. }
  67. } else {
  68. onSortChange({
  69. name,
  70. order: 'asc',
  71. });
  72. }
  73. },
  74. [sort, onSortChange, organization]
  75. );
  76. const releaseTo = (release: string) => {
  77. return {
  78. pathname: `/organizations/${organization.slug}/releases/${encodeURIComponent(
  79. release
  80. )}/`,
  81. query: {
  82. pageStart: selection.datetime.start,
  83. pageEnd: selection.datetime.end,
  84. pageStatsPeriod: selection.datetime.period,
  85. project: selection.projects,
  86. environment: selection.environments,
  87. },
  88. };
  89. };
  90. const transactionTo = (transaction: string) =>
  91. transactionSummaryRouteWithQuery({
  92. orgSlug: organization.slug,
  93. transaction,
  94. projectID: selection.projects.map(p => String(p)),
  95. query: {
  96. query: '',
  97. environment: selection.environments,
  98. start: selection.datetime.start
  99. ? getUtcDateString(selection.datetime.start)
  100. : undefined,
  101. end: selection.datetime.end
  102. ? getUtcDateString(selection.datetime.end)
  103. : undefined,
  104. statsPeriod: selection.datetime.period,
  105. },
  106. });
  107. const rows = series
  108. .map(s => {
  109. return {
  110. ...s,
  111. ...getValues(s.data),
  112. };
  113. })
  114. .sort((a, b) => {
  115. const {name, order} = sort;
  116. if (!name) {
  117. return 0;
  118. }
  119. if (name === 'name') {
  120. return order === 'asc'
  121. ? a.seriesName.localeCompare(b.seriesName)
  122. : b.seriesName.localeCompare(a.seriesName);
  123. }
  124. const aValue = a[name] ?? 0;
  125. const bValue = b[name] ?? 0;
  126. return order === 'asc' ? aValue - bValue : bValue - aValue;
  127. });
  128. return (
  129. <SummaryTableWrapper hasActions={hasActions}>
  130. <HeaderCell disabled />
  131. <HeaderCell disabled />
  132. <SortableHeaderCell onClick={changeSort} sortState={sort} name="name">
  133. {t('Name')}
  134. </SortableHeaderCell>
  135. <SortableHeaderCell onClick={changeSort} sortState={sort} name="avg" right>
  136. {t('Avg')}
  137. </SortableHeaderCell>
  138. <SortableHeaderCell onClick={changeSort} sortState={sort} name="min" right>
  139. {t('Min')}
  140. </SortableHeaderCell>
  141. <SortableHeaderCell onClick={changeSort} sortState={sort} name="max" right>
  142. {t('Max')}
  143. </SortableHeaderCell>
  144. <SortableHeaderCell onClick={changeSort} sortState={sort} name="sum" right>
  145. {t('Sum')}
  146. </SortableHeaderCell>
  147. {hasActions && <HeaderCell disabled right />}
  148. <HeaderCell disabled />
  149. <TableBodyWrapper
  150. hasActions={hasActions}
  151. onMouseLeave={() => {
  152. if (hasMultipleSeries) {
  153. onRowHover?.('');
  154. }
  155. }}
  156. >
  157. {rows.map(
  158. ({
  159. seriesName,
  160. id,
  161. groupBy,
  162. color,
  163. hidden,
  164. unit,
  165. operation,
  166. transaction,
  167. release,
  168. avg,
  169. min,
  170. max,
  171. sum,
  172. }) => {
  173. return (
  174. <Fragment key={id}>
  175. <Row
  176. onClick={() => {
  177. if (hasMultipleSeries) {
  178. onRowClick({
  179. id,
  180. groupBy,
  181. });
  182. }
  183. }}
  184. onMouseEnter={() => {
  185. if (hasMultipleSeries) {
  186. onRowHover?.(id);
  187. }
  188. }}
  189. >
  190. <PaddingCell />
  191. <Cell
  192. onClick={event => {
  193. event.stopPropagation();
  194. if (hasMultipleSeries) {
  195. onColorDotClick?.({
  196. id,
  197. groupBy,
  198. });
  199. }
  200. }}
  201. >
  202. <ColorDot
  203. color={color}
  204. isHidden={!!hidden}
  205. style={{
  206. backgroundColor: hidden
  207. ? 'transparent'
  208. : colorFn(color).alpha(1).string(),
  209. }}
  210. />
  211. </Cell>
  212. <TextOverflowCell>
  213. <Tooltip
  214. title={<FullSeriesName seriesName={seriesName} groupBy={groupBy} />}
  215. delay={500}
  216. overlayStyle={{maxWidth: '80vw'}}
  217. >
  218. <TextOverflow>{seriesName}</TextOverflow>
  219. </Tooltip>
  220. </TextOverflowCell>
  221. {/* TODO(ddm): Add a tooltip with the full value, don't add on click in case users want to copy the value */}
  222. <NumberCell>
  223. {formatMetricsUsingUnitAndOp(avg, unit, operation)}
  224. </NumberCell>
  225. <NumberCell>
  226. {formatMetricsUsingUnitAndOp(min, unit, operation)}
  227. </NumberCell>
  228. <NumberCell>
  229. {formatMetricsUsingUnitAndOp(max, unit, operation)}
  230. </NumberCell>
  231. <NumberCell>
  232. {formatMetricsUsingUnitAndOp(sum, unit, operation)}
  233. </NumberCell>
  234. {hasActions && (
  235. <CenterCell>
  236. <ButtonBar gap={0.5}>
  237. {transaction && (
  238. <div>
  239. <Tooltip title={t('Open Transaction Summary')}>
  240. <LinkButton
  241. to={transactionTo(transaction)}
  242. size="zero"
  243. borderless
  244. >
  245. <IconLightning size="sm" />
  246. </LinkButton>
  247. </Tooltip>
  248. </div>
  249. )}
  250. {release && (
  251. <div>
  252. <Tooltip title={t('Open Release Details')}>
  253. <LinkButton to={releaseTo(release)} size="zero" borderless>
  254. <IconReleases size="sm" />
  255. </LinkButton>
  256. </Tooltip>
  257. </div>
  258. )}
  259. </ButtonBar>
  260. </CenterCell>
  261. )}
  262. <PaddingCell />
  263. </Row>
  264. </Fragment>
  265. );
  266. }
  267. )}
  268. </TableBodyWrapper>
  269. </SummaryTableWrapper>
  270. );
  271. });
  272. function FullSeriesName({
  273. seriesName,
  274. groupBy,
  275. }: {
  276. seriesName: string;
  277. groupBy?: Record<string, string>;
  278. }) {
  279. if (!groupBy || Object.keys(groupBy).length === 0) {
  280. return <Fragment>{seriesName}</Fragment>;
  281. }
  282. const goupByEntries = Object.entries(groupBy);
  283. return (
  284. <Fragment>
  285. {goupByEntries.map(([key, value], index) => {
  286. const formattedValue = value || t('(none)');
  287. return (
  288. <span key={key}>
  289. <strong>{`${key}:`}</strong>
  290. &nbsp;
  291. {index === goupByEntries.length - 1 ? formattedValue : `${formattedValue}, `}
  292. </span>
  293. );
  294. })}
  295. </Fragment>
  296. );
  297. }
  298. function SortableHeaderCell({
  299. sortState,
  300. name,
  301. right,
  302. children,
  303. onClick,
  304. }: {
  305. children: React.ReactNode;
  306. name: SortState['name'];
  307. onClick: (name: SortState['name']) => void;
  308. sortState: SortState;
  309. right?: boolean;
  310. }) {
  311. const sortIcon =
  312. sortState.name === name ? (
  313. <IconArrow size="xs" direction={sortState.order === 'asc' ? 'up' : 'down'} />
  314. ) : (
  315. ''
  316. );
  317. if (right) {
  318. return (
  319. <HeaderCell
  320. onClick={() => {
  321. onClick(name);
  322. }}
  323. right
  324. >
  325. {sortIcon} {children}
  326. </HeaderCell>
  327. );
  328. }
  329. return (
  330. <HeaderCell
  331. onClick={() => {
  332. onClick(name);
  333. }}
  334. >
  335. {children} {sortIcon}
  336. </HeaderCell>
  337. );
  338. }
  339. function getValues(seriesData: Series['data']) {
  340. if (!seriesData) {
  341. return {min: null, max: null, avg: null, sum: null};
  342. }
  343. const res = seriesData.reduce(
  344. (acc, {value}) => {
  345. if (value === null) {
  346. return acc;
  347. }
  348. acc.min = Math.min(acc.min, value);
  349. acc.max = Math.max(acc.max, value);
  350. acc.sum += value;
  351. acc.definedDatapoints += 1;
  352. return acc;
  353. },
  354. {min: Infinity, max: -Infinity, sum: 0, definedDatapoints: 0}
  355. );
  356. return {min: res.min, max: res.max, sum: res.sum, avg: res.sum / res.definedDatapoints};
  357. }
  358. const SummaryTableWrapper = styled(`div`)<{hasActions: boolean}>`
  359. display: grid;
  360. /* padding | color dot | name | avg | min | max | sum | actions | padding */
  361. grid-template-columns:
  362. ${space(0.75)} ${space(3)} 8fr repeat(${p => (p.hasActions ? 5 : 4)}, max-content)
  363. ${space(0.75)};
  364. max-height: 200px;
  365. overflow-x: hidden;
  366. overflow-y: auto;
  367. border: 1px solid ${p => p.theme.border};
  368. border-radius: ${p => p.theme.borderRadius};
  369. font-size: ${p => p.theme.fontSizeSmall};
  370. `;
  371. const TableBodyWrapper = styled(`div`)<{hasActions: boolean}>`
  372. display: contents;
  373. `;
  374. const HeaderCell = styled('div')<{disabled?: boolean; right?: boolean}>`
  375. display: flex;
  376. flex-direction: row;
  377. text-transform: uppercase;
  378. justify-content: ${p => (p.right ? 'flex-end' : 'flex-start')};
  379. align-items: center;
  380. gap: ${space(0.5)};
  381. padding: ${space(0.25)} ${space(0.75)};
  382. line-height: ${p => p.theme.text.lineHeightBody};
  383. font-weight: 600;
  384. font-family: ${p => p.theme.text.family};
  385. color: ${p => p.theme.subText};
  386. user-select: none;
  387. background-color: ${p => p.theme.backgroundSecondary};
  388. border-radius: 0;
  389. border-bottom: 1px solid ${p => p.theme.border};
  390. top: 0;
  391. position: sticky;
  392. z-index: 1;
  393. &:hover {
  394. cursor: ${p => (p.disabled ? 'default' : 'pointer')};
  395. }
  396. `;
  397. const Cell = styled('div')<{right?: boolean}>`
  398. display: flex;
  399. padding: ${space(0.25)} ${space(0.75)};
  400. align-items: center;
  401. justify-content: flex-start;
  402. white-space: nowrap;
  403. `;
  404. const NumberCell = styled(Cell)`
  405. justify-content: flex-end;
  406. font-variant-numeric: tabular-nums;
  407. `;
  408. const CenterCell = styled(Cell)`
  409. justify-content: center;
  410. `;
  411. const TextOverflowCell = styled(Cell)`
  412. min-width: 0;
  413. `;
  414. const ColorDot = styled(`div`)<{color: string; isHidden: boolean}>`
  415. border: 1px solid ${p => p.color};
  416. border-radius: 50%;
  417. width: ${space(1)};
  418. height: ${space(1)};
  419. `;
  420. const PaddingCell = styled(Cell)`
  421. padding: 0;
  422. `;
  423. const Row = styled('div')`
  424. display: contents;
  425. &:hover {
  426. cursor: pointer;
  427. ${Cell}, ${NumberCell}, ${CenterCell}, ${PaddingCell}, ${TextOverflowCell} {
  428. background-color: ${p => p.theme.bodyBackground};
  429. }
  430. }
  431. `;