pagePerformanceTable.tsx 12 KB

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