summaryTable.tsx 13 KB

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