pagePerformanceTable.tsx 13 KB

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