pagePerformanceTable.tsx 12 KB

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