pageSamplePerformanceTable.tsx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  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/performance/browser/webVitals/components/performanceBadge';
  34. import {MODULE_DOC_LINK} from 'sentry/views/performance/browser/webVitals/settings';
  35. import useProfileExists from 'sentry/views/performance/browser/webVitals/utils/profiling/useProfileExists';
  36. import {useInpSpanSamplesWebVitalsQuery} from 'sentry/views/performance/browser/webVitals/utils/queries/useInpSpanSamplesWebVitalsQuery';
  37. import {useTransactionSamplesWebVitalsQuery} from 'sentry/views/performance/browser/webVitals/utils/queries/useTransactionSamplesWebVitalsQuery';
  38. import type {
  39. InteractionSpanSampleRowWithScore,
  40. TransactionSampleRowWithScore,
  41. } from 'sentry/views/performance/browser/webVitals/utils/types';
  42. import {
  43. DEFAULT_INDEXED_SORT,
  44. SORTABLE_INDEXED_FIELDS,
  45. } from 'sentry/views/performance/browser/webVitals/utils/types';
  46. import {useWebVitalsSort} from 'sentry/views/performance/browser/webVitals/utils/useWebVitalsSort';
  47. import {generateReplayLink} from 'sentry/views/performance/transactionSummary/utils';
  48. import {SpanIndexedField} from 'sentry/views/starfish/types';
  49. import {TraceViewSources} from '../../newTraceDetails/traceMetadataHeader';
  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. } = useTransactionSamplesWebVitalsQuery({
  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.fid',
  164. 'measurements.cls',
  165. 'measurements.inp',
  166. 'transaction.duration',
  167. ].includes(col.key)
  168. ) {
  169. if (canSort) {
  170. return (
  171. <SortLink
  172. align="right"
  173. title={col.name}
  174. direction={sort?.field === col.key ? sort.kind : undefined}
  175. canSort={canSort}
  176. generateSortLink={generateSortLink}
  177. />
  178. );
  179. }
  180. return (
  181. <AlignRight>
  182. <span>{col.name}</span>
  183. </AlignRight>
  184. );
  185. }
  186. if (col.key === 'totalScore' || col.key === 'inpScore') {
  187. return (
  188. <SortLink
  189. title={
  190. <AlignCenter>
  191. <StyledTooltip
  192. isHoverable
  193. title={
  194. <span>
  195. {t('The overall performance rating of this page.')}
  196. <br />
  197. <ExternalLink href={`${MODULE_DOC_LINK}#performance-score`}>
  198. {t('How is this calculated?')}
  199. </ExternalLink>
  200. </span>
  201. }
  202. >
  203. <TooltipHeader>{t('Perf Score')}</TooltipHeader>
  204. </StyledTooltip>
  205. </AlignCenter>
  206. }
  207. direction={sort?.field === col.key ? sort.kind : undefined}
  208. canSort={canSort}
  209. generateSortLink={generateSortLink}
  210. align={undefined}
  211. />
  212. );
  213. }
  214. if (col.key === 'replayId' || col.key === 'profile.id') {
  215. return (
  216. <AlignCenter>
  217. <span>{col.name}</span>
  218. </AlignCenter>
  219. );
  220. }
  221. return <span>{col.name}</span>;
  222. }
  223. function renderBodyCell(
  224. col: Column | InteractionsColumn,
  225. row: TransactionSampleRowWithScore | InteractionSpanSampleRowWithScore
  226. ) {
  227. const {key} = col;
  228. if (key === 'totalScore' || key === 'inpScore') {
  229. return (
  230. <AlignCenter>
  231. <PerformanceBadge score={row[key]} />
  232. </AlignCenter>
  233. );
  234. }
  235. if (key === 'transaction' && 'transaction' in row) {
  236. return (
  237. <NoOverflow>
  238. {project && (
  239. <StyledProjectAvatar
  240. project={project}
  241. direction="left"
  242. size={16}
  243. hasTooltip
  244. tooltip={project.slug}
  245. />
  246. )}
  247. <Link
  248. to={{...location, query: {...location.query, transaction: row.transaction}}}
  249. >
  250. {row.transaction}
  251. </Link>
  252. </NoOverflow>
  253. );
  254. }
  255. if (
  256. [
  257. 'measurements.fcp',
  258. 'measurements.lcp',
  259. 'measurements.ttfb',
  260. 'measurements.fid',
  261. 'measurements.inp',
  262. 'transaction.duration',
  263. ].includes(key)
  264. ) {
  265. return (
  266. <AlignRight>
  267. {row[key] === undefined ? (
  268. <NoValue>{' \u2014 '}</NoValue>
  269. ) : (
  270. getFormattedDuration((row[key] as number) / 1000)
  271. )}
  272. </AlignRight>
  273. );
  274. }
  275. if (['measurements.cls', 'opportunity'].includes(key)) {
  276. return (
  277. <AlignRight>
  278. {row[key] === undefined ? (
  279. <NoValue>{' \u2014 '}</NoValue>
  280. ) : (
  281. Math.round((row[key] as number) * 100) / 100
  282. )}
  283. </AlignRight>
  284. );
  285. }
  286. if (key === 'profile.id') {
  287. const profileId = String(row[key]);
  288. const profileTarget =
  289. defined(row.projectSlug) && defined(row[key])
  290. ? generateProfileFlamechartRoute({
  291. orgSlug: organization.slug,
  292. projectSlug: row.projectSlug,
  293. profileId,
  294. })
  295. : null;
  296. return (
  297. <NoOverflow>
  298. <AlignCenter>
  299. {profileTarget && profileExists(profileId) && (
  300. <Tooltip title={t('View Profile')}>
  301. <LinkButton to={profileTarget} size="xs">
  302. <IconProfiling size="xs" />
  303. </LinkButton>
  304. </Tooltip>
  305. )}
  306. </AlignCenter>
  307. </NoOverflow>
  308. );
  309. }
  310. if (key === 'replayId') {
  311. const replayTarget =
  312. (row['transaction.duration'] !== undefined ||
  313. row[SpanIndexedField.SPAN_SELF_TIME] !== undefined) &&
  314. replayLinkGenerator(
  315. organization,
  316. {
  317. replayId: row[key],
  318. id: '', // id doesn't get used in replayLinkGenerator. This is just to satisfy the type.
  319. 'transaction.duration':
  320. datatype === Datatype.INTERACTIONS
  321. ? row[SpanIndexedField.SPAN_SELF_TIME]
  322. : row['transaction.duration'],
  323. timestamp: row.timestamp,
  324. },
  325. undefined
  326. );
  327. return (
  328. <NoOverflow>
  329. <AlignCenter>
  330. {replayTarget &&
  331. Object.keys(replayTarget).length > 0 &&
  332. replayExists(row[key]) && (
  333. <Tooltip title={t('View Replay')}>
  334. <LinkButton to={replayTarget} size="xs">
  335. <IconPlay size="xs" />
  336. </LinkButton>
  337. </Tooltip>
  338. )}
  339. </AlignCenter>
  340. </NoOverflow>
  341. );
  342. }
  343. if (key === 'id' && 'id' in row) {
  344. const eventTarget = generateLinkToEventInTraceView({
  345. projectSlug: row.projectSlug,
  346. traceSlug: row.trace,
  347. eventId: row.id,
  348. timestamp: row.timestamp,
  349. organization,
  350. location,
  351. source: TraceViewSources.WEB_VITALS_MODULE,
  352. });
  353. return (
  354. <NoOverflow>
  355. <Tooltip title={t('View Transaction')}>
  356. <Link to={eventTarget}>{getShortEventId(row.id)}</Link>
  357. </Tooltip>
  358. </NoOverflow>
  359. );
  360. }
  361. if (key === SpanIndexedField.SPAN_DESCRIPTION) {
  362. return (
  363. <NoOverflow>
  364. <Tooltip title={row[key]}>{row[key]}</Tooltip>
  365. </NoOverflow>
  366. );
  367. }
  368. return <NoOverflow>{row[key]}</NoOverflow>;
  369. }
  370. return (
  371. <span>
  372. <SearchBarContainer>
  373. <SegmentedControl
  374. size="md"
  375. value={datatype}
  376. aria-label={t('Data Type')}
  377. onChange={newDataSet => {
  378. // Reset pagination and sort when switching datatypes
  379. trackAnalytics('insight.vital.overview.toggle_data_type', {
  380. organization,
  381. type: newDataSet,
  382. });
  383. router.replace({
  384. ...location,
  385. query: {
  386. ...location.query,
  387. sort: undefined,
  388. cursor: undefined,
  389. [DATATYPE_KEY]: newDataSet,
  390. },
  391. });
  392. }}
  393. >
  394. <SegmentedControl.Item key={Datatype.PAGELOADS} aria-label={t('Pageloads')}>
  395. {t('Pageloads')}
  396. </SegmentedControl.Item>
  397. <SegmentedControl.Item
  398. key={Datatype.INTERACTIONS}
  399. aria-label={t('Interactions')}
  400. >
  401. {t('Interactions')}
  402. </SegmentedControl.Item>
  403. </SegmentedControl>
  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. {datatype === Datatype.PAGELOADS && (
  444. <GridEditable
  445. isLoading={isLoading}
  446. columnOrder={PAGELOADS_COLUMN_ORDER}
  447. columnSortBy={[]}
  448. data={tableData}
  449. grid={{
  450. renderHeadCell,
  451. renderBodyCell,
  452. }}
  453. minimumColWidth={70}
  454. />
  455. )}
  456. {datatype === Datatype.INTERACTIONS && (
  457. <GridEditable
  458. isLoading={isInteractionsLoading}
  459. columnOrder={INTERACTION_SAMPLES_COLUMN_ORDER}
  460. columnSortBy={[]}
  461. data={interactionsTableData}
  462. grid={{
  463. renderHeadCell,
  464. renderBodyCell,
  465. }}
  466. minimumColWidth={70}
  467. />
  468. )}
  469. </span>
  470. );
  471. }
  472. const NoOverflow = styled('span')`
  473. overflow: hidden;
  474. text-overflow: ellipsis;
  475. white-space: nowrap;
  476. `;
  477. const AlignRight = styled('span')<{color?: string}>`
  478. text-align: right;
  479. width: 100%;
  480. ${p => (p.color ? `color: ${p.color};` : '')}
  481. `;
  482. const AlignCenter = styled('div')`
  483. display: block;
  484. margin: auto;
  485. text-align: center;
  486. width: 100%;
  487. `;
  488. const StyledProjectAvatar = styled(ProjectAvatar)`
  489. top: ${space(0.25)};
  490. position: relative;
  491. padding-right: ${space(1)};
  492. `;
  493. const NoValue = styled('span')`
  494. color: ${p => p.theme.gray300};
  495. `;
  496. const SearchBarContainer = styled('div')`
  497. display: flex;
  498. margin-top: ${space(2)};
  499. margin-bottom: ${space(1)};
  500. gap: ${space(1)};
  501. `;
  502. const StyledSearchBar = styled(SearchBar)`
  503. flex-grow: 1;
  504. `;
  505. const StyledPagination = styled(Pagination)`
  506. margin: 0;
  507. `;
  508. const Wrapper = styled('div')`
  509. display: flex;
  510. align-items: center;
  511. justify-content: flex-end;
  512. margin: 0;
  513. `;
  514. const TooltipHeader = styled('span')`
  515. ${p => p.theme.tooltipUnderline()};
  516. `;
  517. const StyledTooltip = styled(Tooltip)`
  518. top: 1px;
  519. position: relative;
  520. `;