summaryTable.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  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. setHoveredSeries,
  28. }: {
  29. onRowClick: (series: FocusedMetricsSeries) => void;
  30. onSortChange: (sortState: SortState) => void;
  31. series: Series[];
  32. onColorDotClick?: (series: FocusedMetricsSeries) => void;
  33. setHoveredSeries?: (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. <SortableHeaderCell onClick={changeSort} sortState={sort} name="name">
  132. {t('Name')}
  133. </SortableHeaderCell>
  134. <SortableHeaderCell onClick={changeSort} sortState={sort} name="avg" right>
  135. {t('Avg')}
  136. </SortableHeaderCell>
  137. <SortableHeaderCell onClick={changeSort} sortState={sort} name="min" right>
  138. {t('Min')}
  139. </SortableHeaderCell>
  140. <SortableHeaderCell onClick={changeSort} sortState={sort} name="max" right>
  141. {t('Max')}
  142. </SortableHeaderCell>
  143. <SortableHeaderCell onClick={changeSort} sortState={sort} name="sum" right>
  144. {t('Sum')}
  145. </SortableHeaderCell>
  146. {hasActions && (
  147. <HeaderCell disabled right>
  148. {t('Actions')}
  149. </HeaderCell>
  150. )}
  151. <TableBodyWrapper
  152. onMouseLeave={() => {
  153. if (hasMultipleSeries) {
  154. setHoveredSeries?.('');
  155. }
  156. }}
  157. >
  158. {rows.map(
  159. ({
  160. seriesName,
  161. id,
  162. groupBy,
  163. color,
  164. hidden,
  165. unit,
  166. operation,
  167. transaction,
  168. release,
  169. avg,
  170. min,
  171. max,
  172. sum,
  173. }) => {
  174. return (
  175. <Fragment key={id}>
  176. <CellWrapper
  177. onClick={() => {
  178. if (hasMultipleSeries) {
  179. onRowClick({
  180. id,
  181. groupBy,
  182. });
  183. }
  184. }}
  185. onMouseEnter={() => {
  186. if (hasMultipleSeries) {
  187. setHoveredSeries?.(id);
  188. }
  189. }}
  190. >
  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. <Cell right>{formatMetricsUsingUnitAndOp(avg, unit, operation)}</Cell>
  223. <Cell right>{formatMetricsUsingUnitAndOp(min, unit, operation)}</Cell>
  224. <Cell right>{formatMetricsUsingUnitAndOp(max, unit, operation)}</Cell>
  225. <Cell right>{formatMetricsUsingUnitAndOp(sum, unit, operation)}</Cell>
  226. </CellWrapper>
  227. {hasActions && (
  228. <Cell right>
  229. <ButtonBar gap={0.5}>
  230. {transaction && (
  231. <div>
  232. <Tooltip title={t('Open Transaction Summary')}>
  233. <LinkButton to={transactionTo(transaction)} size="xs">
  234. <IconLightning size="xs" />
  235. </LinkButton>
  236. </Tooltip>
  237. </div>
  238. )}
  239. {release && (
  240. <div>
  241. <Tooltip title={t('Open Release Details')}>
  242. <LinkButton to={releaseTo(release)} size="xs">
  243. <IconReleases size="xs" />
  244. </LinkButton>
  245. </Tooltip>
  246. </div>
  247. )}
  248. </ButtonBar>
  249. </Cell>
  250. )}
  251. </Fragment>
  252. );
  253. }
  254. )}
  255. </TableBodyWrapper>
  256. </SummaryTableWrapper>
  257. );
  258. });
  259. function FullSeriesName({
  260. seriesName,
  261. groupBy,
  262. }: {
  263. seriesName: string;
  264. groupBy?: Record<string, string>;
  265. }) {
  266. if (!groupBy || Object.keys(groupBy).length === 0) {
  267. return <Fragment>{seriesName}</Fragment>;
  268. }
  269. const goupByEntries = Object.entries(groupBy);
  270. return (
  271. <Fragment>
  272. {goupByEntries.map(([key, value], index) => {
  273. const formattedValue = value || t('(none)');
  274. return (
  275. <span key={key}>
  276. <strong>{`${key}:`}</strong>
  277. &nbsp;
  278. {index === goupByEntries.length - 1 ? formattedValue : `${formattedValue}, `}
  279. </span>
  280. );
  281. })}
  282. </Fragment>
  283. );
  284. }
  285. function SortableHeaderCell({
  286. sortState,
  287. name,
  288. right,
  289. children,
  290. onClick,
  291. }: {
  292. children: React.ReactNode;
  293. name: SortState['name'];
  294. onClick: (name: SortState['name']) => void;
  295. sortState: SortState;
  296. right?: boolean;
  297. }) {
  298. const sortIcon =
  299. sortState.name === name ? (
  300. <IconArrow size="xs" direction={sortState.order === 'asc' ? 'up' : 'down'} />
  301. ) : (
  302. ''
  303. );
  304. return (
  305. <HeaderCell
  306. onClick={() => {
  307. onClick(name);
  308. }}
  309. right={right}
  310. >
  311. {sortIcon} {children}
  312. </HeaderCell>
  313. );
  314. }
  315. function getValues(seriesData: Series['data']) {
  316. if (!seriesData) {
  317. return {min: null, max: null, avg: null, sum: null};
  318. }
  319. const res = seriesData.reduce(
  320. (acc, {value}) => {
  321. if (value === null) {
  322. return acc;
  323. }
  324. acc.min = Math.min(acc.min, value);
  325. acc.max = Math.max(acc.max, value);
  326. acc.sum += value;
  327. acc.definedDatapoints += 1;
  328. return acc;
  329. },
  330. {min: Infinity, max: -Infinity, sum: 0, definedDatapoints: 0}
  331. );
  332. return {min: res.min, max: res.max, sum: res.sum, avg: res.sum / res.definedDatapoints};
  333. }
  334. // TODO(ddm): PanelTable component proved to be a bit too opinionated for this use case,
  335. // so we're using a custom styled component instead. Figure out what we want to do here
  336. const SummaryTableWrapper = styled(`div`)<{hasActions: boolean}>`
  337. display: grid;
  338. grid-template-columns: ${p =>
  339. p.hasActions ? '24px 8fr repeat(5, 1fr)' : '24px 8fr repeat(4, 1fr)'};
  340. max-height: 200px;
  341. overflow-y: auto;
  342. scrollbar-gutter: stable;
  343. `;
  344. // TODO(ddm): This is a copy of PanelTableHeader, try to figure out how to reuse it
  345. const HeaderCell = styled('div')<{disabled?: boolean; right?: boolean}>`
  346. color: ${p => p.theme.subText};
  347. font-size: ${p => p.theme.fontSizeSmall};
  348. font-weight: 600;
  349. text-transform: uppercase;
  350. border-radius: ${p => p.theme.borderRadius} ${p => p.theme.borderRadius} 0 0;
  351. line-height: 1;
  352. display: flex;
  353. flex-direction: row;
  354. justify-content: ${p => (p.right ? 'flex-end' : 'flex-start')};
  355. padding: ${space(0.5)} ${space(1)};
  356. gap: ${space(0.5)};
  357. user-select: none;
  358. :hover {
  359. cursor: ${p => (p.disabled ? 'auto' : 'pointer')};
  360. background-color: ${p => (p.disabled ? p.theme.background : p.theme.bodyBackground)};
  361. }
  362. `;
  363. const Cell = styled('div')<{right?: boolean}>`
  364. display: flex;
  365. padding: ${space(0.25)} ${space(1)};
  366. align-items: center;
  367. justify-content: ${p => (p.right ? 'flex-end' : 'flex-start')};
  368. white-space: nowrap;
  369. `;
  370. const TextOverflowCell = styled(Cell)`
  371. min-width: 0;
  372. `;
  373. const ColorDot = styled(`div`)<{color: string; isHidden: boolean}>`
  374. border: 1px solid ${p => p.color};
  375. border-radius: 50%;
  376. width: ${space(1)};
  377. height: ${space(1)};
  378. `;
  379. const TableBodyWrapper = styled('div')`
  380. display: contents;
  381. `;
  382. const CellWrapper = styled('div')`
  383. display: contents;
  384. &:hover {
  385. cursor: pointer;
  386. ${Cell}, ${TextOverflowCell} {
  387. background-color: ${p => p.theme.bodyBackground};
  388. }
  389. }
  390. `;