summaryTable.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  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 {Button, 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, IconFilter, 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 {formatMetricUsingUnit} 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/metrics/chart/types';
  20. import {transactionSummaryRouteWithQuery} from 'sentry/views/performance/transactionSummary/utils';
  21. export const SummaryTable = memo(function SummaryTable({
  22. series,
  23. onRowClick,
  24. onColorDotClick,
  25. onSortChange,
  26. sort = DEFAULT_SORT_STATE as SortState,
  27. onRowHover,
  28. onRowFilter,
  29. }: {
  30. onRowClick: (series: FocusedMetricsSeries) => void;
  31. onSortChange: (sortState: SortState) => void;
  32. series: Series[];
  33. onColorDotClick?: (series: FocusedMetricsSeries) => void;
  34. onRowFilter?: (index: number, series: FocusedMetricsSeries) => void;
  35. onRowHover?: (seriesName: string) => void;
  36. sort?: SortState;
  37. }) {
  38. const {selection} = usePageFilters();
  39. const organization = useOrganization();
  40. const canFilter = series.length > 1 && !!onRowFilter;
  41. const hasActions = series.some(s => s.release || s.transaction) || canFilter;
  42. const hasMultipleSeries = series.length > 1;
  43. const changeSort = useCallback(
  44. (name: SortState['name']) => {
  45. trackAnalytics('ddm.widget.sort', {
  46. organization,
  47. by: name ?? '(none)',
  48. order: sort.order,
  49. });
  50. Sentry.metrics.increment('ddm.widget.sort', 1, {
  51. tags: {
  52. by: name ?? '(none)',
  53. order: sort.order,
  54. },
  55. });
  56. if (sort.name === name) {
  57. if (sort.order === 'desc') {
  58. onSortChange(DEFAULT_SORT_STATE as SortState);
  59. } else if (sort.order === 'asc') {
  60. onSortChange({
  61. name,
  62. order: 'desc',
  63. });
  64. } else {
  65. onSortChange({
  66. name,
  67. order: 'asc',
  68. });
  69. }
  70. } else {
  71. onSortChange({
  72. name,
  73. order: 'asc',
  74. });
  75. }
  76. },
  77. [sort, onSortChange, organization]
  78. );
  79. const handleRowFilter = useCallback(
  80. (index: number | undefined, row: FocusedMetricsSeries) => {
  81. if (index === undefined) {
  82. return;
  83. }
  84. trackAnalytics('ddm.widget.add_row_filter', {
  85. organization,
  86. });
  87. onRowFilter?.(index, row);
  88. },
  89. [onRowFilter, organization]
  90. );
  91. const releaseTo = (release: string) => {
  92. return {
  93. pathname: `/organizations/${organization.slug}/releases/${encodeURIComponent(
  94. release
  95. )}/`,
  96. query: {
  97. pageStart: selection.datetime.start,
  98. pageEnd: selection.datetime.end,
  99. pageStatsPeriod: selection.datetime.period,
  100. project: selection.projects,
  101. environment: selection.environments,
  102. },
  103. };
  104. };
  105. const transactionTo = (transaction: string) =>
  106. transactionSummaryRouteWithQuery({
  107. orgSlug: organization.slug,
  108. transaction,
  109. projectID: selection.projects.map(p => String(p)),
  110. query: {
  111. query: '',
  112. environment: selection.environments,
  113. start: selection.datetime.start
  114. ? getUtcDateString(selection.datetime.start)
  115. : undefined,
  116. end: selection.datetime.end
  117. ? getUtcDateString(selection.datetime.end)
  118. : undefined,
  119. statsPeriod: selection.datetime.period,
  120. },
  121. });
  122. const rows = series
  123. .map(s => {
  124. return {
  125. ...s,
  126. ...getValues(s.data),
  127. };
  128. })
  129. // Filter series with no data
  130. .filter(s => s.min !== Infinity)
  131. .sort((a, b) => {
  132. const {name, order} = sort;
  133. if (!name) {
  134. return 0;
  135. }
  136. if (name === 'name') {
  137. return order === 'asc'
  138. ? a.seriesName.localeCompare(b.seriesName)
  139. : b.seriesName.localeCompare(a.seriesName);
  140. }
  141. const aValue = a[name] ?? 0;
  142. const bValue = b[name] ?? 0;
  143. return order === 'asc' ? aValue - bValue : bValue - aValue;
  144. });
  145. return (
  146. <SummaryTableWrapper hasActions={hasActions}>
  147. <HeaderCell disabled />
  148. <HeaderCell disabled />
  149. <SortableHeaderCell onClick={changeSort} sortState={sort} name="name">
  150. {t('Name')}
  151. </SortableHeaderCell>
  152. <SortableHeaderCell onClick={changeSort} sortState={sort} name="avg" right>
  153. {t('Avg')}
  154. </SortableHeaderCell>
  155. <SortableHeaderCell onClick={changeSort} sortState={sort} name="min" right>
  156. {t('Min')}
  157. </SortableHeaderCell>
  158. <SortableHeaderCell onClick={changeSort} sortState={sort} name="max" right>
  159. {t('Max')}
  160. </SortableHeaderCell>
  161. <SortableHeaderCell onClick={changeSort} sortState={sort} name="sum" right>
  162. {t('Sum')}
  163. </SortableHeaderCell>
  164. <SortableHeaderCell onClick={changeSort} sortState={sort} name="total" right>
  165. {t('Total')}
  166. </SortableHeaderCell>
  167. {hasActions && <HeaderCell disabled right />}
  168. <HeaderCell disabled />
  169. <TableBodyWrapper
  170. hasActions={hasActions}
  171. onMouseLeave={() => {
  172. if (hasMultipleSeries) {
  173. onRowHover?.('');
  174. }
  175. }}
  176. >
  177. {rows.map(
  178. ({
  179. seriesName,
  180. id,
  181. groupBy,
  182. color,
  183. hidden,
  184. unit,
  185. transaction,
  186. release,
  187. avg,
  188. min,
  189. max,
  190. sum,
  191. total,
  192. isEquationSeries,
  193. queryIndex,
  194. }) => {
  195. return (
  196. <Fragment key={id}>
  197. <Row
  198. onClick={() => {
  199. if (hasMultipleSeries) {
  200. onRowClick({
  201. id,
  202. groupBy,
  203. });
  204. }
  205. }}
  206. onMouseEnter={() => {
  207. if (hasMultipleSeries) {
  208. onRowHover?.(id);
  209. }
  210. }}
  211. >
  212. <PaddingCell />
  213. <Cell
  214. onClick={event => {
  215. event.stopPropagation();
  216. if (hasMultipleSeries) {
  217. onColorDotClick?.({
  218. id,
  219. groupBy,
  220. });
  221. }
  222. }}
  223. >
  224. <ColorDot
  225. color={color}
  226. isHidden={!!hidden}
  227. style={{
  228. backgroundColor: hidden
  229. ? 'transparent'
  230. : colorFn(color).alpha(1).string(),
  231. }}
  232. />
  233. </Cell>
  234. <TextOverflowCell>
  235. <Tooltip
  236. title={<FullSeriesName seriesName={seriesName} groupBy={groupBy} />}
  237. delay={500}
  238. overlayStyle={{maxWidth: '80vw'}}
  239. >
  240. <TextOverflow>{seriesName}</TextOverflow>
  241. </Tooltip>
  242. </TextOverflowCell>
  243. {/* TODO(ddm): Add a tooltip with the full value, don't add on click in case users want to copy the value */}
  244. <NumberCell>{formatMetricUsingUnit(avg, unit)}</NumberCell>
  245. <NumberCell>{formatMetricUsingUnit(min, unit)}</NumberCell>
  246. <NumberCell>{formatMetricUsingUnit(max, unit)}</NumberCell>
  247. <NumberCell>{formatMetricUsingUnit(sum, unit)}</NumberCell>
  248. <NumberCell>{formatMetricUsingUnit(total, unit)}</NumberCell>
  249. {hasActions && (
  250. <CenterCell>
  251. <ButtonBar gap={0.5}>
  252. {transaction && (
  253. <div>
  254. <Tooltip title={t('Open Transaction Summary')}>
  255. <LinkButton
  256. to={transactionTo(transaction)}
  257. size="zero"
  258. borderless
  259. >
  260. <IconLightning size="sm" />
  261. </LinkButton>
  262. </Tooltip>
  263. </div>
  264. )}
  265. {release && (
  266. <div>
  267. <Tooltip title={t('Open Release Details')}>
  268. <LinkButton to={releaseTo(release)} size="zero" borderless>
  269. <IconReleases size="sm" />
  270. </LinkButton>
  271. </Tooltip>
  272. </div>
  273. )}
  274. <Tooltip title={t('Add to Filter')} disabled={isEquationSeries}>
  275. <Button
  276. disabled={isEquationSeries}
  277. onClick={event => {
  278. event.stopPropagation();
  279. handleRowFilter(queryIndex, {
  280. id,
  281. groupBy,
  282. });
  283. }}
  284. size="zero"
  285. borderless
  286. >
  287. <IconFilter size="sm" />
  288. </Button>
  289. </Tooltip>
  290. </ButtonBar>
  291. </CenterCell>
  292. )}
  293. <PaddingCell />
  294. </Row>
  295. </Fragment>
  296. );
  297. }
  298. )}
  299. </TableBodyWrapper>
  300. </SummaryTableWrapper>
  301. );
  302. });
  303. function FullSeriesName({
  304. seriesName,
  305. groupBy,
  306. }: {
  307. seriesName: string;
  308. groupBy?: Record<string, string>;
  309. }) {
  310. if (!groupBy || Object.keys(groupBy).length === 0) {
  311. return <Fragment>{seriesName}</Fragment>;
  312. }
  313. const goupByEntries = Object.entries(groupBy);
  314. return (
  315. <Fragment>
  316. {goupByEntries.map(([key, value], index) => {
  317. const formattedValue = value || t('(none)');
  318. return (
  319. <span key={key}>
  320. <strong>{`${key}:`}</strong>
  321. &nbsp;
  322. {index === goupByEntries.length - 1 ? formattedValue : `${formattedValue}, `}
  323. </span>
  324. );
  325. })}
  326. </Fragment>
  327. );
  328. }
  329. function SortableHeaderCell({
  330. sortState,
  331. name,
  332. right,
  333. children,
  334. onClick,
  335. }: {
  336. children: React.ReactNode;
  337. name: SortState['name'];
  338. onClick: (name: SortState['name']) => void;
  339. sortState: SortState;
  340. right?: boolean;
  341. }) {
  342. const sortIcon =
  343. sortState.name === name ? (
  344. <IconArrow size="xs" direction={sortState.order === 'asc' ? 'up' : 'down'} />
  345. ) : (
  346. ''
  347. );
  348. if (right) {
  349. return (
  350. <HeaderCell
  351. onClick={() => {
  352. onClick(name);
  353. }}
  354. right
  355. >
  356. {sortIcon} {children}
  357. </HeaderCell>
  358. );
  359. }
  360. return (
  361. <HeaderCell
  362. onClick={() => {
  363. onClick(name);
  364. }}
  365. >
  366. {children} {sortIcon}
  367. </HeaderCell>
  368. );
  369. }
  370. function getValues(seriesData: Series['data']) {
  371. if (!seriesData) {
  372. return {min: null, max: null, avg: null, sum: null};
  373. }
  374. const res = seriesData.reduce(
  375. (acc, {value}) => {
  376. if (value === null) {
  377. return acc;
  378. }
  379. acc.min = Math.min(acc.min, value);
  380. acc.max = Math.max(acc.max, value);
  381. acc.sum += value;
  382. acc.definedDatapoints += 1;
  383. return acc;
  384. },
  385. {min: Infinity, max: -Infinity, sum: 0, definedDatapoints: 0}
  386. );
  387. return {min: res.min, max: res.max, sum: res.sum, avg: res.sum / res.definedDatapoints};
  388. }
  389. const SummaryTableWrapper = styled(`div`)<{hasActions: boolean}>`
  390. display: grid;
  391. /* padding | color dot | name | avg | min | max | sum | total | actions | padding */
  392. grid-template-columns:
  393. ${space(0.75)} ${space(3)} 8fr repeat(${p => (p.hasActions ? 6 : 5)}, max-content)
  394. ${space(0.75)};
  395. max-height: 200px;
  396. overflow-x: hidden;
  397. overflow-y: auto;
  398. border: 1px solid ${p => p.theme.border};
  399. border-radius: ${p => p.theme.borderRadius};
  400. font-size: ${p => p.theme.fontSizeSmall};
  401. `;
  402. const TableBodyWrapper = styled(`div`)<{hasActions: boolean}>`
  403. display: contents;
  404. `;
  405. const HeaderCell = styled('div')<{disabled?: boolean; right?: boolean}>`
  406. display: flex;
  407. flex-direction: row;
  408. text-transform: uppercase;
  409. justify-content: ${p => (p.right ? 'flex-end' : 'flex-start')};
  410. align-items: center;
  411. gap: ${space(0.5)};
  412. padding: ${space(0.25)} ${space(0.75)};
  413. line-height: ${p => p.theme.text.lineHeightBody};
  414. font-weight: 600;
  415. font-family: ${p => p.theme.text.family};
  416. color: ${p => p.theme.subText};
  417. user-select: none;
  418. background-color: ${p => p.theme.backgroundSecondary};
  419. border-radius: 0;
  420. border-bottom: 1px solid ${p => p.theme.border};
  421. top: 0;
  422. position: sticky;
  423. z-index: 1;
  424. &:hover {
  425. cursor: ${p => (p.disabled ? 'default' : 'pointer')};
  426. }
  427. `;
  428. const Cell = styled('div')<{right?: boolean}>`
  429. display: flex;
  430. padding: ${space(0.25)} ${space(0.75)};
  431. align-items: center;
  432. justify-content: flex-start;
  433. white-space: nowrap;
  434. `;
  435. const NumberCell = styled(Cell)`
  436. justify-content: flex-end;
  437. font-variant-numeric: tabular-nums;
  438. `;
  439. const CenterCell = styled(Cell)`
  440. justify-content: center;
  441. `;
  442. const TextOverflowCell = styled(Cell)`
  443. min-width: 0;
  444. `;
  445. const ColorDot = styled(`div`)<{color: string; isHidden: boolean}>`
  446. border: 1px solid ${p => p.color};
  447. border-radius: 50%;
  448. width: ${space(1)};
  449. height: ${space(1)};
  450. `;
  451. const PaddingCell = styled(Cell)`
  452. padding: 0;
  453. `;
  454. const Row = styled('div')`
  455. display: contents;
  456. &:hover {
  457. cursor: pointer;
  458. ${Cell}, ${NumberCell}, ${CenterCell}, ${PaddingCell}, ${TextOverflowCell} {
  459. background-color: ${p => p.theme.bodyBackground};
  460. }
  461. }
  462. `;