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/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. type Column = GridColumnHeader<keyof TransactionSampleRowWithScore>;
  50. type InteractionsColumn = GridColumnHeader<keyof InteractionSpanSampleRowWithScore>;
  51. const PAGELOADS_COLUMN_ORDER: GridColumnOrder<keyof TransactionSampleRowWithScore>[] = [
  52. {key: 'id', width: COL_WIDTH_UNDEFINED, name: t('Event ID')},
  53. {key: 'user.display', width: COL_WIDTH_UNDEFINED, name: t('User')},
  54. {key: 'measurements.lcp', width: COL_WIDTH_UNDEFINED, name: 'LCP'},
  55. {key: 'measurements.fcp', width: COL_WIDTH_UNDEFINED, name: 'FCP'},
  56. {key: 'measurements.cls', width: COL_WIDTH_UNDEFINED, name: 'CLS'},
  57. {key: 'measurements.ttfb', width: COL_WIDTH_UNDEFINED, name: 'TTFB'},
  58. {key: 'profile.id', width: COL_WIDTH_UNDEFINED, name: t('Profile')},
  59. {key: 'replayId', width: COL_WIDTH_UNDEFINED, name: t('Replay')},
  60. {key: 'totalScore', width: COL_WIDTH_UNDEFINED, name: t('Score')},
  61. ];
  62. const INTERACTION_SAMPLES_COLUMN_ORDER: GridColumnOrder<
  63. keyof InteractionSpanSampleRowWithScore
  64. >[] = [
  65. {
  66. key: SpanIndexedField.SPAN_DESCRIPTION,
  67. width: COL_WIDTH_UNDEFINED,
  68. name: t('Interaction Target'),
  69. },
  70. {key: 'user.display', width: COL_WIDTH_UNDEFINED, name: t('User')},
  71. {key: SpanIndexedField.INP, width: COL_WIDTH_UNDEFINED, name: 'INP'},
  72. {key: 'profile.id', width: COL_WIDTH_UNDEFINED, name: t('Profile')},
  73. {key: 'replayId', width: COL_WIDTH_UNDEFINED, name: t('Replay')},
  74. {key: 'inpScore', width: COL_WIDTH_UNDEFINED, name: t('Score')},
  75. ];
  76. enum Datatype {
  77. PAGELOADS = 'pageloads',
  78. INTERACTIONS = 'interactions',
  79. }
  80. const DATATYPE_KEY = 'type';
  81. type Props = {
  82. transaction: string;
  83. limit?: number;
  84. search?: string;
  85. };
  86. export function PageSamplePerformanceTable({transaction, search, limit = 9}: Props) {
  87. const location = useLocation();
  88. const {projects} = useProjects();
  89. const organization = useOrganization();
  90. const {replayExists} = useReplayExists();
  91. const routes = useRoutes();
  92. const router = useRouter();
  93. let datatype = Datatype.PAGELOADS;
  94. switch (decodeScalar(location.query[DATATYPE_KEY], 'pageloads')) {
  95. case 'interactions':
  96. datatype = Datatype.INTERACTIONS;
  97. break;
  98. default:
  99. datatype = Datatype.PAGELOADS;
  100. }
  101. const sortableFields = SORTABLE_INDEXED_FIELDS;
  102. const sort = useWebVitalsSort({
  103. defaultSort: DEFAULT_INDEXED_SORT,
  104. sortableFields: sortableFields as unknown as string[],
  105. });
  106. const replayLinkGenerator = generateReplayLink(routes);
  107. const project = useMemo(
  108. () => projects.find(p => p.id === String(location.query.project)),
  109. [projects, location.query.project]
  110. );
  111. const query = decodeScalar(location.query.query);
  112. const {
  113. data: tableData,
  114. isLoading,
  115. pageLinks,
  116. } = useTransactionSamplesWebVitalsQuery({
  117. limit,
  118. transaction,
  119. query: search,
  120. withProfiles: true,
  121. enabled: datatype === Datatype.PAGELOADS,
  122. });
  123. const {
  124. data: interactionsTableData,
  125. isFetching: isInteractionsLoading,
  126. pageLinks: interactionsPageLinks,
  127. } = useInpSpanSamplesWebVitalsQuery({
  128. transaction,
  129. enabled: datatype === Datatype.INTERACTIONS,
  130. limit,
  131. filters: new MutableSearch(query ?? '').filters,
  132. });
  133. const {profileExists} = useProfileExists(
  134. interactionsTableData.filter(row => row['profile.id']).map(row => row['profile.id'])
  135. );
  136. const getFormattedDuration = (value: number) => {
  137. return getDuration(value, value < 1 ? 0 : 2, true);
  138. };
  139. function renderHeadCell(col: Column | InteractionsColumn) {
  140. function generateSortLink() {
  141. const key = ['totalScore', 'inpScore'].includes(col.key)
  142. ? 'measurements.score.total'
  143. : col.key;
  144. let newSortDirection: Sort['kind'] = 'desc';
  145. if (sort?.field === key) {
  146. if (sort.kind === 'desc') {
  147. newSortDirection = 'asc';
  148. }
  149. }
  150. const newSort = `${newSortDirection === 'desc' ? '-' : ''}${key}`;
  151. return {
  152. ...location,
  153. query: {...location.query, sort: newSort},
  154. };
  155. }
  156. const canSort = (sortableFields as ReadonlyArray<string>).includes(col.key);
  157. if (
  158. [
  159. 'measurements.fcp',
  160. 'measurements.lcp',
  161. 'measurements.ttfb',
  162. 'measurements.fid',
  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.fid',
  260. 'measurements.inp',
  261. 'transaction.duration',
  262. ].includes(key)
  263. ) {
  264. return (
  265. <AlignRight>
  266. {row[key] === undefined ? (
  267. <NoValue>{' \u2014 '}</NoValue>
  268. ) : (
  269. getFormattedDuration((row[key] as number) / 1000)
  270. )}
  271. </AlignRight>
  272. );
  273. }
  274. if (['measurements.cls', 'opportunity'].includes(key)) {
  275. return (
  276. <AlignRight>
  277. {row[key] === undefined ? (
  278. <NoValue>{' \u2014 '}</NoValue>
  279. ) : (
  280. Math.round((row[key] as number) * 100) / 100
  281. )}
  282. </AlignRight>
  283. );
  284. }
  285. if (key === 'profile.id') {
  286. const profileId = String(row[key]);
  287. const profileTarget =
  288. defined(row.projectSlug) && defined(row[key])
  289. ? generateProfileFlamechartRoute({
  290. orgSlug: organization.slug,
  291. projectSlug: row.projectSlug,
  292. profileId,
  293. })
  294. : null;
  295. return (
  296. <NoOverflow>
  297. <AlignCenter>
  298. {profileTarget && profileExists(profileId) && (
  299. <Tooltip title={t('View Profile')}>
  300. <LinkButton to={profileTarget} size="xs">
  301. <IconProfiling size="xs" />
  302. </LinkButton>
  303. </Tooltip>
  304. )}
  305. </AlignCenter>
  306. </NoOverflow>
  307. );
  308. }
  309. if (key === 'replayId') {
  310. const replayTarget =
  311. (row['transaction.duration'] !== undefined ||
  312. row[SpanIndexedField.SPAN_SELF_TIME] !== undefined) &&
  313. replayLinkGenerator(
  314. organization,
  315. {
  316. replayId: row[key],
  317. id: '', // id doesn't get used in replayLinkGenerator. This is just to satisfy the type.
  318. 'transaction.duration':
  319. datatype === Datatype.INTERACTIONS
  320. ? row[SpanIndexedField.SPAN_SELF_TIME]
  321. : row['transaction.duration'],
  322. timestamp: row.timestamp,
  323. },
  324. undefined
  325. );
  326. return (
  327. <NoOverflow>
  328. <AlignCenter>
  329. {replayTarget &&
  330. Object.keys(replayTarget).length > 0 &&
  331. replayExists(row[key]) && (
  332. <Tooltip title={t('View Replay')}>
  333. <LinkButton to={replayTarget} size="xs">
  334. <IconPlay size="xs" />
  335. </LinkButton>
  336. </Tooltip>
  337. )}
  338. </AlignCenter>
  339. </NoOverflow>
  340. );
  341. }
  342. if (key === 'id' && 'id' in row) {
  343. const eventTarget = generateLinkToEventInTraceView({
  344. projectSlug: row.projectSlug,
  345. traceSlug: row.trace,
  346. eventId: row.id,
  347. timestamp: row.timestamp,
  348. organization,
  349. location,
  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. `;