pagePerformanceTable.tsx 12 KB

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