summaryTable.tsx 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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, SortState} 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 {Series} from 'sentry/views/ddm/widget';
  18. import {transactionSummaryRouteWithQuery} from 'sentry/views/performance/transactionSummary/utils';
  19. export function SummaryTable({
  20. series,
  21. operation,
  22. onRowClick,
  23. onSortChange,
  24. sort = DEFAULT_SORT_STATE as SortState,
  25. setHoveredLegend,
  26. }: {
  27. onRowClick: (seriesName: string) => void;
  28. onSortChange: (sortState: SortState) => void;
  29. series: Series[];
  30. setHoveredLegend: React.Dispatch<React.SetStateAction<string>> | undefined;
  31. operation?: string;
  32. sort?: SortState;
  33. }) {
  34. const {selection} = usePageFilters();
  35. const organization = useOrganization();
  36. const hasActions = series.some(s => s.release || s.transaction);
  37. const router = useRouter();
  38. const {start, end, statsPeriod, project, environment} = router.location.query;
  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. if (sort.name === name) {
  48. if (sort.order === 'desc') {
  49. onSortChange(DEFAULT_SORT_STATE as SortState);
  50. } else if (sort.order === 'asc') {
  51. onSortChange({
  52. name,
  53. order: 'desc',
  54. });
  55. } else {
  56. onSortChange({
  57. name,
  58. order: 'asc',
  59. });
  60. }
  61. } else {
  62. onSortChange({
  63. name,
  64. order: 'asc',
  65. });
  66. }
  67. },
  68. [sort, onSortChange, organization]
  69. );
  70. const releaseTo = (release: string) => {
  71. return {
  72. pathname: `/organizations/${organization.slug}/releases/${encodeURIComponent(
  73. release
  74. )}/`,
  75. query: {
  76. pageStart: start,
  77. pageEnd: end,
  78. pageStatsPeriod: statsPeriod,
  79. project,
  80. environment,
  81. },
  82. };
  83. };
  84. const transactionTo = (transaction: string) =>
  85. transactionSummaryRouteWithQuery({
  86. orgSlug: organization.slug,
  87. transaction,
  88. projectID: selection.projects.map(p => String(p)),
  89. query: {
  90. query: '',
  91. environment: selection.environments,
  92. start: selection.datetime.start
  93. ? getUtcDateString(selection.datetime.start)
  94. : undefined,
  95. end: selection.datetime.end
  96. ? getUtcDateString(selection.datetime.end)
  97. : undefined,
  98. statsPeriod: selection.datetime.period,
  99. },
  100. });
  101. const rows = series
  102. .map(s => {
  103. return {
  104. ...s,
  105. ...getValues(s.data),
  106. name: s.seriesName,
  107. };
  108. })
  109. .sort((a, b) => {
  110. const {name, order} = sort;
  111. if (!name) {
  112. return 0;
  113. }
  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. `;