summaryTable.tsx 11 KB

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