pagePerformanceTable.tsx 12 KB

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