webVitalsDetailPanel.tsx 10 KB

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