pagePerformanceTable.tsx 14 KB

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