pageSamplePerformanceTable.tsx 17 KB

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