pagePerformanceTable.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  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 = [measurement, ...(shouldUseStoredScores ? [] : ['any'])];
  248. const countWebVitalKey = `${func}(${args.join(',')})`;
  249. const countWebVital = row[countWebVitalKey];
  250. if (measurement === undefined || countWebVital === 0) {
  251. return (
  252. <AlignRight>
  253. <NoValue>{' \u2014 '}</NoValue>
  254. </AlignRight>
  255. );
  256. }
  257. return <AlignRight>{getFormattedDuration((row[key] as number) / 1000)}</AlignRight>;
  258. }
  259. if (key === 'p75(measurements.cls)') {
  260. const countWebVitalKey = shouldUseStoredScores
  261. ? 'count_scores(measurements.score.cls)'
  262. : 'count_web_vitals(measurements.cls, any)';
  263. const countWebVital = row[countWebVitalKey];
  264. if (countWebVital === 0) {
  265. return (
  266. <AlignRight>
  267. <NoValue>{' \u2014 '}</NoValue>
  268. </AlignRight>
  269. );
  270. }
  271. return <AlignRight>{Math.round((row[key] as number) * 100) / 100}</AlignRight>;
  272. }
  273. if (key === 'opportunity') {
  274. if (row.opportunity !== undefined) {
  275. return (
  276. <AlignRight>{Math.round((row.opportunity as number) * 100) / 100}</AlignRight>
  277. );
  278. }
  279. return null;
  280. }
  281. return <NoOverflow>{row[key]}</NoOverflow>;
  282. }
  283. const handleSearch = (newQuery: string) => {
  284. browserHistory.push({
  285. ...location,
  286. query: {
  287. ...location.query,
  288. query: newQuery === '' ? undefined : `*${newQuery}*`,
  289. cursor: undefined,
  290. },
  291. });
  292. };
  293. return (
  294. <span>
  295. <SearchBarContainer>
  296. <StyledSearchBar
  297. placeholder={t('Search for more Pages')}
  298. onSearch={handleSearch}
  299. />
  300. <StyledPagination
  301. pageLinks={pageLinks}
  302. disabled={
  303. (shouldUseStoredScores && isProjectScoresLoading) ||
  304. isProjectWebVitalsQueryLoading ||
  305. isTransactionWebVitalsQueryLoading
  306. }
  307. size="md"
  308. />
  309. {/* The Pagination component disappears if pageLinks is not defined,
  310. which happens any time the table data is loading. So we render a
  311. disabled button bar if pageLinks is not defined to minimize ui shifting */}
  312. {!pageLinks && (
  313. <Wrapper>
  314. <ButtonBar merged>
  315. <Button
  316. icon={<IconChevron direction="left" />}
  317. disabled
  318. aria-label={t('Previous')}
  319. />
  320. <Button
  321. icon={<IconChevron direction="right" />}
  322. disabled
  323. aria-label={t('Next')}
  324. />
  325. </ButtonBar>
  326. </Wrapper>
  327. )}
  328. </SearchBarContainer>
  329. <GridContainer>
  330. <GridEditable
  331. isLoading={
  332. (shouldUseStoredScores && isProjectScoresLoading) ||
  333. isProjectWebVitalsQueryLoading ||
  334. isTransactionWebVitalsQueryLoading
  335. }
  336. columnOrder={columnOrder}
  337. columnSortBy={[]}
  338. data={tableData}
  339. grid={{
  340. renderHeadCell,
  341. renderBodyCell,
  342. }}
  343. location={location}
  344. />
  345. </GridContainer>
  346. </span>
  347. );
  348. }
  349. const NoOverflow = styled('span')`
  350. overflow: hidden;
  351. text-overflow: ellipsis;
  352. white-space: nowrap;
  353. `;
  354. const AlignRight = styled('span')<{color?: string}>`
  355. text-align: right;
  356. width: 100%;
  357. ${p => (p.color ? `color: ${p.color};` : '')}
  358. `;
  359. const AlignCenter = styled('span')`
  360. display: block;
  361. margin: auto;
  362. text-align: center;
  363. width: 100%;
  364. `;
  365. const StyledProjectAvatar = styled(ProjectAvatar)`
  366. top: ${space(0.25)};
  367. position: relative;
  368. padding-right: ${space(1)};
  369. `;
  370. const SearchBarContainer = styled('div')`
  371. display: flex;
  372. margin-bottom: ${space(1)};
  373. gap: ${space(1)};
  374. `;
  375. const GridContainer = styled('div')`
  376. margin-bottom: ${space(1)};
  377. `;
  378. const TooltipHeader = styled('span')`
  379. ${p => p.theme.tooltipUnderline()};
  380. `;
  381. const StyledSearchBar = styled(SearchBar)`
  382. flex-grow: 1;
  383. `;
  384. const StyledPagination = styled(Pagination)`
  385. margin: 0;
  386. `;
  387. const Wrapper = styled('div')`
  388. display: flex;
  389. align-items: center;
  390. justify-content: flex-end;
  391. margin: 0;
  392. `;
  393. const StyledTooltip = styled(Tooltip)`
  394. top: 1px;
  395. position: relative;
  396. `;
  397. const NoValue = styled('span')`
  398. color: ${p => p.theme.gray300};
  399. `;