pageSamplePerformanceTable.tsx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  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 {SegmentedControl} from 'sentry/components/segmentedControl';
  14. import {Tooltip} from 'sentry/components/tooltip';
  15. import {IconChevron, IconPlay, IconProfiling} from 'sentry/icons';
  16. import {t} from 'sentry/locale';
  17. import {space} from 'sentry/styles/space';
  18. import {defined} from 'sentry/utils';
  19. import EventView from 'sentry/utils/discover/eventView';
  20. import type {Sort} from 'sentry/utils/discover/fields';
  21. import {
  22. generateEventSlug,
  23. generateLinkToEventInTraceView,
  24. } from 'sentry/utils/discover/urls';
  25. import {getShortEventId} from 'sentry/utils/events';
  26. import {getDuration} from 'sentry/utils/formatters';
  27. import {generateProfileFlamechartRoute} from 'sentry/utils/profiling/routes';
  28. import {decodeScalar} from 'sentry/utils/queryString';
  29. import useReplayExists from 'sentry/utils/replayCount/useReplayExists';
  30. import {MutableSearch} from 'sentry/utils/tokenizeSearch';
  31. import {useLocation} from 'sentry/utils/useLocation';
  32. import useOrganization from 'sentry/utils/useOrganization';
  33. import useProjects from 'sentry/utils/useProjects';
  34. import useRouter from 'sentry/utils/useRouter';
  35. import {useRoutes} from 'sentry/utils/useRoutes';
  36. import {PerformanceBadge} from 'sentry/views/performance/browser/webVitals/components/performanceBadge';
  37. import useProfileExists from 'sentry/views/performance/browser/webVitals/utils/profiling/useProfileExists';
  38. import {useInpSpanSamplesWebVitalsQuery} from 'sentry/views/performance/browser/webVitals/utils/queries/useInpSpanSamplesWebVitalsQuery';
  39. import {useTransactionSamplesWebVitalsQuery} from 'sentry/views/performance/browser/webVitals/utils/queries/useTransactionSamplesWebVitalsQuery';
  40. import type {
  41. InteractionSpanSampleRowWithScore,
  42. TransactionSampleRowWithScore,
  43. } from 'sentry/views/performance/browser/webVitals/utils/types';
  44. import {
  45. DEFAULT_INDEXED_SORT,
  46. SORTABLE_INDEXED_FIELDS,
  47. } from 'sentry/views/performance/browser/webVitals/utils/types';
  48. import {useWebVitalsSort} from 'sentry/views/performance/browser/webVitals/utils/useWebVitalsSort';
  49. import {generateReplayLink} from 'sentry/views/performance/transactionSummary/utils';
  50. import {SpanIndexedField} from 'sentry/views/starfish/types';
  51. type Column = GridColumnHeader<keyof TransactionSampleRowWithScore>;
  52. type InteractionsColumn = GridColumnHeader<keyof InteractionSpanSampleRowWithScore>;
  53. const PAGELOADS_COLUMN_ORDER: GridColumnOrder<keyof TransactionSampleRowWithScore>[] = [
  54. {key: 'id', width: COL_WIDTH_UNDEFINED, name: t('Event ID')},
  55. {key: 'user.display', width: COL_WIDTH_UNDEFINED, name: t('User')},
  56. {key: 'measurements.lcp', width: COL_WIDTH_UNDEFINED, name: 'LCP'},
  57. {key: 'measurements.fcp', width: COL_WIDTH_UNDEFINED, name: 'FCP'},
  58. {key: 'measurements.cls', width: COL_WIDTH_UNDEFINED, name: 'CLS'},
  59. {key: 'measurements.ttfb', width: COL_WIDTH_UNDEFINED, name: 'TTFB'},
  60. {key: 'profile.id', width: COL_WIDTH_UNDEFINED, name: t('Profile')},
  61. {key: 'replayId', width: COL_WIDTH_UNDEFINED, name: t('Replay')},
  62. {key: 'totalScore', width: COL_WIDTH_UNDEFINED, name: t('Score')},
  63. ];
  64. const INTERACTION_SAMPLES_COLUMN_ORDER: GridColumnOrder<
  65. keyof InteractionSpanSampleRowWithScore
  66. >[] = [
  67. {
  68. key: SpanIndexedField.SPAN_DESCRIPTION,
  69. width: COL_WIDTH_UNDEFINED,
  70. name: t('Interaction Target'),
  71. },
  72. {key: 'user.display', width: COL_WIDTH_UNDEFINED, name: t('User')},
  73. {key: SpanIndexedField.INP, width: COL_WIDTH_UNDEFINED, name: 'INP'},
  74. {key: 'profile.id', width: COL_WIDTH_UNDEFINED, name: t('Profile')},
  75. {key: 'replayId', width: COL_WIDTH_UNDEFINED, name: t('Replay')},
  76. {key: 'inpScore', width: COL_WIDTH_UNDEFINED, name: t('Score')},
  77. ];
  78. enum Datatype {
  79. PAGELOADS = 'pageloads',
  80. INTERACTIONS = 'interactions',
  81. }
  82. const DATATYPE_KEY = 'type';
  83. type Props = {
  84. transaction: string;
  85. limit?: number;
  86. search?: string;
  87. };
  88. export function PageSamplePerformanceTable({transaction, search, limit = 9}: Props) {
  89. const location = useLocation();
  90. const {projects} = useProjects();
  91. const organization = useOrganization();
  92. const {replayExists} = useReplayExists();
  93. const routes = useRoutes();
  94. const router = useRouter();
  95. let datatype = Datatype.PAGELOADS;
  96. switch (decodeScalar(location.query[DATATYPE_KEY], 'pageloads')) {
  97. case 'interactions':
  98. datatype = Datatype.INTERACTIONS;
  99. break;
  100. default:
  101. datatype = Datatype.PAGELOADS;
  102. }
  103. const sortableFields = SORTABLE_INDEXED_FIELDS;
  104. const sort = useWebVitalsSort({
  105. defaultSort: DEFAULT_INDEXED_SORT,
  106. sortableFields: sortableFields as unknown as string[],
  107. });
  108. const replayLinkGenerator = generateReplayLink(routes);
  109. const project = useMemo(
  110. () => projects.find(p => p.id === String(location.query.project)),
  111. [projects, location.query.project]
  112. );
  113. const query = decodeScalar(location.query.query);
  114. const {
  115. data: tableData,
  116. isLoading,
  117. pageLinks,
  118. } = useTransactionSamplesWebVitalsQuery({
  119. limit,
  120. transaction,
  121. query: search,
  122. withProfiles: true,
  123. enabled: datatype === Datatype.PAGELOADS,
  124. });
  125. const {
  126. data: interactionsTableData,
  127. isFetching: isInteractionsLoading,
  128. pageLinks: interactionsPageLinks,
  129. } = useInpSpanSamplesWebVitalsQuery({
  130. transaction,
  131. enabled: datatype === Datatype.INTERACTIONS,
  132. limit,
  133. filters: new MutableSearch(query ?? '').filters,
  134. });
  135. const {profileExists} = useProfileExists(
  136. interactionsTableData.filter(row => row['profile.id']).map(row => row['profile.id'])
  137. );
  138. const getFormattedDuration = (value: number) => {
  139. return getDuration(value, value < 1 ? 0 : 2, true);
  140. };
  141. function renderHeadCell(col: Column | InteractionsColumn) {
  142. function generateSortLink() {
  143. const key = col.key === 'inpScore' ? 'measurements.score.total' : col.key;
  144. let newSortDirection: Sort['kind'] = 'desc';
  145. if (sort?.field === key) {
  146. if (sort.kind === 'desc') {
  147. newSortDirection = 'asc';
  148. }
  149. }
  150. const newSort = `${newSortDirection === 'desc' ? '-' : ''}${key}`;
  151. return {
  152. ...location,
  153. query: {...location.query, sort: newSort},
  154. };
  155. }
  156. const canSort = (sortableFields as ReadonlyArray<string>).includes(col.key);
  157. if (
  158. [
  159. 'measurements.fcp',
  160. 'measurements.lcp',
  161. 'measurements.ttfb',
  162. 'measurements.fid',
  163. 'measurements.cls',
  164. 'measurements.inp',
  165. 'transaction.duration',
  166. ].includes(col.key)
  167. ) {
  168. if (canSort) {
  169. return (
  170. <SortLink
  171. align="right"
  172. title={col.name}
  173. direction={sort?.field === col.key ? sort.kind : undefined}
  174. canSort={canSort}
  175. generateSortLink={generateSortLink}
  176. />
  177. );
  178. }
  179. return (
  180. <AlignRight>
  181. <span>{col.name}</span>
  182. </AlignRight>
  183. );
  184. }
  185. if (col.key === 'totalScore' || col.key === 'inpScore') {
  186. return (
  187. <SortLink
  188. title={
  189. <AlignCenter>
  190. <StyledTooltip
  191. isHoverable
  192. title={
  193. <span>
  194. {t('The overall performance rating of this page.')}
  195. <br />
  196. <ExternalLink href="https://docs.sentry.io/product/performance/web-vitals/#performance-score">
  197. {t('How is this calculated?')}
  198. </ExternalLink>
  199. </span>
  200. }
  201. >
  202. <TooltipHeader>{t('Perf Score')}</TooltipHeader>
  203. </StyledTooltip>
  204. </AlignCenter>
  205. }
  206. direction={sort?.field === col.key ? sort.kind : undefined}
  207. canSort={canSort}
  208. generateSortLink={generateSortLink}
  209. align={undefined}
  210. />
  211. );
  212. }
  213. if (col.key === 'replayId' || col.key === 'profile.id') {
  214. return (
  215. <AlignCenter>
  216. <span>{col.name}</span>
  217. </AlignCenter>
  218. );
  219. }
  220. return <span>{col.name}</span>;
  221. }
  222. function renderBodyCell(
  223. col: Column | InteractionsColumn,
  224. row: TransactionSampleRowWithScore | InteractionSpanSampleRowWithScore
  225. ) {
  226. const {key} = col;
  227. if (key === 'totalScore' || key === 'inpScore') {
  228. return (
  229. <AlignCenter>
  230. <PerformanceBadge score={row[key]} />
  231. </AlignCenter>
  232. );
  233. }
  234. if (key === 'transaction' && 'transaction' in row) {
  235. return (
  236. <NoOverflow>
  237. {project && (
  238. <StyledProjectAvatar
  239. project={project}
  240. direction="left"
  241. size={16}
  242. hasTooltip
  243. tooltip={project.slug}
  244. />
  245. )}
  246. <Link
  247. to={{...location, query: {...location.query, transaction: row.transaction}}}
  248. >
  249. {row.transaction}
  250. </Link>
  251. </NoOverflow>
  252. );
  253. }
  254. if (
  255. [
  256. 'measurements.fcp',
  257. 'measurements.lcp',
  258. 'measurements.ttfb',
  259. 'measurements.fid',
  260. 'measurements.inp',
  261. 'transaction.duration',
  262. ].includes(key)
  263. ) {
  264. return (
  265. <AlignRight>
  266. {row[key] === undefined ? (
  267. <NoValue>{' \u2014 '}</NoValue>
  268. ) : (
  269. getFormattedDuration((row[key] as number) / 1000)
  270. )}
  271. </AlignRight>
  272. );
  273. }
  274. if (['measurements.cls', 'opportunity'].includes(key)) {
  275. return (
  276. <AlignRight>
  277. {row[key] === undefined ? (
  278. <NoValue>{' \u2014 '}</NoValue>
  279. ) : (
  280. Math.round((row[key] as number) * 100) / 100
  281. )}
  282. </AlignRight>
  283. );
  284. }
  285. if (key === 'profile.id') {
  286. const profileId = String(row[key]);
  287. const profileTarget =
  288. defined(row.projectSlug) && defined(row[key])
  289. ? generateProfileFlamechartRoute({
  290. orgSlug: organization.slug,
  291. projectSlug: row.projectSlug,
  292. profileId,
  293. })
  294. : null;
  295. return (
  296. <NoOverflow>
  297. <AlignCenter>
  298. {profileTarget && profileExists(profileId) && (
  299. <Tooltip title={t('View Profile')}>
  300. <LinkButton to={profileTarget} size="xs">
  301. <IconProfiling size="xs" />
  302. </LinkButton>
  303. </Tooltip>
  304. )}
  305. </AlignCenter>
  306. </NoOverflow>
  307. );
  308. }
  309. if (key === 'replayId') {
  310. const replayTarget =
  311. (row['transaction.duration'] !== undefined ||
  312. row[SpanIndexedField.SPAN_SELF_TIME] !== undefined) &&
  313. replayLinkGenerator(
  314. organization,
  315. {
  316. replayId: row[key],
  317. id: '', // id doesn't get used in replayLinkGenerator. This is just to satisfy the type.
  318. 'transaction.duration':
  319. datatype === Datatype.INTERACTIONS
  320. ? row[SpanIndexedField.SPAN_SELF_TIME]
  321. : row['transaction.duration'],
  322. timestamp: row.timestamp,
  323. },
  324. undefined
  325. );
  326. return (
  327. <NoOverflow>
  328. <AlignCenter>
  329. {replayTarget &&
  330. Object.keys(replayTarget).length > 0 &&
  331. replayExists(row[key]) && (
  332. <Tooltip title={t('View Replay')}>
  333. <LinkButton to={replayTarget} size="xs">
  334. <IconPlay size="xs" />
  335. </LinkButton>
  336. </Tooltip>
  337. )}
  338. </AlignCenter>
  339. </NoOverflow>
  340. );
  341. }
  342. if (key === 'id' && 'id' in row) {
  343. const eventTarget = generateLinkToEventInTraceView({
  344. eventSlug: generateEventSlug({...row, project: row.projectSlug}),
  345. dataRow: row,
  346. eventView: EventView.fromLocation(location),
  347. organization,
  348. location,
  349. });
  350. return (
  351. <NoOverflow>
  352. <Tooltip title={t('View Transaction')}>
  353. <Link to={eventTarget}>{getShortEventId(row.id)}</Link>
  354. </Tooltip>
  355. </NoOverflow>
  356. );
  357. }
  358. if (key === SpanIndexedField.SPAN_DESCRIPTION) {
  359. return (
  360. <NoOverflow>
  361. <Tooltip title={row[key]}>{row[key]}</Tooltip>
  362. </NoOverflow>
  363. );
  364. }
  365. return <NoOverflow>{row[key]}</NoOverflow>;
  366. }
  367. return (
  368. <span>
  369. <SearchBarContainer>
  370. {
  371. <SegmentedControl
  372. size="md"
  373. value={datatype}
  374. onChange={newDataSet => {
  375. // Reset pagination and sort when switching datatypes
  376. router.replace({
  377. ...location,
  378. query: {
  379. ...location.query,
  380. sort: undefined,
  381. cursor: undefined,
  382. [DATATYPE_KEY]: newDataSet,
  383. },
  384. });
  385. }}
  386. >
  387. <SegmentedControl.Item key={Datatype.PAGELOADS}>
  388. {t('Pageloads')}
  389. </SegmentedControl.Item>
  390. <SegmentedControl.Item key={Datatype.INTERACTIONS}>
  391. {t('Interactions')}
  392. </SegmentedControl.Item>
  393. </SegmentedControl>
  394. }
  395. <StyledSearchBar
  396. query={query}
  397. organization={organization}
  398. onSearch={queryString =>
  399. router.replace({
  400. ...location,
  401. query: {...location.query, query: queryString},
  402. })
  403. }
  404. />
  405. <StyledPagination
  406. pageLinks={
  407. datatype === Datatype.INTERACTIONS ? interactionsPageLinks : pageLinks
  408. }
  409. disabled={
  410. datatype === Datatype.INTERACTIONS ? isInteractionsLoading : isLoading
  411. }
  412. size="md"
  413. />
  414. {/* The Pagination component disappears if pageLinks is not defined,
  415. which happens any time the table data is loading. So we render a
  416. disabled button bar if pageLinks is not defined to minimize ui shifting */}
  417. {!(datatype === Datatype.INTERACTIONS ? interactionsPageLinks : pageLinks) && (
  418. <Wrapper>
  419. <ButtonBar merged>
  420. <Button
  421. icon={<IconChevron direction="left" />}
  422. disabled
  423. aria-label={t('Previous')}
  424. />
  425. <Button
  426. icon={<IconChevron direction="right" />}
  427. disabled
  428. aria-label={t('Next')}
  429. />
  430. </ButtonBar>
  431. </Wrapper>
  432. )}
  433. </SearchBarContainer>
  434. <GridContainer>
  435. {datatype === Datatype.PAGELOADS && (
  436. <GridEditable
  437. isLoading={isLoading}
  438. columnOrder={PAGELOADS_COLUMN_ORDER}
  439. columnSortBy={[]}
  440. data={tableData}
  441. grid={{
  442. renderHeadCell,
  443. renderBodyCell,
  444. }}
  445. location={location}
  446. minimumColWidth={70}
  447. />
  448. )}
  449. {datatype === Datatype.INTERACTIONS && (
  450. <GridEditable
  451. isLoading={isInteractionsLoading}
  452. columnOrder={INTERACTION_SAMPLES_COLUMN_ORDER}
  453. columnSortBy={[]}
  454. data={interactionsTableData}
  455. grid={{
  456. renderHeadCell,
  457. renderBodyCell,
  458. }}
  459. location={location}
  460. minimumColWidth={70}
  461. />
  462. )}
  463. </GridContainer>
  464. </span>
  465. );
  466. }
  467. const NoOverflow = styled('span')`
  468. overflow: hidden;
  469. text-overflow: ellipsis;
  470. white-space: nowrap;
  471. `;
  472. const AlignRight = styled('span')<{color?: string}>`
  473. text-align: right;
  474. width: 100%;
  475. ${p => (p.color ? `color: ${p.color};` : '')}
  476. `;
  477. const AlignCenter = styled('div')`
  478. display: block;
  479. margin: auto;
  480. text-align: center;
  481. width: 100%;
  482. `;
  483. const StyledProjectAvatar = styled(ProjectAvatar)`
  484. top: ${space(0.25)};
  485. position: relative;
  486. padding-right: ${space(1)};
  487. `;
  488. // Not pretty but we need to override gridEditable styles since the original
  489. // styles have too much padding for small spaces
  490. const GridContainer = styled('div')`
  491. margin-bottom: ${space(1)};
  492. th {
  493. padding: 0 ${space(1)};
  494. }
  495. th:first-child {
  496. padding-left: ${space(2)};
  497. }
  498. th:last-child {
  499. padding-right: ${space(2)};
  500. }
  501. td {
  502. padding: ${space(1)};
  503. }
  504. td:first-child {
  505. padding-right: ${space(1)};
  506. padding-left: ${space(2)};
  507. }
  508. `;
  509. const NoValue = styled('span')`
  510. color: ${p => p.theme.gray300};
  511. `;
  512. const SearchBarContainer = styled('div')`
  513. display: flex;
  514. margin-top: ${space(2)};
  515. margin-bottom: ${space(1)};
  516. gap: ${space(1)};
  517. `;
  518. const StyledSearchBar = styled(SearchBar)`
  519. flex-grow: 1;
  520. `;
  521. const StyledPagination = styled(Pagination)`
  522. margin: 0;
  523. `;
  524. const Wrapper = styled('div')`
  525. display: flex;
  526. align-items: center;
  527. justify-content: flex-end;
  528. margin: 0;
  529. `;
  530. const TooltipHeader = styled('span')`
  531. ${p => p.theme.tooltipUnderline()};
  532. `;
  533. const StyledTooltip = styled(Tooltip)`
  534. top: 1px;
  535. position: relative;
  536. `;