webVitalsDetailPanel.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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. webVital: 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. sortName: 'webVitalsDetailPanelSort',
  81. });
  82. const dataByOpportunity = useMemo(() => {
  83. if (!data) {
  84. return [];
  85. }
  86. const count = projectData?.data?.[0]?.['count()'] as number;
  87. const sumWeights = projectScoresData?.data?.[0]?.[
  88. `sum(measurements.score.weight.${webVital})`
  89. ] as number;
  90. return data
  91. .map(row => ({
  92. ...row,
  93. opportunity: shouldUseStoredScores
  94. ? Math.round(
  95. (((row as RowWithScoreAndOpportunity).opportunity ?? 0) * 100 * 100) /
  96. sumWeights
  97. ) / 100
  98. : calculateOpportunity(
  99. projectScore[`${webVital}Score`],
  100. count,
  101. row[`${webVital}Score`],
  102. row['count()']
  103. ),
  104. }))
  105. .sort((a, b) => {
  106. if (a.opportunity === undefined) {
  107. return 1;
  108. }
  109. if (b.opportunity === undefined) {
  110. return -1;
  111. }
  112. return b.opportunity - a.opportunity;
  113. })
  114. .slice(0, MAX_ROWS);
  115. }, [
  116. data,
  117. projectData?.data,
  118. projectScore,
  119. projectScoresData?.data,
  120. shouldUseStoredScores,
  121. webVital,
  122. ]);
  123. const {data: timeseriesData, isLoading: isTimeseriesLoading} =
  124. useProjectRawWebVitalsValuesTimeseriesQuery({});
  125. const webVitalData: LineChartSeries = {
  126. data:
  127. !isTimeseriesLoading && webVital
  128. ? timeseriesData?.[webVital].map(({name, value}) => ({
  129. name,
  130. value,
  131. }))
  132. : [],
  133. seriesName: webVital ?? '',
  134. };
  135. const detailKey = webVital;
  136. const renderHeadCell = (col: Column) => {
  137. if (col.key === 'transaction') {
  138. return <NoOverflow>{col.name}</NoOverflow>;
  139. }
  140. if (col.key === 'webVital') {
  141. return <AlignRight>{`${webVital} P75`}</AlignRight>;
  142. }
  143. if (col.key === 'score') {
  144. return <AlignCenter>{`${webVital} ${col.name}`}</AlignCenter>;
  145. }
  146. if (col.key === 'opportunity') {
  147. return (
  148. <Tooltip
  149. isHoverable
  150. title={
  151. <span>
  152. {tct(
  153. "A number rating how impactful a performance improvement on this page would be to your application's [webVital] Performance Score.",
  154. {webVital: webVital?.toUpperCase() ?? ''}
  155. )}
  156. <br />
  157. <ExternalLink href="https://docs.sentry.io/product/performance/web-vitals/#opportunity">
  158. {t('How is this calculated?')}
  159. </ExternalLink>
  160. </span>
  161. }
  162. >
  163. <OpportunityHeader>{col.name}</OpportunityHeader>
  164. </Tooltip>
  165. );
  166. }
  167. if (col.key === 'count') {
  168. if (webVital === 'inp') {
  169. return <AlignRight>{t('Interactions')}</AlignRight>;
  170. }
  171. }
  172. return <AlignRight>{col.name}</AlignRight>;
  173. };
  174. const getFormattedDuration = (value: number) => {
  175. if (value < 1000) {
  176. return getDuration(value / 1000, 0, true);
  177. }
  178. return getDuration(value / 1000, 2, true);
  179. };
  180. const renderBodyCell = (col: Column, row: RowWithScoreAndOpportunity) => {
  181. const {key} = col;
  182. if (key === 'score') {
  183. return (
  184. <AlignCenter>
  185. <PerformanceBadge score={row[`${webVital}Score`]} />
  186. </AlignCenter>
  187. );
  188. }
  189. if (col.key === 'webVital') {
  190. let value: string | number = row[mapWebVitalToColumn(webVital)];
  191. if (webVital && ['lcp', 'fcp', 'ttfb', 'fid', 'inp'].includes(webVital)) {
  192. value = getFormattedDuration(value);
  193. } else if (webVital === 'cls') {
  194. value = value?.toFixed(2);
  195. }
  196. return <AlignRight>{value}</AlignRight>;
  197. }
  198. if (key === 'transaction') {
  199. return (
  200. <NoOverflow>
  201. <Link
  202. to={{
  203. ...location,
  204. ...(organization.features.includes(
  205. 'starfish-browser-webvitals-pageoverview-v2'
  206. )
  207. ? {pathname: `${location.pathname}overview/`}
  208. : {}),
  209. query: {
  210. ...location.query,
  211. transaction: row.transaction,
  212. webVital,
  213. },
  214. }}
  215. >
  216. {row.transaction}
  217. </Link>
  218. </NoOverflow>
  219. );
  220. }
  221. if (key === 'count') {
  222. const count =
  223. webVital === 'inp' ? row['count_scores(measurements.score.inp)'] : row['count()'];
  224. return <AlignRight>{formatAbbreviatedNumber(count)}</AlignRight>;
  225. }
  226. return <AlignRight>{row[key]}</AlignRight>;
  227. };
  228. const webVitalScore = projectScore[`${webVital}Score`];
  229. const webVitalValue = projectData?.data?.[0]?.[mapWebVitalToColumn(webVital)] as
  230. | number
  231. | undefined;
  232. return (
  233. <PageAlertProvider>
  234. <DetailPanel detailKey={detailKey ?? undefined} onClose={onClose}>
  235. {webVital && (
  236. <WebVitalDescription
  237. value={
  238. webVitalValue !== undefined
  239. ? webVital !== 'cls'
  240. ? getDuration(webVitalValue / 1000, 2, true)
  241. : webVitalValue?.toFixed(2)
  242. : undefined
  243. }
  244. webVital={webVital}
  245. score={webVitalScore}
  246. />
  247. )}
  248. <ChartContainer>
  249. {webVital && <WebVitalStatusLineChart webVitalSeries={webVitalData} />}
  250. </ChartContainer>
  251. <TableContainer>
  252. <GridEditable
  253. data={dataByOpportunity}
  254. isLoading={isLoading}
  255. columnOrder={columnOrder}
  256. columnSortBy={[sort]}
  257. grid={{
  258. renderHeadCell,
  259. renderBodyCell,
  260. }}
  261. location={location}
  262. />
  263. </TableContainer>
  264. <PageAlert />
  265. </DetailPanel>
  266. </PageAlertProvider>
  267. );
  268. }
  269. const mapWebVitalToColumn = (webVital?: WebVitals | null) => {
  270. switch (webVital) {
  271. case 'lcp':
  272. return 'p75(measurements.lcp)';
  273. case 'fcp':
  274. return 'p75(measurements.fcp)';
  275. case 'cls':
  276. return 'p75(measurements.cls)';
  277. case 'ttfb':
  278. return 'p75(measurements.ttfb)';
  279. case 'fid':
  280. return 'p75(measurements.fid)';
  281. case 'inp':
  282. return 'p75(measurements.inp)';
  283. default:
  284. return 'count()';
  285. }
  286. };
  287. const NoOverflow = styled('span')`
  288. overflow: hidden;
  289. text-overflow: ellipsis;
  290. `;
  291. const AlignRight = styled('span')<{color?: string}>`
  292. text-align: right;
  293. width: 100%;
  294. ${p => (p.color ? `color: ${p.color};` : '')}
  295. `;
  296. const ChartContainer = styled('div')`
  297. position: relative;
  298. flex: 1;
  299. `;
  300. const AlignCenter = styled('span')`
  301. text-align: center;
  302. width: 100%;
  303. `;
  304. const OpportunityHeader = styled('span')`
  305. ${p => p.theme.tooltipUnderline()};
  306. `;
  307. const TableContainer = styled('div')`
  308. margin-bottom: 80px;
  309. `;