summaryTable.tsx 12 KB

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