webVitalsDetailPanel.tsx 9.5 KB

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