pagePerformanceTable.tsx 12 KB

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