summaryTable.tsx 11 KB

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