pageSamplePerformanceTable.tsx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  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 {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 useProfileExists from 'sentry/views/insights/browser/webVitals/utils/useProfileExists';
  46. import {useWebVitalsSort} from 'sentry/views/insights/browser/webVitals/utils/useWebVitalsSort';
  47. import {SpanIndexedField} from 'sentry/views/insights/types';
  48. import {TraceViewSources} from 'sentry/views/performance/newTraceDetails/traceMetadataHeader';
  49. import {generateReplayLink} from 'sentry/views/performance/transactionSummary/utils';
  50. type Column = GridColumnHeader<keyof TransactionSampleRowWithScore>;
  51. type InteractionsColumn = GridColumnHeader<keyof InteractionSpanSampleRowWithScore>;
  52. const PAGELOADS_COLUMN_ORDER: GridColumnOrder<keyof TransactionSampleRowWithScore>[] = [
  53. {key: 'id', width: COL_WIDTH_UNDEFINED, name: t('Event ID')},
  54. {key: 'user.display', width: COL_WIDTH_UNDEFINED, name: t('User')},
  55. {key: 'measurements.lcp', width: COL_WIDTH_UNDEFINED, name: 'LCP'},
  56. {key: 'measurements.fcp', width: COL_WIDTH_UNDEFINED, name: 'FCP'},
  57. {key: 'measurements.cls', width: COL_WIDTH_UNDEFINED, name: 'CLS'},
  58. {key: 'measurements.ttfb', width: COL_WIDTH_UNDEFINED, name: 'TTFB'},
  59. {key: 'profile.id', width: COL_WIDTH_UNDEFINED, name: t('Profile')},
  60. {key: 'replayId', width: COL_WIDTH_UNDEFINED, name: t('Replay')},
  61. {key: 'totalScore', width: COL_WIDTH_UNDEFINED, name: t('Score')},
  62. ];
  63. const INTERACTION_SAMPLES_COLUMN_ORDER: GridColumnOrder<
  64. keyof InteractionSpanSampleRowWithScore
  65. >[] = [
  66. {
  67. key: SpanIndexedField.SPAN_DESCRIPTION,
  68. width: COL_WIDTH_UNDEFINED,
  69. name: t('Interaction Target'),
  70. },
  71. {key: 'user.display', width: COL_WIDTH_UNDEFINED, name: t('User')},
  72. {key: SpanIndexedField.INP, width: COL_WIDTH_UNDEFINED, name: 'INP'},
  73. {key: 'profile.id', width: COL_WIDTH_UNDEFINED, name: t('Profile')},
  74. {key: 'replayId', width: COL_WIDTH_UNDEFINED, name: t('Replay')},
  75. {key: 'inpScore', width: COL_WIDTH_UNDEFINED, name: t('Score')},
  76. ];
  77. enum Datatype {
  78. PAGELOADS = 'pageloads',
  79. INTERACTIONS = 'interactions',
  80. }
  81. const DATATYPE_KEY = 'type';
  82. type Props = {
  83. transaction: string;
  84. limit?: number;
  85. search?: string;
  86. };
  87. export function PageSamplePerformanceTable({transaction, search, limit = 9}: Props) {
  88. const location = useLocation();
  89. const {projects} = useProjects();
  90. const organization = useOrganization();
  91. const {replayExists} = useReplayExists();
  92. const routes = useRoutes();
  93. const router = useRouter();
  94. let datatype = Datatype.PAGELOADS;
  95. switch (decodeScalar(location.query[DATATYPE_KEY], 'pageloads')) {
  96. case 'interactions':
  97. datatype = Datatype.INTERACTIONS;
  98. break;
  99. default:
  100. datatype = Datatype.PAGELOADS;
  101. }
  102. const sortableFields = SORTABLE_INDEXED_FIELDS;
  103. const sort = useWebVitalsSort({
  104. defaultSort: DEFAULT_INDEXED_SORT,
  105. sortableFields: sortableFields as unknown as string[],
  106. });
  107. const replayLinkGenerator = generateReplayLink(routes);
  108. const project = useMemo(
  109. () => projects.find(p => p.id === String(location.query.project)),
  110. [projects, location.query.project]
  111. );
  112. const query = decodeScalar(location.query.query);
  113. const {
  114. data: tableData,
  115. isLoading,
  116. pageLinks,
  117. } = useTransactionSamplesWebVitalsScoresQuery({
  118. limit,
  119. transaction,
  120. query: search,
  121. withProfiles: true,
  122. enabled: datatype === Datatype.PAGELOADS,
  123. });
  124. const {
  125. data: interactionsTableData,
  126. isFetching: isInteractionsLoading,
  127. pageLinks: interactionsPageLinks,
  128. } = useInpSpanSamplesWebVitalsQuery({
  129. transaction,
  130. enabled: datatype === Datatype.INTERACTIONS,
  131. limit,
  132. filters: new MutableSearch(query ?? '').filters,
  133. });
  134. const {profileExists} = useProfileExists(
  135. interactionsTableData.filter(row => row['profile.id']).map(row => row['profile.id'])
  136. );
  137. const getFormattedDuration = (value: number) => {
  138. return getDuration(value, value < 1 ? 0 : 2, true);
  139. };
  140. function renderHeadCell(col: Column | InteractionsColumn) {
  141. function generateSortLink() {
  142. const key = ['totalScore', 'inpScore'].includes(col.key)
  143. ? 'measurements.score.total'
  144. : col.key;
  145. let newSortDirection: Sort['kind'] = 'desc';
  146. if (sort?.field === key) {
  147. if (sort.kind === 'desc') {
  148. newSortDirection = 'asc';
  149. }
  150. }
  151. const newSort = `${newSortDirection === 'desc' ? '-' : ''}${key}`;
  152. return {
  153. ...location,
  154. query: {...location.query, sort: newSort},
  155. };
  156. }
  157. const canSort = (sortableFields as ReadonlyArray<string>).includes(col.key);
  158. if (
  159. [
  160. 'measurements.fcp',
  161. 'measurements.lcp',
  162. 'measurements.ttfb',
  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={`${MODULE_DOC_LINK}#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.inp',
  260. 'transaction.duration',
  261. ].includes(key)
  262. ) {
  263. return (
  264. <AlignRight>
  265. {row[key] === undefined ? (
  266. <NoValue>{' \u2014 '}</NoValue>
  267. ) : (
  268. getFormattedDuration((row[key] as number) / 1000)
  269. )}
  270. </AlignRight>
  271. );
  272. }
  273. if (['measurements.cls', 'opportunity'].includes(key)) {
  274. return (
  275. <AlignRight>
  276. {row[key] === undefined ? (
  277. <NoValue>{' \u2014 '}</NoValue>
  278. ) : (
  279. Math.round((row[key] as number) * 100) / 100
  280. )}
  281. </AlignRight>
  282. );
  283. }
  284. if (key === 'profile.id') {
  285. const profileId = String(row[key]);
  286. const profileTarget =
  287. defined(row.projectSlug) && defined(row[key])
  288. ? generateProfileFlamechartRoute({
  289. orgSlug: organization.slug,
  290. projectSlug: row.projectSlug,
  291. profileId,
  292. })
  293. : null;
  294. return (
  295. <NoOverflow>
  296. <AlignCenter>
  297. {profileTarget && profileExists(profileId) && (
  298. <Tooltip title={t('View Profile')}>
  299. <LinkButton to={profileTarget} size="xs">
  300. <IconProfiling size="xs" />
  301. </LinkButton>
  302. </Tooltip>
  303. )}
  304. </AlignCenter>
  305. </NoOverflow>
  306. );
  307. }
  308. if (key === 'replayId') {
  309. const replayTarget =
  310. (row['transaction.duration'] !== undefined ||
  311. row[SpanIndexedField.SPAN_SELF_TIME] !== undefined) &&
  312. replayLinkGenerator(
  313. organization,
  314. {
  315. replayId: row[key],
  316. id: '', // id doesn't get used in replayLinkGenerator. This is just to satisfy the type.
  317. 'transaction.duration':
  318. datatype === Datatype.INTERACTIONS
  319. ? row[SpanIndexedField.SPAN_SELF_TIME]
  320. : row['transaction.duration'],
  321. timestamp: row.timestamp,
  322. },
  323. undefined
  324. );
  325. return (
  326. <NoOverflow>
  327. <AlignCenter>
  328. {replayTarget &&
  329. Object.keys(replayTarget).length > 0 &&
  330. replayExists(row[key]) && (
  331. <Tooltip title={t('View Replay')}>
  332. <LinkButton to={replayTarget} size="xs">
  333. <IconPlay size="xs" />
  334. </LinkButton>
  335. </Tooltip>
  336. )}
  337. </AlignCenter>
  338. </NoOverflow>
  339. );
  340. }
  341. if (key === 'id' && 'id' in row) {
  342. const eventTarget = generateLinkToEventInTraceView({
  343. projectSlug: row.projectSlug,
  344. traceSlug: row.trace,
  345. eventId: row.id,
  346. timestamp: row.timestamp,
  347. organization,
  348. location,
  349. source: TraceViewSources.WEB_VITALS_MODULE,
  350. });
  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. <SegmentedControl
  372. size="md"
  373. value={datatype}
  374. aria-label={t('Data Type')}
  375. onChange={newDataSet => {
  376. // Reset pagination and sort when switching datatypes
  377. trackAnalytics('insight.vital.overview.toggle_data_type', {
  378. organization,
  379. type: newDataSet,
  380. });
  381. router.replace({
  382. ...location,
  383. query: {
  384. ...location.query,
  385. sort: undefined,
  386. cursor: undefined,
  387. [DATATYPE_KEY]: newDataSet,
  388. },
  389. });
  390. }}
  391. >
  392. <SegmentedControl.Item key={Datatype.PAGELOADS} aria-label={t('Pageloads')}>
  393. {t('Pageloads')}
  394. </SegmentedControl.Item>
  395. <SegmentedControl.Item
  396. key={Datatype.INTERACTIONS}
  397. aria-label={t('Interactions')}
  398. >
  399. {t('Interactions')}
  400. </SegmentedControl.Item>
  401. </SegmentedControl>
  402. <StyledSearchBar
  403. query={query}
  404. organization={organization}
  405. onSearch={queryString =>
  406. router.replace({
  407. ...location,
  408. query: {...location.query, query: queryString},
  409. })
  410. }
  411. />
  412. <StyledPagination
  413. pageLinks={
  414. datatype === Datatype.INTERACTIONS ? interactionsPageLinks : pageLinks
  415. }
  416. disabled={
  417. datatype === Datatype.INTERACTIONS ? isInteractionsLoading : isLoading
  418. }
  419. size="md"
  420. />
  421. {/* The Pagination component disappears if pageLinks is not defined,
  422. which happens any time the table data is loading. So we render a
  423. disabled button bar if pageLinks is not defined to minimize ui shifting */}
  424. {!(datatype === Datatype.INTERACTIONS ? interactionsPageLinks : pageLinks) && (
  425. <Wrapper>
  426. <ButtonBar merged>
  427. <Button
  428. icon={<IconChevron direction="left" />}
  429. disabled
  430. aria-label={t('Previous')}
  431. />
  432. <Button
  433. icon={<IconChevron direction="right" />}
  434. disabled
  435. aria-label={t('Next')}
  436. />
  437. </ButtonBar>
  438. </Wrapper>
  439. )}
  440. </SearchBarContainer>
  441. {datatype === Datatype.PAGELOADS && (
  442. <GridEditable
  443. isLoading={isLoading}
  444. columnOrder={PAGELOADS_COLUMN_ORDER}
  445. columnSortBy={[]}
  446. data={tableData}
  447. grid={{
  448. renderHeadCell,
  449. renderBodyCell,
  450. }}
  451. minimumColWidth={70}
  452. />
  453. )}
  454. {datatype === Datatype.INTERACTIONS && (
  455. <GridEditable
  456. isLoading={isInteractionsLoading}
  457. columnOrder={INTERACTION_SAMPLES_COLUMN_ORDER}
  458. columnSortBy={[]}
  459. data={interactionsTableData}
  460. grid={{
  461. renderHeadCell,
  462. renderBodyCell,
  463. }}
  464. minimumColWidth={70}
  465. />
  466. )}
  467. </span>
  468. );
  469. }
  470. const NoOverflow = styled('span')`
  471. overflow: hidden;
  472. text-overflow: ellipsis;
  473. white-space: nowrap;
  474. `;
  475. const AlignRight = styled('span')<{color?: string}>`
  476. text-align: right;
  477. width: 100%;
  478. ${p => (p.color ? `color: ${p.color};` : '')}
  479. `;
  480. const AlignCenter = styled('div')`
  481. display: block;
  482. margin: auto;
  483. text-align: center;
  484. width: 100%;
  485. `;
  486. const StyledProjectAvatar = styled(ProjectAvatar)`
  487. top: ${space(0.25)};
  488. position: relative;
  489. padding-right: ${space(1)};
  490. `;
  491. const NoValue = styled('span')`
  492. color: ${p => p.theme.gray300};
  493. `;
  494. const SearchBarContainer = styled('div')`
  495. display: flex;
  496. margin-top: ${space(2)};
  497. margin-bottom: ${space(1)};
  498. gap: ${space(1)};
  499. `;
  500. const StyledSearchBar = styled(SearchBar)`
  501. flex-grow: 1;
  502. `;
  503. const StyledPagination = styled(Pagination)`
  504. margin: 0;
  505. `;
  506. const Wrapper = styled('div')`
  507. display: flex;
  508. align-items: center;
  509. justify-content: flex-end;
  510. margin: 0;
  511. `;
  512. const TooltipHeader = styled('span')`
  513. ${p => p.theme.tooltipUnderline()};
  514. `;
  515. const StyledTooltip = styled(Tooltip)`
  516. top: 1px;
  517. position: relative;
  518. `;