pagePerformanceTable.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. import {useMemo} from 'react';
  2. import {browserHistory, Link} from 'react-router';
  3. import styled from '@emotion/styled';
  4. import ProjectAvatar from 'sentry/components/avatar/projectAvatar';
  5. import {Button} from 'sentry/components/button';
  6. import ButtonBar from 'sentry/components/buttonBar';
  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 Pagination from 'sentry/components/pagination';
  12. import SearchBar from 'sentry/components/searchBar';
  13. import {Tooltip} from 'sentry/components/tooltip';
  14. import {IconChevron} from 'sentry/icons/iconChevron';
  15. import {t} from 'sentry/locale';
  16. import {space} from 'sentry/styles/space';
  17. import type {Sort} from 'sentry/utils/discover/fields';
  18. import {parseFunction} from 'sentry/utils/discover/fields';
  19. import {formatAbbreviatedNumber, getDuration} from 'sentry/utils/formatters';
  20. import {decodeScalar} from 'sentry/utils/queryString';
  21. import {useLocation} from 'sentry/utils/useLocation';
  22. import useOrganization from 'sentry/utils/useOrganization';
  23. import useProjects from 'sentry/utils/useProjects';
  24. import {PerformanceBadge} from 'sentry/views/performance/browser/webVitals/components/performanceBadge';
  25. import {calculateOpportunity} from 'sentry/views/performance/browser/webVitals/utils/calculateOpportunity';
  26. import {calculatePerformanceScoreFromTableDataRow} from 'sentry/views/performance/browser/webVitals/utils/queries/rawWebVitalsQueries/calculatePerformanceScore';
  27. import {useProjectRawWebVitalsQuery} from 'sentry/views/performance/browser/webVitals/utils/queries/rawWebVitalsQueries/useProjectRawWebVitalsQuery';
  28. import {calculatePerformanceScoreFromStoredTableDataRow} from 'sentry/views/performance/browser/webVitals/utils/queries/storedScoreQueries/calculatePerformanceScoreFromStored';
  29. import {useProjectWebVitalsScoresQuery} from 'sentry/views/performance/browser/webVitals/utils/queries/storedScoreQueries/useProjectWebVitalsScoresQuery';
  30. import {useTransactionWebVitalsQuery} from 'sentry/views/performance/browser/webVitals/utils/queries/useTransactionWebVitalsQuery';
  31. import type {RowWithScoreAndOpportunity} from 'sentry/views/performance/browser/webVitals/utils/types';
  32. import {
  33. SORTABLE_FIELDS,
  34. SORTABLE_SCORE_FIELDS,
  35. } from 'sentry/views/performance/browser/webVitals/utils/types';
  36. import {useReplaceFidWithInpSetting} from 'sentry/views/performance/browser/webVitals/utils/useReplaceFidWithInpSetting';
  37. import {useStoredScoresSetting} from 'sentry/views/performance/browser/webVitals/utils/useStoredScoresSetting';
  38. import {useWebVitalsSort} from 'sentry/views/performance/browser/webVitals/utils/useWebVitalsSort';
  39. type Column = GridColumnHeader<keyof RowWithScoreAndOpportunity>;
  40. const INP_COLUMN: GridColumnOrder<keyof RowWithScoreAndOpportunity> = {
  41. key: 'p75(measurements.inp)',
  42. width: COL_WIDTH_UNDEFINED,
  43. name: 'INP',
  44. };
  45. const COLUMN_ORDER: GridColumnOrder<keyof RowWithScoreAndOpportunity>[] = [
  46. {key: 'transaction', width: COL_WIDTH_UNDEFINED, name: 'Pages'},
  47. {key: 'count()', width: COL_WIDTH_UNDEFINED, name: 'Pageloads'},
  48. {key: 'p75(measurements.lcp)', width: COL_WIDTH_UNDEFINED, name: 'LCP'},
  49. {key: 'p75(measurements.fcp)', width: COL_WIDTH_UNDEFINED, name: 'FCP'},
  50. {key: 'p75(measurements.fid)', width: COL_WIDTH_UNDEFINED, name: 'FID'},
  51. {key: 'p75(measurements.cls)', width: COL_WIDTH_UNDEFINED, name: 'CLS'},
  52. {key: 'p75(measurements.ttfb)', width: COL_WIDTH_UNDEFINED, name: 'TTFB'},
  53. {key: 'totalScore', width: COL_WIDTH_UNDEFINED, name: 'Score'},
  54. {key: 'opportunity', width: COL_WIDTH_UNDEFINED, name: 'Opportunity'},
  55. ];
  56. const MAX_ROWS = 25;
  57. const DEFAULT_SORT: Sort = {
  58. field: 'opportunity_score(measurements.score.total)',
  59. kind: 'desc',
  60. };
  61. export function PagePerformanceTable() {
  62. const organization = useOrganization();
  63. const location = useLocation();
  64. const {projects} = useProjects();
  65. const shouldUseStoredScores = useStoredScoresSetting();
  66. const shouldReplaceFidWithInp = useReplaceFidWithInpSetting();
  67. const columnOrder = useMemo(() => {
  68. const columns = [...COLUMN_ORDER];
  69. if (shouldReplaceFidWithInp) {
  70. columns.splice(4, 1, INP_COLUMN);
  71. }
  72. return columns;
  73. }, [shouldReplaceFidWithInp]);
  74. const query = decodeScalar(location.query.query, '');
  75. const project = useMemo(
  76. () => projects.find(p => p.id === String(location.query.project)),
  77. [projects, location.query.project]
  78. );
  79. let sort = useWebVitalsSort({defaultSort: DEFAULT_SORT});
  80. // Need to map fid back to inp for rendering
  81. if (shouldReplaceFidWithInp && sort.field === 'p75(measurements.fid)') {
  82. sort = {...sort, field: 'p75(measurements.inp)'};
  83. }
  84. const {data: projectData, isLoading: isProjectWebVitalsQueryLoading} =
  85. useProjectRawWebVitalsQuery({transaction: query});
  86. const {data: projectScoresData, isLoading: isProjectScoresLoading} =
  87. useProjectWebVitalsScoresQuery({
  88. transaction: query,
  89. enabled: shouldUseStoredScores,
  90. });
  91. const projectScore = shouldUseStoredScores
  92. ? calculatePerformanceScoreFromStoredTableDataRow(projectScoresData?.data?.[0])
  93. : calculatePerformanceScoreFromTableDataRow(projectData?.data?.[0]);
  94. const {
  95. data,
  96. pageLinks,
  97. isLoading: isTransactionWebVitalsQueryLoading,
  98. } = useTransactionWebVitalsQuery({
  99. limit: MAX_ROWS,
  100. transaction: query,
  101. defaultSort: DEFAULT_SORT,
  102. });
  103. const count = projectData?.data?.[0]?.['count()'] as number;
  104. const scoreCount = projectScoresData?.data?.[0]?.[
  105. 'count_scores(measurements.score.total)'
  106. ] as number;
  107. const tableData: RowWithScoreAndOpportunity[] = data.map(row => ({
  108. ...row,
  109. opportunity: shouldUseStoredScores
  110. ? (((row as RowWithScoreAndOpportunity).opportunity ?? 0) * 100) / scoreCount
  111. : calculateOpportunity(
  112. projectScore.totalScore ?? 0,
  113. count,
  114. row.totalScore,
  115. row['count()']
  116. ),
  117. }));
  118. const getFormattedDuration = (value: number) => {
  119. return getDuration(value, value < 1 ? 0 : 2, true);
  120. };
  121. function renderHeadCell(col: Column) {
  122. function generateSortLink() {
  123. const key =
  124. col.key === 'totalScore'
  125. ? 'avg(measurements.score.total)'
  126. : col.key === 'opportunity'
  127. ? 'opportunity_score(measurements.score.total)'
  128. : col.key;
  129. let newSortDirection: Sort['kind'] = 'desc';
  130. if (sort?.field === key) {
  131. if (sort.kind === 'desc') {
  132. newSortDirection = 'asc';
  133. }
  134. }
  135. const newSort = `${newSortDirection === 'desc' ? '-' : ''}${key}`;
  136. return {
  137. ...location,
  138. query: {...location.query, sort: newSort},
  139. };
  140. }
  141. const sortableFields = shouldUseStoredScores
  142. ? SORTABLE_FIELDS
  143. : SORTABLE_FIELDS.filter(field => !SORTABLE_SCORE_FIELDS.includes(field));
  144. const canSort = (sortableFields as unknown as string[]).includes(col.key);
  145. if (canSort && !['totalScore', 'opportunity'].includes(col.key)) {
  146. return (
  147. <SortLink
  148. align="right"
  149. title={col.name}
  150. direction={sort?.field === col.key ? sort.kind : undefined}
  151. canSort={canSort}
  152. generateSortLink={generateSortLink}
  153. />
  154. );
  155. }
  156. if (col.key === 'totalScore') {
  157. return (
  158. <AlignCenter>
  159. <StyledTooltip
  160. isHoverable
  161. title={
  162. <span>
  163. {t('The overall performance rating of this page.')}
  164. <br />
  165. <ExternalLink href="https://docs.sentry.io/product/performance/web-vitals/#performance-score">
  166. {t('How is this calculated?')}
  167. </ExternalLink>
  168. </span>
  169. }
  170. >
  171. <SortLink
  172. title={<TooltipHeader>{t('Perf Score')}</TooltipHeader>}
  173. direction={sort?.field === col.key ? sort.kind : undefined}
  174. canSort={canSort}
  175. generateSortLink={generateSortLink}
  176. align={undefined}
  177. />
  178. </StyledTooltip>
  179. </AlignCenter>
  180. );
  181. }
  182. if (col.key === 'opportunity') {
  183. return (
  184. <AlignRight>
  185. <StyledTooltip
  186. isHoverable
  187. title={
  188. <span>
  189. {t(
  190. "A number rating how impactful a performance improvement on this page would be to your application's overall Performance Score."
  191. )}
  192. <br />
  193. <ExternalLink href="https://docs.sentry.io/product/performance/web-vitals/#opportunity">
  194. {t('How is this calculated?')}
  195. </ExternalLink>
  196. </span>
  197. }
  198. >
  199. <SortLink
  200. align="right"
  201. title={<TooltipHeader>{col.name}</TooltipHeader>}
  202. direction={sort?.field === col.key ? sort.kind : undefined}
  203. canSort={canSort}
  204. generateSortLink={generateSortLink}
  205. />
  206. </StyledTooltip>
  207. </AlignRight>
  208. );
  209. }
  210. return <span>{col.name}</span>;
  211. }
  212. function renderBodyCell(col: Column, row: RowWithScoreAndOpportunity) {
  213. const {key} = col;
  214. if (key === 'totalScore') {
  215. return (
  216. <AlignCenter>
  217. <PerformanceBadge score={row.totalScore} />
  218. </AlignCenter>
  219. );
  220. }
  221. if (key === 'count()') {
  222. return <AlignRight>{formatAbbreviatedNumber(row['count()'])}</AlignRight>;
  223. }
  224. if (key === 'transaction') {
  225. return (
  226. <NoOverflow>
  227. {project && (
  228. <StyledProjectAvatar
  229. project={project}
  230. direction="left"
  231. size={16}
  232. hasTooltip
  233. tooltip={project.slug}
  234. />
  235. )}
  236. <Link
  237. to={{
  238. ...location,
  239. ...(organization.features.includes(
  240. 'starfish-browser-webvitals-pageoverview-v2'
  241. )
  242. ? {pathname: `${location.pathname}overview/`}
  243. : {}),
  244. query: {
  245. ...location.query,
  246. transaction: row.transaction,
  247. query: undefined,
  248. cursor: undefined,
  249. },
  250. }}
  251. >
  252. {row.transaction}
  253. </Link>
  254. </NoOverflow>
  255. );
  256. }
  257. if (
  258. [
  259. 'p75(measurements.fcp)',
  260. 'p75(measurements.lcp)',
  261. 'p75(measurements.ttfb)',
  262. 'p75(measurements.fid)',
  263. 'p75(measurements.inp)',
  264. ].includes(key)
  265. ) {
  266. const measurement = parseFunction(key)?.arguments?.[0];
  267. const func = shouldUseStoredScores ? 'count_scores' : 'count_web_vitals';
  268. const args = [
  269. shouldUseStoredScores
  270. ? measurement?.replace('measurements.', 'measurements.score.')
  271. : measurement,
  272. ...(shouldUseStoredScores ? [] : ['any']),
  273. ];
  274. const countWebVitalKey = `${func}(${args.join(', ')})`;
  275. const countWebVital = row[countWebVitalKey];
  276. if (measurement === undefined || countWebVital === 0) {
  277. return (
  278. <AlignRight>
  279. <NoValue>{' \u2014 '}</NoValue>
  280. </AlignRight>
  281. );
  282. }
  283. return <AlignRight>{getFormattedDuration((row[key] as number) / 1000)}</AlignRight>;
  284. }
  285. if (key === 'p75(measurements.cls)') {
  286. const countWebVitalKey = shouldUseStoredScores
  287. ? 'count_scores(measurements.score.cls)'
  288. : 'count_web_vitals(measurements.cls, any)';
  289. const countWebVital = row[countWebVitalKey];
  290. if (countWebVital === 0) {
  291. return (
  292. <AlignRight>
  293. <NoValue>{' \u2014 '}</NoValue>
  294. </AlignRight>
  295. );
  296. }
  297. return <AlignRight>{Math.round((row[key] as number) * 100) / 100}</AlignRight>;
  298. }
  299. if (key === 'opportunity') {
  300. if (row.opportunity !== undefined) {
  301. return (
  302. <AlignRight>{Math.round((row.opportunity as number) * 100) / 100}</AlignRight>
  303. );
  304. }
  305. return null;
  306. }
  307. return <NoOverflow>{row[key]}</NoOverflow>;
  308. }
  309. const handleSearch = (newQuery: string) => {
  310. browserHistory.push({
  311. ...location,
  312. query: {
  313. ...location.query,
  314. query: newQuery === '' ? undefined : `*${newQuery}*`,
  315. cursor: undefined,
  316. },
  317. });
  318. };
  319. return (
  320. <span>
  321. <SearchBarContainer>
  322. <StyledSearchBar
  323. placeholder={t('Search for more Pages')}
  324. onSearch={handleSearch}
  325. />
  326. <StyledPagination
  327. pageLinks={pageLinks}
  328. disabled={
  329. (shouldUseStoredScores && isProjectScoresLoading) ||
  330. isProjectWebVitalsQueryLoading ||
  331. isTransactionWebVitalsQueryLoading
  332. }
  333. size="md"
  334. />
  335. {/* The Pagination component disappears if pageLinks is not defined,
  336. which happens any time the table data is loading. So we render a
  337. disabled button bar if pageLinks is not defined to minimize ui shifting */}
  338. {!pageLinks && (
  339. <Wrapper>
  340. <ButtonBar merged>
  341. <Button
  342. icon={<IconChevron direction="left" />}
  343. disabled
  344. aria-label={t('Previous')}
  345. />
  346. <Button
  347. icon={<IconChevron direction="right" />}
  348. disabled
  349. aria-label={t('Next')}
  350. />
  351. </ButtonBar>
  352. </Wrapper>
  353. )}
  354. </SearchBarContainer>
  355. <GridContainer>
  356. <GridEditable
  357. isLoading={
  358. (shouldUseStoredScores && isProjectScoresLoading) ||
  359. isProjectWebVitalsQueryLoading ||
  360. isTransactionWebVitalsQueryLoading
  361. }
  362. columnOrder={columnOrder}
  363. columnSortBy={[]}
  364. data={tableData}
  365. grid={{
  366. renderHeadCell,
  367. renderBodyCell,
  368. }}
  369. location={location}
  370. />
  371. </GridContainer>
  372. </span>
  373. );
  374. }
  375. const NoOverflow = styled('span')`
  376. overflow: hidden;
  377. text-overflow: ellipsis;
  378. white-space: nowrap;
  379. `;
  380. const AlignRight = styled('span')<{color?: string}>`
  381. text-align: right;
  382. width: 100%;
  383. ${p => (p.color ? `color: ${p.color};` : '')}
  384. `;
  385. const AlignCenter = styled('span')`
  386. display: block;
  387. margin: auto;
  388. text-align: center;
  389. width: 100%;
  390. `;
  391. const StyledProjectAvatar = styled(ProjectAvatar)`
  392. top: ${space(0.25)};
  393. position: relative;
  394. padding-right: ${space(1)};
  395. `;
  396. const SearchBarContainer = styled('div')`
  397. display: flex;
  398. margin-bottom: ${space(1)};
  399. gap: ${space(1)};
  400. `;
  401. const GridContainer = styled('div')`
  402. margin-bottom: ${space(1)};
  403. `;
  404. const TooltipHeader = styled('span')`
  405. ${p => p.theme.tooltipUnderline()};
  406. `;
  407. const StyledSearchBar = styled(SearchBar)`
  408. flex-grow: 1;
  409. `;
  410. const StyledPagination = styled(Pagination)`
  411. margin: 0;
  412. `;
  413. const Wrapper = styled('div')`
  414. display: flex;
  415. align-items: center;
  416. justify-content: flex-end;
  417. margin: 0;
  418. `;
  419. const StyledTooltip = styled(Tooltip)`
  420. top: 1px;
  421. position: relative;
  422. `;
  423. const NoValue = styled('span')`
  424. color: ${p => p.theme.gray300};
  425. `;