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