pagePerformanceTable.tsx 12 KB

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