pagePerformanceTable.tsx 12 KB

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