pageSamplePerformanceTable.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. import {useMemo} from 'react';
  2. import {Link} from 'react-router';
  3. import styled from '@emotion/styled';
  4. import ProjectAvatar from 'sentry/components/avatar/projectAvatar';
  5. import {Button, LinkButton} from 'sentry/components/button';
  6. import ButtonBar from 'sentry/components/buttonBar';
  7. import SearchBar from 'sentry/components/events/searchBar';
  8. import type {GridColumnHeader, GridColumnOrder} from 'sentry/components/gridEditable';
  9. import GridEditable, {COL_WIDTH_UNDEFINED} from 'sentry/components/gridEditable';
  10. import SortLink from 'sentry/components/gridEditable/sortLink';
  11. import ExternalLink from 'sentry/components/links/externalLink';
  12. import Pagination from 'sentry/components/pagination';
  13. import {Tooltip} from 'sentry/components/tooltip';
  14. import {IconChevron, IconPlay, IconProfiling} from 'sentry/icons';
  15. import {t} from 'sentry/locale';
  16. import {space} from 'sentry/styles/space';
  17. import {defined} from 'sentry/utils';
  18. import type {Sort} from 'sentry/utils/discover/fields';
  19. import {generateEventSlug} from 'sentry/utils/discover/urls';
  20. import {getShortEventId} from 'sentry/utils/events';
  21. import {getDuration} from 'sentry/utils/formatters';
  22. import {getTransactionDetailsUrl} from 'sentry/utils/performance/urls';
  23. import {generateProfileFlamechartRoute} from 'sentry/utils/profiling/routes';
  24. import {decodeScalar} from 'sentry/utils/queryString';
  25. import {useLocation} from 'sentry/utils/useLocation';
  26. import useOrganization from 'sentry/utils/useOrganization';
  27. import useProjects from 'sentry/utils/useProjects';
  28. import useRouter from 'sentry/utils/useRouter';
  29. import {useRoutes} from 'sentry/utils/useRoutes';
  30. import {PerformanceBadge} from 'sentry/views/performance/browser/webVitals/components/performanceBadge';
  31. import {useTransactionSamplesWebVitalsQuery} from 'sentry/views/performance/browser/webVitals/utils/queries/useTransactionSamplesWebVitalsQuery';
  32. import type {TransactionSampleRowWithScore} from 'sentry/views/performance/browser/webVitals/utils/types';
  33. import {
  34. DEFAULT_INDEXED_SORT,
  35. SORTABLE_INDEXED_FIELDS,
  36. SORTABLE_INDEXED_SCORE_FIELDS,
  37. } from 'sentry/views/performance/browser/webVitals/utils/types';
  38. import {useStoredScoresSetting} from 'sentry/views/performance/browser/webVitals/utils/useStoredScoresSetting';
  39. import {useWebVitalsSort} from 'sentry/views/performance/browser/webVitals/utils/useWebVitalsSort';
  40. import {generateReplayLink} from 'sentry/views/performance/transactionSummary/utils';
  41. type Column = GridColumnHeader<keyof TransactionSampleRowWithScore>;
  42. export const COLUMN_ORDER: GridColumnOrder<keyof TransactionSampleRowWithScore>[] = [
  43. {key: 'user.display', width: COL_WIDTH_UNDEFINED, name: 'User'},
  44. {key: 'transaction.duration', width: COL_WIDTH_UNDEFINED, name: 'Duration'},
  45. {key: 'measurements.lcp', width: COL_WIDTH_UNDEFINED, name: 'LCP'},
  46. {key: 'measurements.fcp', width: COL_WIDTH_UNDEFINED, name: 'FCP'},
  47. {key: 'measurements.fid', width: COL_WIDTH_UNDEFINED, name: 'FID'},
  48. {key: 'measurements.cls', width: COL_WIDTH_UNDEFINED, name: 'CLS'},
  49. {key: 'measurements.ttfb', width: COL_WIDTH_UNDEFINED, name: 'TTFB'},
  50. {key: 'totalScore', width: COL_WIDTH_UNDEFINED, name: 'Score'},
  51. ];
  52. type Props = {
  53. transaction: string;
  54. columnOrder?: GridColumnOrder<keyof TransactionSampleRowWithScore>[];
  55. limit?: number;
  56. search?: string;
  57. };
  58. export function PageSamplePerformanceTable({
  59. transaction,
  60. columnOrder,
  61. search,
  62. limit = 9,
  63. }: Props) {
  64. const location = useLocation();
  65. const {projects} = useProjects();
  66. const organization = useOrganization();
  67. const routes = useRoutes();
  68. const router = useRouter();
  69. const shouldUseStoredScores = useStoredScoresSetting();
  70. const sortableFields = shouldUseStoredScores
  71. ? SORTABLE_INDEXED_FIELDS
  72. : SORTABLE_INDEXED_FIELDS.filter(
  73. field => !SORTABLE_INDEXED_SCORE_FIELDS.includes(field)
  74. );
  75. const sort = useWebVitalsSort({
  76. defaultSort: DEFAULT_INDEXED_SORT,
  77. sortableFields: sortableFields as unknown as string[],
  78. });
  79. const replayLinkGenerator = generateReplayLink(routes);
  80. const project = useMemo(
  81. () => projects.find(p => p.id === String(location.query.project)),
  82. [projects, location.query.project]
  83. );
  84. const query = decodeScalar(location.query.query);
  85. // Do 3 queries filtering on LCP to get a spread of good, meh, and poor events
  86. // We can't query by performance score yet, so we're using LCP as a best estimate
  87. const {
  88. data: tableData,
  89. isLoading,
  90. pageLinks,
  91. } = useTransactionSamplesWebVitalsQuery({
  92. limit,
  93. transaction,
  94. query: search,
  95. withProfiles: true,
  96. });
  97. const getFormattedDuration = (value: number) => {
  98. return getDuration(value, value < 1 ? 0 : 2, true);
  99. };
  100. function renderHeadCell(col: Column) {
  101. function generateSortLink() {
  102. const key = col.key === 'totalScore' ? 'measurements.score.total' : col.key;
  103. let newSortDirection: Sort['kind'] = 'desc';
  104. if (sort?.field === key) {
  105. if (sort.kind === 'desc') {
  106. newSortDirection = 'asc';
  107. }
  108. }
  109. const newSort = `${newSortDirection === 'desc' ? '-' : ''}${key}`;
  110. return {
  111. ...location,
  112. query: {...location.query, sort: newSort},
  113. };
  114. }
  115. const canSort = (sortableFields as ReadonlyArray<string>).includes(col.key);
  116. if (
  117. [
  118. 'measurements.fcp',
  119. 'measurements.lcp',
  120. 'measurements.ttfb',
  121. 'measurements.fid',
  122. 'measurements.cls',
  123. 'transaction.duration',
  124. ].includes(col.key)
  125. ) {
  126. if (canSort) {
  127. return (
  128. <SortLink
  129. align="right"
  130. title={col.name}
  131. direction={sort?.field === col.key ? sort.kind : undefined}
  132. canSort={canSort}
  133. generateSortLink={generateSortLink}
  134. />
  135. );
  136. }
  137. return (
  138. <AlignRight>
  139. <span>{col.name}</span>
  140. </AlignRight>
  141. );
  142. }
  143. if (col.key === 'totalScore') {
  144. return (
  145. <SortLink
  146. title={
  147. <AlignCenter>
  148. <StyledTooltip
  149. isHoverable
  150. title={
  151. <span>
  152. {t('The overall performance rating of this page.')}
  153. <br />
  154. <ExternalLink href="https://docs.sentry.io/product/performance/web-vitals/#performance-score">
  155. {t('How is this calculated?')}
  156. </ExternalLink>
  157. </span>
  158. }
  159. >
  160. <TooltipHeader>{t('Perf Score')}</TooltipHeader>
  161. </StyledTooltip>
  162. </AlignCenter>
  163. }
  164. direction={sort?.field === col.key ? sort.kind : undefined}
  165. canSort={canSort}
  166. generateSortLink={generateSortLink}
  167. align={undefined}
  168. />
  169. );
  170. }
  171. if (col.key === 'replayId' || col.key === 'profile.id') {
  172. return (
  173. <AlignCenter>
  174. <span>{col.name}</span>
  175. </AlignCenter>
  176. );
  177. }
  178. return <span>{col.name}</span>;
  179. }
  180. function renderBodyCell(col: Column, row: TransactionSampleRowWithScore) {
  181. const {key} = col;
  182. if (key === 'totalScore') {
  183. return (
  184. <AlignCenter>
  185. <PerformanceBadge score={row.totalScore} />
  186. </AlignCenter>
  187. );
  188. }
  189. if (key === 'transaction') {
  190. return (
  191. <NoOverflow>
  192. {project && (
  193. <StyledProjectAvatar
  194. project={project}
  195. direction="left"
  196. size={16}
  197. hasTooltip
  198. tooltip={project.slug}
  199. />
  200. )}
  201. <Link
  202. to={{...location, query: {...location.query, transaction: row.transaction}}}
  203. >
  204. {row.transaction}
  205. </Link>
  206. </NoOverflow>
  207. );
  208. }
  209. if (
  210. [
  211. 'measurements.fcp',
  212. 'measurements.lcp',
  213. 'measurements.ttfb',
  214. 'measurements.fid',
  215. 'transaction.duration',
  216. ].includes(key)
  217. ) {
  218. return (
  219. <AlignRight>
  220. {row[key] === undefined ? (
  221. <NoValue>{' \u2014 '}</NoValue>
  222. ) : (
  223. getFormattedDuration((row[key] as number) / 1000)
  224. )}
  225. </AlignRight>
  226. );
  227. }
  228. if (['measurements.cls', 'opportunity'].includes(key)) {
  229. return (
  230. <AlignRight>
  231. {row[key] === undefined ? (
  232. <NoValue>{' \u2014 '}</NoValue>
  233. ) : (
  234. Math.round((row[key] as number) * 100) / 100
  235. )}
  236. </AlignRight>
  237. );
  238. }
  239. if (key === 'profile.id') {
  240. const profileTarget =
  241. defined(row.projectSlug) && defined(row['profile.id'])
  242. ? generateProfileFlamechartRoute({
  243. orgSlug: organization.slug,
  244. projectSlug: row.projectSlug,
  245. profileId: String(row['profile.id']),
  246. })
  247. : null;
  248. return (
  249. <NoOverflow>
  250. <AlignCenter>
  251. {profileTarget && (
  252. <Tooltip title={t('View Profile')}>
  253. <LinkButton to={profileTarget} size="xs">
  254. <IconProfiling size="xs" />
  255. </LinkButton>
  256. </Tooltip>
  257. )}
  258. </AlignCenter>
  259. </NoOverflow>
  260. );
  261. }
  262. if (key === 'replayId') {
  263. const replayTarget =
  264. row['transaction.duration'] !== undefined &&
  265. replayLinkGenerator(
  266. organization,
  267. {
  268. replayId: row.replayId,
  269. id: row.id,
  270. 'transaction.duration': row['transaction.duration'],
  271. timestamp: row.timestamp,
  272. },
  273. undefined
  274. );
  275. return (
  276. <NoOverflow>
  277. <AlignCenter>
  278. {replayTarget && Object.keys(replayTarget).length > 0 && (
  279. <Tooltip title={t('View Replay')}>
  280. <LinkButton to={replayTarget} size="xs">
  281. <IconPlay size="xs" />
  282. </LinkButton>
  283. </Tooltip>
  284. )}
  285. </AlignCenter>
  286. </NoOverflow>
  287. );
  288. }
  289. if (key === 'id') {
  290. const eventSlug = generateEventSlug({...row, project: row.projectSlug});
  291. const eventTarget = getTransactionDetailsUrl(organization.slug, eventSlug);
  292. return (
  293. <NoOverflow>
  294. <Tooltip title={t('View Transaction')}>
  295. <Link to={eventTarget}>{getShortEventId(row.id)}</Link>
  296. </Tooltip>
  297. </NoOverflow>
  298. );
  299. }
  300. return <NoOverflow>{row[key]}</NoOverflow>;
  301. }
  302. return (
  303. <span>
  304. <SearchBarContainer>
  305. <StyledSearchBar
  306. query={query}
  307. organization={organization}
  308. onSearch={queryString =>
  309. router.replace({
  310. ...location,
  311. query: {...location.query, query: queryString},
  312. })
  313. }
  314. />
  315. <StyledPagination pageLinks={pageLinks} disabled={isLoading} size="md" />
  316. {/* The Pagination component disappears if pageLinks is not defined,
  317. which happens any time the table data is loading. So we render a
  318. disabled button bar if pageLinks is not defined to minimize ui shifting */}
  319. {!pageLinks && (
  320. <Wrapper>
  321. <ButtonBar merged>
  322. <Button
  323. icon={<IconChevron direction="left" />}
  324. disabled
  325. aria-label={t('Previous')}
  326. />
  327. <Button
  328. icon={<IconChevron direction="right" />}
  329. disabled
  330. aria-label={t('Next')}
  331. />
  332. </ButtonBar>
  333. </Wrapper>
  334. )}
  335. </SearchBarContainer>
  336. <GridContainer>
  337. <GridEditable
  338. isLoading={isLoading}
  339. columnOrder={columnOrder ?? COLUMN_ORDER}
  340. columnSortBy={[]}
  341. data={tableData}
  342. grid={{
  343. renderHeadCell,
  344. renderBodyCell,
  345. }}
  346. location={location}
  347. minimumColWidth={70}
  348. />
  349. </GridContainer>
  350. </span>
  351. );
  352. }
  353. const NoOverflow = styled('span')`
  354. overflow: hidden;
  355. text-overflow: ellipsis;
  356. white-space: nowrap;
  357. `;
  358. const AlignRight = styled('span')<{color?: string}>`
  359. text-align: right;
  360. width: 100%;
  361. ${p => (p.color ? `color: ${p.color};` : '')}
  362. `;
  363. const AlignCenter = styled('div')`
  364. display: block;
  365. margin: auto;
  366. text-align: center;
  367. width: 100%;
  368. `;
  369. const StyledProjectAvatar = styled(ProjectAvatar)`
  370. top: ${space(0.25)};
  371. position: relative;
  372. padding-right: ${space(1)};
  373. `;
  374. // Not pretty but we need to override gridEditable styles since the original
  375. // styles have too much padding for small spaces
  376. const GridContainer = styled('div')`
  377. margin-bottom: ${space(1)};
  378. th {
  379. padding: 0 ${space(1)};
  380. }
  381. th:first-child {
  382. padding-left: ${space(2)};
  383. }
  384. th:last-child {
  385. padding-right: ${space(2)};
  386. }
  387. td {
  388. padding: ${space(1)};
  389. }
  390. td:first-child {
  391. padding-right: ${space(1)};
  392. padding-left: ${space(2)};
  393. }
  394. `;
  395. const NoValue = styled('span')`
  396. color: ${p => p.theme.gray300};
  397. `;
  398. const SearchBarContainer = styled('div')`
  399. display: flex;
  400. margin-top: ${space(2)};
  401. margin-bottom: ${space(1)};
  402. gap: ${space(1)};
  403. `;
  404. const StyledSearchBar = styled(SearchBar)`
  405. flex-grow: 1;
  406. `;
  407. const StyledPagination = styled(Pagination)`
  408. margin: 0;
  409. `;
  410. const Wrapper = styled('div')`
  411. display: flex;
  412. align-items: center;
  413. justify-content: flex-end;
  414. margin: 0;
  415. `;
  416. const TooltipHeader = styled('span')`
  417. ${p => p.theme.tooltipUnderline()};
  418. `;
  419. const StyledTooltip = styled(Tooltip)`
  420. top: 1px;
  421. position: relative;
  422. `;