pagePerformanceTable.tsx 11 KB

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