webVitalsDetailPanel.tsx 9.5 KB

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