webVitalsDetailPanel.tsx 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. import {useMemo} from 'react';
  2. import {Link} from 'react-router';
  3. import styled from '@emotion/styled';
  4. import type {LineChartSeries} from 'sentry/components/charts/lineChart';
  5. import type {
  6. GridColumnHeader,
  7. GridColumnOrder,
  8. GridColumnSortBy,
  9. } from 'sentry/components/gridEditable';
  10. import GridEditable, {COL_WIDTH_UNDEFINED} from 'sentry/components/gridEditable';
  11. import ExternalLink from 'sentry/components/links/externalLink';
  12. import {Tooltip} from 'sentry/components/tooltip';
  13. import {t, tct} from 'sentry/locale';
  14. import {formatAbbreviatedNumber, getDuration} from 'sentry/utils/formatters';
  15. import {PageAlert, PageAlertProvider} from 'sentry/utils/performance/contexts/pageAlert';
  16. import {useLocation} from 'sentry/utils/useLocation';
  17. import {PerformanceBadge} from 'sentry/views/performance/browser/webVitals/components/performanceBadge';
  18. import {WebVitalDescription} from 'sentry/views/performance/browser/webVitals/components/webVitalDescription';
  19. import {WebVitalStatusLineChart} from 'sentry/views/performance/browser/webVitals/components/webVitalStatusLineChart';
  20. import {useProjectRawWebVitalsQuery} from 'sentry/views/performance/browser/webVitals/utils/queries/rawWebVitalsQueries/useProjectRawWebVitalsQuery';
  21. import {useProjectRawWebVitalsValuesTimeseriesQuery} from 'sentry/views/performance/browser/webVitals/utils/queries/rawWebVitalsQueries/useProjectRawWebVitalsValuesTimeseriesQuery';
  22. import {calculatePerformanceScoreFromStoredTableDataRow} from 'sentry/views/performance/browser/webVitals/utils/queries/storedScoreQueries/calculatePerformanceScoreFromStored';
  23. import {useProjectWebVitalsScoresQuery} from 'sentry/views/performance/browser/webVitals/utils/queries/storedScoreQueries/useProjectWebVitalsScoresQuery';
  24. import {useTransactionWebVitalsQuery} from 'sentry/views/performance/browser/webVitals/utils/queries/useTransactionWebVitalsQuery';
  25. import type {
  26. Row,
  27. RowWithScoreAndOpportunity,
  28. WebVitals,
  29. } from 'sentry/views/performance/browser/webVitals/utils/types';
  30. import DetailPanel from 'sentry/views/starfish/components/detailPanel';
  31. type Column = GridColumnHeader;
  32. const columnOrder: GridColumnOrder[] = [
  33. {key: 'transaction', width: COL_WIDTH_UNDEFINED, name: 'Pages'},
  34. {key: 'count', width: COL_WIDTH_UNDEFINED, name: 'Pageloads'},
  35. {key: 'webVital', width: COL_WIDTH_UNDEFINED, name: 'Web Vital'},
  36. {key: 'score', width: COL_WIDTH_UNDEFINED, name: 'Score'},
  37. {key: 'opportunity', width: COL_WIDTH_UNDEFINED, name: 'Opportunity'},
  38. ];
  39. const sort: GridColumnSortBy<keyof Row> = {key: 'count()', order: 'desc'};
  40. const MAX_ROWS = 10;
  41. export function WebVitalsDetailPanel({
  42. webVital,
  43. onClose,
  44. }: {
  45. onClose: () => void;
  46. webVital: WebVitals | null;
  47. }) {
  48. const location = useLocation();
  49. const {data: projectData} = useProjectRawWebVitalsQuery({});
  50. const {data: projectScoresData} = useProjectWebVitalsScoresQuery({
  51. weightWebVital: webVital ?? 'total',
  52. });
  53. const projectScore = calculatePerformanceScoreFromStoredTableDataRow(
  54. projectScoresData?.data?.[0]
  55. );
  56. const {data, isLoading} = useTransactionWebVitalsQuery({
  57. limit: 100,
  58. webVital: webVital ?? 'total',
  59. ...(webVital
  60. ? {
  61. query: `count_scores(measurements.score.${webVital}):>0`,
  62. defaultSort: {
  63. field: `opportunity_score(measurements.score.${webVital})`,
  64. kind: 'desc',
  65. },
  66. }
  67. : {}),
  68. enabled: webVital !== null,
  69. sortName: 'webVitalsDetailPanelSort',
  70. });
  71. const dataByOpportunity = useMemo(() => {
  72. if (!data) {
  73. return [];
  74. }
  75. const sumWeights = projectScoresData?.data?.[0]?.[
  76. `sum(measurements.score.weight.${webVital})`
  77. ] as number;
  78. return data
  79. .map(row => ({
  80. ...row,
  81. opportunity:
  82. Math.round(
  83. (((row as RowWithScoreAndOpportunity).opportunity ?? 0) * 100 * 100) /
  84. sumWeights
  85. ) / 100,
  86. }))
  87. .sort((a, b) => {
  88. if (a.opportunity === undefined) {
  89. return 1;
  90. }
  91. if (b.opportunity === undefined) {
  92. return -1;
  93. }
  94. return b.opportunity - a.opportunity;
  95. })
  96. .slice(0, MAX_ROWS);
  97. }, [data, projectScoresData?.data, webVital]);
  98. const {data: timeseriesData, isLoading: isTimeseriesLoading} =
  99. useProjectRawWebVitalsValuesTimeseriesQuery({});
  100. const webVitalData: LineChartSeries = {
  101. data:
  102. !isTimeseriesLoading && webVital
  103. ? timeseriesData?.[webVital].map(({name, value}) => ({
  104. name,
  105. value,
  106. }))
  107. : [],
  108. seriesName: webVital ?? '',
  109. };
  110. const detailKey = webVital;
  111. const renderHeadCell = (col: Column) => {
  112. if (col.key === 'transaction') {
  113. return <NoOverflow>{col.name}</NoOverflow>;
  114. }
  115. if (col.key === 'webVital') {
  116. return <AlignRight>{`${webVital} P75`}</AlignRight>;
  117. }
  118. if (col.key === 'score') {
  119. return <AlignCenter>{`${webVital} ${col.name}`}</AlignCenter>;
  120. }
  121. if (col.key === 'opportunity') {
  122. return (
  123. <Tooltip
  124. isHoverable
  125. title={
  126. <span>
  127. {tct(
  128. "A number rating how impactful a performance improvement on this page would be to your application's [webVital] Performance Score.",
  129. {webVital: webVital?.toUpperCase() ?? ''}
  130. )}
  131. <br />
  132. <ExternalLink href="https://docs.sentry.io/product/performance/web-vitals/#opportunity">
  133. {t('How is this calculated?')}
  134. </ExternalLink>
  135. </span>
  136. }
  137. >
  138. <OpportunityHeader>{col.name}</OpportunityHeader>
  139. </Tooltip>
  140. );
  141. }
  142. if (col.key === 'count') {
  143. if (webVital === 'inp') {
  144. return <AlignRight>{t('Interactions')}</AlignRight>;
  145. }
  146. }
  147. return <AlignRight>{col.name}</AlignRight>;
  148. };
  149. const getFormattedDuration = (value: number) => {
  150. if (value < 1000) {
  151. return getDuration(value / 1000, 0, true);
  152. }
  153. return getDuration(value / 1000, 2, true);
  154. };
  155. const renderBodyCell = (col: Column, row: RowWithScoreAndOpportunity) => {
  156. const {key} = col;
  157. if (key === 'score') {
  158. return (
  159. <AlignCenter>
  160. <PerformanceBadge score={row[`${webVital}Score`]} />
  161. </AlignCenter>
  162. );
  163. }
  164. if (col.key === 'webVital') {
  165. let value: string | number = row[mapWebVitalToColumn(webVital)];
  166. if (webVital && ['lcp', 'fcp', 'ttfb', 'fid', 'inp'].includes(webVital)) {
  167. value = getFormattedDuration(value);
  168. } else if (webVital === 'cls') {
  169. value = value?.toFixed(2);
  170. }
  171. return <AlignRight>{value}</AlignRight>;
  172. }
  173. if (key === 'transaction') {
  174. return (
  175. <NoOverflow>
  176. <Link
  177. to={{
  178. ...location,
  179. pathname: `${location.pathname}overview/`,
  180. query: {
  181. ...location.query,
  182. transaction: row.transaction,
  183. webVital,
  184. },
  185. }}
  186. >
  187. {row.transaction}
  188. </Link>
  189. </NoOverflow>
  190. );
  191. }
  192. if (key === 'count') {
  193. const count =
  194. webVital === 'inp' ? row['count_scores(measurements.score.inp)'] : row['count()'];
  195. return <AlignRight>{formatAbbreviatedNumber(count)}</AlignRight>;
  196. }
  197. return <AlignRight>{row[key]}</AlignRight>;
  198. };
  199. const webVitalScore = projectScore[`${webVital}Score`];
  200. const webVitalValue = projectData?.data?.[0]?.[mapWebVitalToColumn(webVital)] as
  201. | number
  202. | undefined;
  203. return (
  204. <PageAlertProvider>
  205. <DetailPanel detailKey={detailKey ?? undefined} onClose={onClose}>
  206. {webVital && (
  207. <WebVitalDescription
  208. value={
  209. webVitalValue !== undefined
  210. ? webVital !== 'cls'
  211. ? getDuration(webVitalValue / 1000, 2, true)
  212. : webVitalValue?.toFixed(2)
  213. : undefined
  214. }
  215. webVital={webVital}
  216. score={webVitalScore}
  217. />
  218. )}
  219. <ChartContainer>
  220. {webVital && <WebVitalStatusLineChart webVitalSeries={webVitalData} />}
  221. </ChartContainer>
  222. <TableContainer>
  223. <GridEditable
  224. data={dataByOpportunity}
  225. isLoading={isLoading}
  226. columnOrder={columnOrder}
  227. columnSortBy={[sort]}
  228. grid={{
  229. renderHeadCell,
  230. renderBodyCell,
  231. }}
  232. location={location}
  233. />
  234. </TableContainer>
  235. <PageAlert />
  236. </DetailPanel>
  237. </PageAlertProvider>
  238. );
  239. }
  240. const mapWebVitalToColumn = (webVital?: WebVitals | null) => {
  241. switch (webVital) {
  242. case 'lcp':
  243. return 'p75(measurements.lcp)';
  244. case 'fcp':
  245. return 'p75(measurements.fcp)';
  246. case 'cls':
  247. return 'p75(measurements.cls)';
  248. case 'ttfb':
  249. return 'p75(measurements.ttfb)';
  250. case 'fid':
  251. return 'p75(measurements.fid)';
  252. case 'inp':
  253. return 'p75(measurements.inp)';
  254. default:
  255. return 'count()';
  256. }
  257. };
  258. const NoOverflow = styled('span')`
  259. overflow: hidden;
  260. text-overflow: ellipsis;
  261. `;
  262. const AlignRight = styled('span')<{color?: string}>`
  263. text-align: right;
  264. width: 100%;
  265. ${p => (p.color ? `color: ${p.color};` : '')}
  266. `;
  267. const ChartContainer = styled('div')`
  268. position: relative;
  269. flex: 1;
  270. `;
  271. const AlignCenter = styled('span')`
  272. text-align: center;
  273. width: 100%;
  274. `;
  275. const OpportunityHeader = styled('span')`
  276. ${p => p.theme.tooltipUnderline()};
  277. `;
  278. const TableContainer = styled('div')`
  279. margin-bottom: 80px;
  280. `;