pagePerformanceTable.tsx 13 KB

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