pageSamplePerformanceTable.tsx 18 KB

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