summaryTable.tsx 9.5 KB

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