pageSamplePerformanceTable.tsx 18 KB

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