webVitalsDetailPanel.tsx 11 KB

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