pageSamplePerformanceTable.tsx 17 KB

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