webVitalsDetailPanel.tsx 11 KB

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