summaryTable.tsx 11 KB

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