pagePerformanceTable.tsx 15 KB

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