webVitalsDetailPanel.tsx 10 KB

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