summaryTable.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  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/ddm/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. {hasActions && <HeaderCell disabled right />}
  165. <HeaderCell disabled />
  166. <TableBodyWrapper
  167. hasActions={hasActions}
  168. onMouseLeave={() => {
  169. if (hasMultipleSeries) {
  170. onRowHover?.('');
  171. }
  172. }}
  173. >
  174. {rows.map(
  175. ({
  176. seriesName,
  177. id,
  178. groupBy,
  179. color,
  180. hidden,
  181. unit,
  182. transaction,
  183. release,
  184. avg,
  185. min,
  186. max,
  187. sum,
  188. isEquationSeries,
  189. queryIndex,
  190. }) => {
  191. return (
  192. <Fragment key={id}>
  193. <Row
  194. onClick={() => {
  195. if (hasMultipleSeries) {
  196. onRowClick({
  197. id,
  198. groupBy,
  199. });
  200. }
  201. }}
  202. onMouseEnter={() => {
  203. if (hasMultipleSeries) {
  204. onRowHover?.(id);
  205. }
  206. }}
  207. >
  208. <PaddingCell />
  209. <Cell
  210. onClick={event => {
  211. event.stopPropagation();
  212. if (hasMultipleSeries) {
  213. onColorDotClick?.({
  214. id,
  215. groupBy,
  216. });
  217. }
  218. }}
  219. >
  220. <ColorDot
  221. color={color}
  222. isHidden={!!hidden}
  223. style={{
  224. backgroundColor: hidden
  225. ? 'transparent'
  226. : colorFn(color).alpha(1).string(),
  227. }}
  228. />
  229. </Cell>
  230. <TextOverflowCell>
  231. <Tooltip
  232. title={<FullSeriesName seriesName={seriesName} groupBy={groupBy} />}
  233. delay={500}
  234. overlayStyle={{maxWidth: '80vw'}}
  235. >
  236. <TextOverflow>{seriesName}</TextOverflow>
  237. </Tooltip>
  238. </TextOverflowCell>
  239. {/* TODO(ddm): Add a tooltip with the full value, don't add on click in case users want to copy the value */}
  240. <NumberCell>{formatMetricUsingUnit(avg, unit)}</NumberCell>
  241. <NumberCell>{formatMetricUsingUnit(min, unit)}</NumberCell>
  242. <NumberCell>{formatMetricUsingUnit(max, unit)}</NumberCell>
  243. <NumberCell>{formatMetricUsingUnit(sum, unit)}</NumberCell>
  244. {hasActions && (
  245. <CenterCell>
  246. <ButtonBar gap={0.5}>
  247. {transaction && (
  248. <div>
  249. <Tooltip title={t('Open Transaction Summary')}>
  250. <LinkButton
  251. to={transactionTo(transaction)}
  252. size="zero"
  253. borderless
  254. >
  255. <IconLightning size="sm" />
  256. </LinkButton>
  257. </Tooltip>
  258. </div>
  259. )}
  260. {release && (
  261. <div>
  262. <Tooltip title={t('Open Release Details')}>
  263. <LinkButton to={releaseTo(release)} size="zero" borderless>
  264. <IconReleases size="sm" />
  265. </LinkButton>
  266. </Tooltip>
  267. </div>
  268. )}
  269. <Tooltip title={t('Add to Filter')} disabled={isEquationSeries}>
  270. <Button
  271. disabled={isEquationSeries}
  272. onClick={event => {
  273. event.stopPropagation();
  274. handleRowFilter(queryIndex, {
  275. id,
  276. groupBy,
  277. });
  278. }}
  279. size="zero"
  280. borderless
  281. >
  282. <IconFilter size="sm" />
  283. </Button>
  284. </Tooltip>
  285. </ButtonBar>
  286. </CenterCell>
  287. )}
  288. <PaddingCell />
  289. </Row>
  290. </Fragment>
  291. );
  292. }
  293. )}
  294. </TableBodyWrapper>
  295. </SummaryTableWrapper>
  296. );
  297. });
  298. function FullSeriesName({
  299. seriesName,
  300. groupBy,
  301. }: {
  302. seriesName: string;
  303. groupBy?: Record<string, string>;
  304. }) {
  305. if (!groupBy || Object.keys(groupBy).length === 0) {
  306. return <Fragment>{seriesName}</Fragment>;
  307. }
  308. const goupByEntries = Object.entries(groupBy);
  309. return (
  310. <Fragment>
  311. {goupByEntries.map(([key, value], index) => {
  312. const formattedValue = value || t('(none)');
  313. return (
  314. <span key={key}>
  315. <strong>{`${key}:`}</strong>
  316. &nbsp;
  317. {index === goupByEntries.length - 1 ? formattedValue : `${formattedValue}, `}
  318. </span>
  319. );
  320. })}
  321. </Fragment>
  322. );
  323. }
  324. function SortableHeaderCell({
  325. sortState,
  326. name,
  327. right,
  328. children,
  329. onClick,
  330. }: {
  331. children: React.ReactNode;
  332. name: SortState['name'];
  333. onClick: (name: SortState['name']) => void;
  334. sortState: SortState;
  335. right?: boolean;
  336. }) {
  337. const sortIcon =
  338. sortState.name === name ? (
  339. <IconArrow size="xs" direction={sortState.order === 'asc' ? 'up' : 'down'} />
  340. ) : (
  341. ''
  342. );
  343. if (right) {
  344. return (
  345. <HeaderCell
  346. onClick={() => {
  347. onClick(name);
  348. }}
  349. right
  350. >
  351. {sortIcon} {children}
  352. </HeaderCell>
  353. );
  354. }
  355. return (
  356. <HeaderCell
  357. onClick={() => {
  358. onClick(name);
  359. }}
  360. >
  361. {children} {sortIcon}
  362. </HeaderCell>
  363. );
  364. }
  365. function getValues(seriesData: Series['data']) {
  366. if (!seriesData) {
  367. return {min: null, max: null, avg: null, sum: null};
  368. }
  369. const res = seriesData.reduce(
  370. (acc, {value}) => {
  371. if (value === null) {
  372. return acc;
  373. }
  374. acc.min = Math.min(acc.min, value);
  375. acc.max = Math.max(acc.max, value);
  376. acc.sum += value;
  377. acc.definedDatapoints += 1;
  378. return acc;
  379. },
  380. {min: Infinity, max: -Infinity, sum: 0, definedDatapoints: 0}
  381. );
  382. return {min: res.min, max: res.max, sum: res.sum, avg: res.sum / res.definedDatapoints};
  383. }
  384. const SummaryTableWrapper = styled(`div`)<{hasActions: boolean}>`
  385. display: grid;
  386. /* padding | color dot | name | avg | min | max | sum | actions | padding */
  387. grid-template-columns:
  388. ${space(0.75)} ${space(3)} 8fr repeat(${p => (p.hasActions ? 5 : 4)}, max-content)
  389. ${space(0.75)};
  390. max-height: 200px;
  391. overflow-x: hidden;
  392. overflow-y: auto;
  393. border: 1px solid ${p => p.theme.border};
  394. border-radius: ${p => p.theme.borderRadius};
  395. font-size: ${p => p.theme.fontSizeSmall};
  396. `;
  397. const TableBodyWrapper = styled(`div`)<{hasActions: boolean}>`
  398. display: contents;
  399. `;
  400. const HeaderCell = styled('div')<{disabled?: boolean; right?: boolean}>`
  401. display: flex;
  402. flex-direction: row;
  403. text-transform: uppercase;
  404. justify-content: ${p => (p.right ? 'flex-end' : 'flex-start')};
  405. align-items: center;
  406. gap: ${space(0.5)};
  407. padding: ${space(0.25)} ${space(0.75)};
  408. line-height: ${p => p.theme.text.lineHeightBody};
  409. font-weight: 600;
  410. font-family: ${p => p.theme.text.family};
  411. color: ${p => p.theme.subText};
  412. user-select: none;
  413. background-color: ${p => p.theme.backgroundSecondary};
  414. border-radius: 0;
  415. border-bottom: 1px solid ${p => p.theme.border};
  416. top: 0;
  417. position: sticky;
  418. z-index: 1;
  419. &:hover {
  420. cursor: ${p => (p.disabled ? 'default' : 'pointer')};
  421. }
  422. `;
  423. const Cell = styled('div')<{right?: boolean}>`
  424. display: flex;
  425. padding: ${space(0.25)} ${space(0.75)};
  426. align-items: center;
  427. justify-content: flex-start;
  428. white-space: nowrap;
  429. `;
  430. const NumberCell = styled(Cell)`
  431. justify-content: flex-end;
  432. font-variant-numeric: tabular-nums;
  433. `;
  434. const CenterCell = styled(Cell)`
  435. justify-content: center;
  436. `;
  437. const TextOverflowCell = styled(Cell)`
  438. min-width: 0;
  439. `;
  440. const ColorDot = styled(`div`)<{color: string; isHidden: boolean}>`
  441. border: 1px solid ${p => p.color};
  442. border-radius: 50%;
  443. width: ${space(1)};
  444. height: ${space(1)};
  445. `;
  446. const PaddingCell = styled(Cell)`
  447. padding: 0;
  448. `;
  449. const Row = styled('div')`
  450. display: contents;
  451. &:hover {
  452. cursor: pointer;
  453. ${Cell}, ${NumberCell}, ${CenterCell}, ${PaddingCell}, ${TextOverflowCell} {
  454. background-color: ${p => p.theme.bodyBackground};
  455. }
  456. }
  457. `;