summaryTable.tsx 9.8 KB

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