summaryTable.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  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. <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. <CenterCell>
  235. <ButtonBar gap={0.5}>
  236. {transaction && (
  237. <div>
  238. <Tooltip title={t('Open Transaction Summary')}>
  239. <LinkButton
  240. to={transactionTo(transaction)}
  241. size="zero"
  242. borderless
  243. >
  244. <IconLightning size="sm" />
  245. </LinkButton>
  246. </Tooltip>
  247. </div>
  248. )}
  249. {release && (
  250. <div>
  251. <Tooltip title={t('Open Release Details')}>
  252. <LinkButton to={releaseTo(release)} size="zero" borderless>
  253. <IconReleases size="sm" />
  254. </LinkButton>
  255. </Tooltip>
  256. </div>
  257. )}
  258. </ButtonBar>
  259. </CenterCell>
  260. <PaddingCell />
  261. </Row>
  262. </Fragment>
  263. );
  264. }
  265. )}
  266. </TableBodyWrapper>
  267. </SummaryTableWrapper>
  268. );
  269. });
  270. function FullSeriesName({
  271. seriesName,
  272. groupBy,
  273. }: {
  274. seriesName: string;
  275. groupBy?: Record<string, string>;
  276. }) {
  277. if (!groupBy || Object.keys(groupBy).length === 0) {
  278. return <Fragment>{seriesName}</Fragment>;
  279. }
  280. const goupByEntries = Object.entries(groupBy);
  281. return (
  282. <Fragment>
  283. {goupByEntries.map(([key, value], index) => {
  284. const formattedValue = value || t('(none)');
  285. return (
  286. <span key={key}>
  287. <strong>{`${key}:`}</strong>
  288. &nbsp;
  289. {index === goupByEntries.length - 1 ? formattedValue : `${formattedValue}, `}
  290. </span>
  291. );
  292. })}
  293. </Fragment>
  294. );
  295. }
  296. function SortableHeaderCell({
  297. sortState,
  298. name,
  299. right,
  300. children,
  301. onClick,
  302. }: {
  303. children: React.ReactNode;
  304. name: SortState['name'];
  305. onClick: (name: SortState['name']) => void;
  306. sortState: SortState;
  307. right?: boolean;
  308. }) {
  309. const sortIcon =
  310. sortState.name === name ? (
  311. <IconArrow size="xs" direction={sortState.order === 'asc' ? 'up' : 'down'} />
  312. ) : (
  313. ''
  314. );
  315. if (right) {
  316. return (
  317. <HeaderCell
  318. onClick={() => {
  319. onClick(name);
  320. }}
  321. right
  322. >
  323. {sortIcon} {children}
  324. </HeaderCell>
  325. );
  326. }
  327. return (
  328. <HeaderCell
  329. onClick={() => {
  330. onClick(name);
  331. }}
  332. >
  333. {children} {sortIcon}
  334. </HeaderCell>
  335. );
  336. }
  337. function getValues(seriesData: Series['data']) {
  338. if (!seriesData) {
  339. return {min: null, max: null, avg: null, sum: null};
  340. }
  341. const res = seriesData.reduce(
  342. (acc, {value}) => {
  343. if (value === null) {
  344. return acc;
  345. }
  346. acc.min = Math.min(acc.min, value);
  347. acc.max = Math.max(acc.max, value);
  348. acc.sum += value;
  349. acc.definedDatapoints += 1;
  350. return acc;
  351. },
  352. {min: Infinity, max: -Infinity, sum: 0, definedDatapoints: 0}
  353. );
  354. return {min: res.min, max: res.max, sum: res.sum, avg: res.sum / res.definedDatapoints};
  355. }
  356. const SummaryTableWrapper = styled(`div`)<{hasActions: boolean}>`
  357. display: grid;
  358. /* padding | color dot | name | avg | min | max | sum | actions | padding */
  359. grid-template-columns: ${space(0.75)} ${space(3)} 8fr repeat(5, max-content) ${space(
  360. 0.75
  361. )};
  362. max-height: 200px;
  363. overflow-x: hidden;
  364. overflow-y: auto;
  365. border: 1px solid ${p => p.theme.border};
  366. border-radius: ${p => p.theme.borderRadius};
  367. font-size: ${p => p.theme.fontSizeSmall};
  368. `;
  369. const TableBodyWrapper = styled(`div`)<{hasActions: boolean}>`
  370. display: contents;
  371. `;
  372. const HeaderCell = styled('div')<{disabled?: boolean; right?: boolean}>`
  373. display: flex;
  374. flex-direction: row;
  375. text-transform: uppercase;
  376. justify-content: ${p => (p.right ? 'flex-end' : 'flex-start')};
  377. align-items: center;
  378. gap: ${space(0.5)};
  379. padding: ${space(0.25)} ${space(0.75)};
  380. line-height: ${p => p.theme.text.lineHeightBody};
  381. font-weight: 600;
  382. font-family: ${p => p.theme.text.family};
  383. color: ${p => p.theme.subText};
  384. user-select: none;
  385. background-color: ${p => p.theme.backgroundSecondary};
  386. border-radius: 0;
  387. border-bottom: 1px solid ${p => p.theme.border};
  388. &:hover {
  389. cursor: ${p => (p.disabled ? 'default' : 'pointer')};
  390. }
  391. `;
  392. const Cell = styled('div')<{right?: boolean}>`
  393. display: flex;
  394. padding: ${space(0.25)} ${space(0.75)};
  395. align-items: center;
  396. justify-content: flex-start;
  397. white-space: nowrap;
  398. `;
  399. const NumberCell = styled(Cell)`
  400. justify-content: flex-end;
  401. font-variant-numeric: tabular-nums;
  402. `;
  403. const CenterCell = styled(Cell)`
  404. justify-content: center;
  405. `;
  406. const TextOverflowCell = styled(Cell)`
  407. min-width: 0;
  408. `;
  409. const ColorDot = styled(`div`)<{color: string; isHidden: boolean}>`
  410. border: 1px solid ${p => p.color};
  411. border-radius: 50%;
  412. width: ${space(1)};
  413. height: ${space(1)};
  414. `;
  415. const PaddingCell = styled(Cell)`
  416. padding: 0;
  417. `;
  418. const Row = styled('div')`
  419. display: contents;
  420. &:hover {
  421. cursor: pointer;
  422. ${Cell}, ${NumberCell}, ${CenterCell}, ${PaddingCell}, ${TextOverflowCell} {
  423. background-color: ${p => p.theme.bodyBackground};
  424. }
  425. }
  426. `;