webVitalsDetailPanel.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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 {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. return <AlignRight>{col.name}</AlignRight>;
  167. };
  168. const getFormattedDuration = (value: number) => {
  169. if (value < 1000) {
  170. return getDuration(value / 1000, 0, true);
  171. }
  172. return getDuration(value / 1000, 2, true);
  173. };
  174. const renderBodyCell = (col: Column, row: RowWithScoreAndOpportunity) => {
  175. const {key} = col;
  176. if (key === 'score') {
  177. return (
  178. <AlignCenter>
  179. <PerformanceBadge score={row[`${webVital}Score`]} />
  180. </AlignCenter>
  181. );
  182. }
  183. if (col.key === 'webVital') {
  184. let value: string | number = row[mapWebVitalToColumn(webVital)];
  185. if (webVital && ['lcp', 'fcp', 'ttfb', 'fid'].includes(webVital)) {
  186. value = getFormattedDuration(value);
  187. } else if (webVital === 'cls') {
  188. value = value?.toFixed(2);
  189. }
  190. return <AlignRight>{value}</AlignRight>;
  191. }
  192. if (key === 'transaction') {
  193. return (
  194. <NoOverflow>
  195. <Link
  196. to={{
  197. ...location,
  198. ...(organization.features.includes(
  199. 'starfish-browser-webvitals-pageoverview-v2'
  200. )
  201. ? {pathname: `${location.pathname}overview/`}
  202. : {}),
  203. query: {
  204. ...location.query,
  205. transaction: row.transaction,
  206. webVital,
  207. },
  208. }}
  209. >
  210. {row.transaction}
  211. </Link>
  212. </NoOverflow>
  213. );
  214. }
  215. return <AlignRight>{row[key]}</AlignRight>;
  216. };
  217. const webVitalScore = projectScore[`${webVital}Score`];
  218. const webVitalValue = projectData?.data?.[0]?.[mapWebVitalToColumn(webVital)] as
  219. | number
  220. | undefined;
  221. return (
  222. <PageAlertProvider>
  223. <DetailPanel detailKey={detailKey ?? undefined} onClose={onClose}>
  224. {webVital && (
  225. <WebVitalDescription
  226. value={
  227. webVitalValue !== undefined
  228. ? webVital !== 'cls'
  229. ? getDuration(webVitalValue / 1000, 2, true)
  230. : webVitalValue?.toFixed(2)
  231. : undefined
  232. }
  233. webVital={webVital}
  234. score={webVitalScore}
  235. />
  236. )}
  237. <ChartContainer>
  238. {webVital && <WebVitalStatusLineChart webVitalSeries={webVitalData} />}
  239. </ChartContainer>
  240. <TableContainer>
  241. <GridEditable
  242. data={dataByOpportunity}
  243. isLoading={isLoading}
  244. columnOrder={columnOrder}
  245. columnSortBy={[sort]}
  246. grid={{
  247. renderHeadCell,
  248. renderBodyCell,
  249. }}
  250. location={location}
  251. />
  252. </TableContainer>
  253. <PageAlert />
  254. </DetailPanel>
  255. </PageAlertProvider>
  256. );
  257. }
  258. const mapWebVitalToColumn = (webVital?: WebVitals | null) => {
  259. switch (webVital) {
  260. case 'lcp':
  261. return 'p75(measurements.lcp)';
  262. case 'fcp':
  263. return 'p75(measurements.fcp)';
  264. case 'cls':
  265. return 'p75(measurements.cls)';
  266. case 'ttfb':
  267. return 'p75(measurements.ttfb)';
  268. case 'fid':
  269. return 'p75(measurements.fid)';
  270. default:
  271. return 'count()';
  272. }
  273. };
  274. const NoOverflow = styled('span')`
  275. overflow: hidden;
  276. text-overflow: ellipsis;
  277. `;
  278. const AlignRight = styled('span')<{color?: string}>`
  279. text-align: right;
  280. width: 100%;
  281. ${p => (p.color ? `color: ${p.color};` : '')}
  282. `;
  283. const ChartContainer = styled('div')`
  284. position: relative;
  285. flex: 1;
  286. `;
  287. const AlignCenter = styled('span')`
  288. text-align: center;
  289. width: 100%;
  290. `;
  291. const OpportunityHeader = styled('span')`
  292. ${p => p.theme.tooltipUnderline()};
  293. `;
  294. const TableContainer = styled('div')`
  295. margin-bottom: 80px;
  296. `;