summaryTable.tsx 10 KB

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