pagePerformanceTable.tsx 14 KB

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