summaryTable.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  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. <TableHeaderWrapper hasActions={hasActions}>
  131. <HeaderCell disabled />
  132. <HeaderCell disabled />
  133. <SortableHeaderCell onClick={changeSort} sortState={sort} name="name">
  134. {t('Name')}
  135. </SortableHeaderCell>
  136. <SortableHeaderCell onClick={changeSort} sortState={sort} name="avg" right>
  137. {t('Avg')}
  138. </SortableHeaderCell>
  139. <SortableHeaderCell onClick={changeSort} sortState={sort} name="min" right>
  140. {t('Min')}
  141. </SortableHeaderCell>
  142. <SortableHeaderCell onClick={changeSort} sortState={sort} name="max" right>
  143. {t('Max')}
  144. </SortableHeaderCell>
  145. <SortableHeaderCell onClick={changeSort} sortState={sort} name="sum" right>
  146. {t('Sum')}
  147. </SortableHeaderCell>
  148. {hasActions && <HeaderCell disabled right />}
  149. <HeaderCell disabled />
  150. </TableHeaderWrapper>
  151. <TableBodyWrapper
  152. hasActions={hasActions}
  153. onMouseLeave={() => {
  154. if (hasMultipleSeries) {
  155. onRowHover?.('');
  156. }
  157. }}
  158. >
  159. {rows.map(
  160. ({
  161. seriesName,
  162. id,
  163. groupBy,
  164. color,
  165. hidden,
  166. unit,
  167. operation,
  168. transaction,
  169. release,
  170. avg,
  171. min,
  172. max,
  173. sum,
  174. }) => {
  175. return (
  176. <Fragment key={id}>
  177. <Row
  178. onClick={() => {
  179. if (hasMultipleSeries) {
  180. onRowClick({
  181. id,
  182. groupBy,
  183. });
  184. }
  185. }}
  186. onMouseEnter={() => {
  187. if (hasMultipleSeries) {
  188. onRowHover?.(id);
  189. }
  190. }}
  191. >
  192. <PaddingCell />
  193. <Cell
  194. onClick={event => {
  195. event.stopPropagation();
  196. if (hasMultipleSeries) {
  197. onColorDotClick?.({
  198. id,
  199. groupBy,
  200. });
  201. }
  202. }}
  203. >
  204. <ColorDot
  205. color={color}
  206. isHidden={!!hidden}
  207. style={{
  208. backgroundColor: hidden
  209. ? 'transparent'
  210. : colorFn(color).alpha(1).string(),
  211. }}
  212. />
  213. </Cell>
  214. <TextOverflowCell>
  215. <Tooltip
  216. title={<FullSeriesName seriesName={seriesName} groupBy={groupBy} />}
  217. delay={500}
  218. overlayStyle={{maxWidth: '80vw'}}
  219. >
  220. <TextOverflow>{seriesName}</TextOverflow>
  221. </Tooltip>
  222. </TextOverflowCell>
  223. {/* TODO(ddm): Add a tooltip with the full value, don't add on click in case users want to copy the value */}
  224. <RightCell>
  225. {formatMetricsUsingUnitAndOp(avg, unit, operation)}
  226. </RightCell>
  227. <RightCell>
  228. {formatMetricsUsingUnitAndOp(min, unit, operation)}
  229. </RightCell>
  230. <RightCell>
  231. {formatMetricsUsingUnitAndOp(max, unit, operation)}
  232. </RightCell>
  233. <RightCell>
  234. {formatMetricsUsingUnitAndOp(sum, unit, operation)}
  235. </RightCell>
  236. {hasActions && (
  237. <CenterCell>
  238. <ButtonBar gap={0.5}>
  239. {transaction && (
  240. <div>
  241. <Tooltip title={t('Open Transaction Summary')}>
  242. <LinkButton
  243. to={transactionTo(transaction)}
  244. size="zero"
  245. borderless
  246. >
  247. <IconLightning size="sm" />
  248. </LinkButton>
  249. </Tooltip>
  250. </div>
  251. )}
  252. {release && (
  253. <div>
  254. <Tooltip title={t('Open Release Details')}>
  255. <LinkButton to={releaseTo(release)} size="zero" borderless>
  256. <IconReleases size="sm" />
  257. </LinkButton>
  258. </Tooltip>
  259. </div>
  260. )}
  261. </ButtonBar>
  262. </CenterCell>
  263. )}
  264. <PaddingCell />
  265. </Row>
  266. </Fragment>
  267. );
  268. }
  269. )}
  270. </TableBodyWrapper>
  271. </SummaryTableWrapper>
  272. );
  273. });
  274. function FullSeriesName({
  275. seriesName,
  276. groupBy,
  277. }: {
  278. seriesName: string;
  279. groupBy?: Record<string, string>;
  280. }) {
  281. if (!groupBy || Object.keys(groupBy).length === 0) {
  282. return <Fragment>{seriesName}</Fragment>;
  283. }
  284. const goupByEntries = Object.entries(groupBy);
  285. return (
  286. <Fragment>
  287. {goupByEntries.map(([key, value], index) => {
  288. const formattedValue = value || t('(none)');
  289. return (
  290. <span key={key}>
  291. <strong>{`${key}:`}</strong>
  292. &nbsp;
  293. {index === goupByEntries.length - 1 ? formattedValue : `${formattedValue}, `}
  294. </span>
  295. );
  296. })}
  297. </Fragment>
  298. );
  299. }
  300. function SortableHeaderCell({
  301. sortState,
  302. name,
  303. right,
  304. children,
  305. onClick,
  306. }: {
  307. children: React.ReactNode;
  308. name: SortState['name'];
  309. onClick: (name: SortState['name']) => void;
  310. sortState: SortState;
  311. right?: boolean;
  312. }) {
  313. const sortIcon =
  314. sortState.name === name ? (
  315. <IconArrow size="xs" direction={sortState.order === 'asc' ? 'up' : 'down'} />
  316. ) : (
  317. ''
  318. );
  319. if (right) {
  320. return (
  321. <HeaderCell
  322. onClick={() => {
  323. onClick(name);
  324. }}
  325. right
  326. >
  327. {sortIcon} {children}
  328. </HeaderCell>
  329. );
  330. }
  331. return (
  332. <HeaderCell
  333. onClick={() => {
  334. onClick(name);
  335. }}
  336. >
  337. {children} {sortIcon}
  338. </HeaderCell>
  339. );
  340. }
  341. function getValues(seriesData: Series['data']) {
  342. if (!seriesData) {
  343. return {min: null, max: null, avg: null, sum: null};
  344. }
  345. const res = seriesData.reduce(
  346. (acc, {value}) => {
  347. if (value === null) {
  348. return acc;
  349. }
  350. acc.min = Math.min(acc.min, value);
  351. acc.max = Math.max(acc.max, value);
  352. acc.sum += value;
  353. acc.definedDatapoints += 1;
  354. return acc;
  355. },
  356. {min: Infinity, max: -Infinity, sum: 0, definedDatapoints: 0}
  357. );
  358. return {min: res.min, max: res.max, sum: res.sum, avg: res.sum / res.definedDatapoints};
  359. }
  360. const SummaryTableWrapper = styled(`div`)<{hasActions: boolean}>`
  361. display: grid;
  362. grid-template-areas:
  363. 'header'
  364. 'body';
  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 gridColumns = ({hasActions}: {hasActions: boolean}) =>
  370. // padding | color dot | name | avg | min | max | sum | actions | padding
  371. hasActions
  372. ? `${space(0.75)} ${space(3)} 8fr repeat(4, 70px) 50px ${space(0.75)}`
  373. : `${space(0.75)} ${space(3)} 8fr repeat(4, 70px) ${space(0.75)}`;
  374. const TableHeaderWrapper = styled('div')<{hasActions: boolean}>`
  375. grid-area: header;
  376. position: sticky;
  377. top: 0;
  378. display: grid;
  379. grid-template-columns: ${p => gridColumns(p)};
  380. background-color: ${p => p.theme.backgroundSecondary};
  381. border-radius: ${p => p.theme.borderRadius} ${p => p.theme.borderRadius} 0 0;
  382. border-bottom: 1px solid ${p => p.theme.border};
  383. `;
  384. const TableBodyWrapper = styled('div')<{hasActions: boolean}>`
  385. grid-area: body;
  386. display: grid;
  387. grid-template-columns: ${p => gridColumns(p)};
  388. overflow-y: auto;
  389. scrollbar-gutter: stable;
  390. max-height: 180px;
  391. `;
  392. const HeaderCell = styled('div')<{disabled?: boolean; right?: boolean}>`
  393. font-weight: 600;
  394. color: ${p => p.theme.subText};
  395. text-transform: uppercase;
  396. border-left: 1px solid transparent;
  397. border-right: 1px solid transparent;
  398. line-height: ${p => p.theme.text.lineHeightBody};
  399. font-family: ${p => p.theme.text.family};
  400. display: flex;
  401. flex-direction: row;
  402. justify-content: ${p => (p.right ? 'flex-end' : 'flex-start')};
  403. padding: ${space(0.25)} ${space(0.75)};
  404. gap: ${space(0.5)};
  405. user-select: none;
  406. align-items: center;
  407. ${p =>
  408. !p.disabled &&
  409. `
  410. &:hover {
  411. cursor: pointer;
  412. border-left: 1px solid ${p.theme.border};
  413. border-right: 1px solid ${p.theme.border};
  414. `};
  415. `;
  416. const Cell = styled('div')<{right?: boolean}>`
  417. display: flex;
  418. padding: ${space(0.25)} ${space(0.75)};
  419. align-items: center;
  420. justify-content: flex-start;
  421. white-space: nowrap;
  422. `;
  423. const RightCell = styled(Cell)`
  424. justify-content: flex-end;
  425. `;
  426. const CenterCell = styled(Cell)`
  427. justify-content: center;
  428. `;
  429. const TextOverflowCell = styled(Cell)`
  430. min-width: 0;
  431. `;
  432. const ColorDot = styled(`div`)<{color: string; isHidden: boolean}>`
  433. border: 1px solid ${p => p.color};
  434. border-radius: 50%;
  435. width: ${space(1)};
  436. height: ${space(1)};
  437. `;
  438. const PaddingCell = styled(Cell)`
  439. padding: 0;
  440. `;
  441. const Row = styled('div')`
  442. display: contents;
  443. &:hover {
  444. cursor: pointer;
  445. ${Cell}, ${RightCell}, ${CenterCell}, ${PaddingCell}, ${TextOverflowCell} {
  446. background-color: ${p => p.theme.bodyBackground};
  447. }
  448. }
  449. `;