summaryTable.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  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 {Tooltip} from 'sentry/components/tooltip';
  8. import {IconArrow, IconLightning, IconReleases} from 'sentry/icons';
  9. import {t} from 'sentry/locale';
  10. import {space} from 'sentry/styles/space';
  11. import {trackAnalytics} from 'sentry/utils/analytics';
  12. import {getUtcDateString} from 'sentry/utils/dates';
  13. import {
  14. formatMetricsUsingUnitAndOp,
  15. MetricWidgetQueryParams,
  16. SortState,
  17. } from 'sentry/utils/metrics';
  18. import useOrganization from 'sentry/utils/useOrganization';
  19. import usePageFilters from 'sentry/utils/usePageFilters';
  20. import {DEFAULT_SORT_STATE} from 'sentry/views/ddm/constants';
  21. import {Series} from 'sentry/views/ddm/widget';
  22. import {transactionSummaryRouteWithQuery} from 'sentry/views/performance/transactionSummary/utils';
  23. export const SummaryTable = memo(function SummaryTable({
  24. series,
  25. operation,
  26. onRowClick,
  27. onSortChange,
  28. sort = DEFAULT_SORT_STATE as SortState,
  29. setHoveredSeries,
  30. }: {
  31. onRowClick: (series: MetricWidgetQueryParams['focusedSeries']) => void;
  32. onSortChange: (sortState: SortState) => void;
  33. series: Series[];
  34. operation?: string;
  35. setHoveredSeries?: (seriesName: string) => void;
  36. sort?: SortState;
  37. }) {
  38. const {selection} = usePageFilters();
  39. const organization = useOrganization();
  40. const hasActions = series.some(s => s.release || s.transaction);
  41. const hasMultipleSeries = series.length > 1;
  42. const changeSort = useCallback(
  43. (name: SortState['name']) => {
  44. trackAnalytics('ddm.widget.sort', {
  45. organization,
  46. by: name ?? '(none)',
  47. order: sort.order,
  48. });
  49. Sentry.metrics.increment('ddm.widget.sort', 1, {
  50. tags: {
  51. by: name ?? '(none)',
  52. order: sort.order,
  53. },
  54. });
  55. if (sort.name === name) {
  56. if (sort.order === 'desc') {
  57. onSortChange(DEFAULT_SORT_STATE as SortState);
  58. } else if (sort.order === 'asc') {
  59. onSortChange({
  60. name,
  61. order: 'desc',
  62. });
  63. } else {
  64. onSortChange({
  65. name,
  66. order: 'asc',
  67. });
  68. }
  69. } else {
  70. onSortChange({
  71. name,
  72. order: 'asc',
  73. });
  74. }
  75. },
  76. [sort, onSortChange, organization]
  77. );
  78. const releaseTo = (release: string) => {
  79. return {
  80. pathname: `/organizations/${organization.slug}/releases/${encodeURIComponent(
  81. release
  82. )}/`,
  83. query: {
  84. pageStart: selection.datetime.start,
  85. pageEnd: selection.datetime.end,
  86. pageStatsPeriod: selection.datetime.period,
  87. project: selection.projects,
  88. environment: selection.environments,
  89. },
  90. };
  91. };
  92. const transactionTo = (transaction: string) =>
  93. transactionSummaryRouteWithQuery({
  94. orgSlug: organization.slug,
  95. transaction,
  96. projectID: selection.projects.map(p => String(p)),
  97. query: {
  98. query: '',
  99. environment: selection.environments,
  100. start: selection.datetime.start
  101. ? getUtcDateString(selection.datetime.start)
  102. : undefined,
  103. end: selection.datetime.end
  104. ? getUtcDateString(selection.datetime.end)
  105. : undefined,
  106. statsPeriod: selection.datetime.period,
  107. },
  108. });
  109. const rows = series
  110. .map(s => {
  111. return {
  112. ...s,
  113. ...getValues(s.data),
  114. name: s.seriesName,
  115. };
  116. })
  117. .sort((a, b) => {
  118. const {name, order} = sort;
  119. if (!name) {
  120. return 0;
  121. }
  122. if (name === 'name') {
  123. return order === 'asc'
  124. ? a.name.localeCompare(b.name)
  125. : b.name.localeCompare(a.name);
  126. }
  127. const aValue = a[name] ?? 0;
  128. const bValue = b[name] ?? 0;
  129. return order === 'asc' ? aValue - bValue : bValue - aValue;
  130. });
  131. return (
  132. <SummaryTableWrapper hasActions={hasActions}>
  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 && (
  150. <HeaderCell disabled right>
  151. {t('Actions')}
  152. </HeaderCell>
  153. )}
  154. <TableBodyWrapper
  155. onMouseLeave={() => {
  156. if (hasMultipleSeries) {
  157. setHoveredSeries?.('');
  158. }
  159. }}
  160. >
  161. {rows.map(
  162. ({
  163. name,
  164. seriesName,
  165. groupBy,
  166. color,
  167. hidden,
  168. unit,
  169. transaction,
  170. release,
  171. avg,
  172. min,
  173. max,
  174. sum,
  175. }) => {
  176. return (
  177. <Fragment key={seriesName}>
  178. <CellWrapper
  179. onClick={() => {
  180. if (hasMultipleSeries) {
  181. onRowClick({
  182. seriesName,
  183. groupBy,
  184. });
  185. }
  186. }}
  187. onMouseEnter={() => {
  188. if (hasMultipleSeries) {
  189. setHoveredSeries?.(seriesName);
  190. }
  191. }}
  192. >
  193. <Cell>
  194. <ColorDot
  195. color={color}
  196. isHidden={!!hidden}
  197. style={{
  198. backgroundColor: hidden
  199. ? 'transparent'
  200. : colorFn(color).alpha(1).string(),
  201. }}
  202. />
  203. </Cell>
  204. <TextOverflowCell>{name}</TextOverflowCell>
  205. {/* TODO(ddm): Add a tooltip with the full value, don't add on click in case users want to copy the value */}
  206. <Cell right>{formatMetricsUsingUnitAndOp(avg, unit, operation)}</Cell>
  207. <Cell right>{formatMetricsUsingUnitAndOp(min, unit, operation)}</Cell>
  208. <Cell right>{formatMetricsUsingUnitAndOp(max, unit, operation)}</Cell>
  209. <Cell right>{formatMetricsUsingUnitAndOp(sum, unit, operation)}</Cell>
  210. </CellWrapper>
  211. {hasActions && (
  212. <Cell right>
  213. <ButtonBar gap={0.5}>
  214. {transaction && (
  215. <div>
  216. <Tooltip title={t('Open Transaction Summary')}>
  217. <LinkButton to={transactionTo(transaction)} size="xs">
  218. <IconLightning size="xs" />
  219. </LinkButton>
  220. </Tooltip>
  221. </div>
  222. )}
  223. {release && (
  224. <div>
  225. <Tooltip title={t('Open Release Details')}>
  226. <LinkButton to={releaseTo(release)} size="xs">
  227. <IconReleases size="xs" />
  228. </LinkButton>
  229. </Tooltip>
  230. </div>
  231. )}
  232. </ButtonBar>
  233. </Cell>
  234. )}
  235. </Fragment>
  236. );
  237. }
  238. )}
  239. </TableBodyWrapper>
  240. </SummaryTableWrapper>
  241. );
  242. });
  243. function SortableHeaderCell({
  244. sortState,
  245. name,
  246. right,
  247. children,
  248. onClick,
  249. }: {
  250. children: React.ReactNode;
  251. name: SortState['name'];
  252. onClick: (name: SortState['name']) => void;
  253. sortState: SortState;
  254. right?: boolean;
  255. }) {
  256. const sortIcon =
  257. sortState.name === name ? (
  258. <IconArrow size="xs" direction={sortState.order === 'asc' ? 'up' : 'down'} />
  259. ) : (
  260. ''
  261. );
  262. return (
  263. <HeaderCell
  264. onClick={() => {
  265. onClick(name);
  266. }}
  267. right={right}
  268. >
  269. {sortIcon} {children}
  270. </HeaderCell>
  271. );
  272. }
  273. function getValues(seriesData: Series['data']) {
  274. if (!seriesData) {
  275. return {min: null, max: null, avg: null, sum: null};
  276. }
  277. const res = seriesData.reduce(
  278. (acc, {value}) => {
  279. if (value === null) {
  280. return acc;
  281. }
  282. acc.min = Math.min(acc.min, value);
  283. acc.max = Math.max(acc.max, value);
  284. acc.sum += value;
  285. return acc;
  286. },
  287. {min: Infinity, max: -Infinity, sum: 0}
  288. );
  289. return {...res, avg: res.sum / seriesData.length};
  290. }
  291. // TODO(ddm): PanelTable component proved to be a bit too opinionated for this use case,
  292. // so we're using a custom styled component instead. Figure out what we want to do here
  293. const SummaryTableWrapper = styled(`div`)<{hasActions: boolean}>`
  294. display: grid;
  295. grid-template-columns: ${p =>
  296. p.hasActions ? '24px 8fr repeat(5, 1fr)' : '24px 8fr repeat(4, 1fr)'};
  297. max-height: 200px;
  298. overflow-y: auto;
  299. scrollbar-gutter: stable;
  300. `;
  301. // TODO(ddm): This is a copy of PanelTableHeader, try to figure out how to reuse it
  302. const HeaderCell = styled('div')<{disabled?: boolean; right?: boolean}>`
  303. color: ${p => p.theme.subText};
  304. font-size: ${p => p.theme.fontSizeSmall};
  305. font-weight: 600;
  306. text-transform: uppercase;
  307. border-radius: ${p => p.theme.borderRadius} ${p => p.theme.borderRadius} 0 0;
  308. line-height: 1;
  309. display: flex;
  310. flex-direction: row;
  311. justify-content: ${p => (p.right ? 'flex-end' : 'flex-start')};
  312. padding: ${space(0.5)} ${space(1)};
  313. gap: ${space(0.5)};
  314. user-select: none;
  315. :hover {
  316. cursor: ${p => (p.disabled ? 'auto' : 'pointer')};
  317. background-color: ${p => (p.disabled ? p.theme.background : p.theme.bodyBackground)};
  318. }
  319. `;
  320. const Cell = styled('div')<{right?: boolean}>`
  321. display: flex;
  322. padding: ${space(0.25)} ${space(1)};
  323. align-items: center;
  324. justify-content: ${p => (p.right ? 'flex-end' : 'flex-start')};
  325. `;
  326. const TextOverflowCell = styled(Cell)`
  327. overflow: hidden;
  328. text-overflow: ellipsis;
  329. white-space: nowrap;
  330. `;
  331. const ColorDot = styled(`div`)<{color: string; isHidden: boolean}>`
  332. border: 1px solid ${p => p.color};
  333. border-radius: 50%;
  334. width: ${space(1)};
  335. height: ${space(1)};
  336. `;
  337. const TableBodyWrapper = styled('div')`
  338. display: contents;
  339. `;
  340. const CellWrapper = styled('div')`
  341. display: contents;
  342. &:hover {
  343. cursor: pointer;
  344. ${Cell}, ${TextOverflowCell} {
  345. background-color: ${p => p.theme.bodyBackground};
  346. }
  347. }
  348. `;