webVitalsDetailPanel.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. import {useEffect, 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 {trackAnalytics} from 'sentry/utils/analytics';
  15. import getDuration from 'sentry/utils/duration/getDuration';
  16. import {formatAbbreviatedNumber} from 'sentry/utils/formatters';
  17. import {PageAlert, PageAlertProvider} from 'sentry/utils/performance/contexts/pageAlert';
  18. import {decodeList} from 'sentry/utils/queryString';
  19. import {useLocation} from 'sentry/utils/useLocation';
  20. import useOrganization from 'sentry/utils/useOrganization';
  21. import {WebVitalStatusLineChart} from 'sentry/views/insights/browser/webVitals/components/charts/webVitalStatusLineChart';
  22. import {PerformanceBadge} from 'sentry/views/insights/browser/webVitals/components/performanceBadge';
  23. import {WebVitalDescription} from 'sentry/views/insights/browser/webVitals/components/webVitalDescription';
  24. import {useProjectRawWebVitalsQuery} from 'sentry/views/insights/browser/webVitals/queries/rawWebVitalsQueries/useProjectRawWebVitalsQuery';
  25. import {useProjectRawWebVitalsValuesTimeseriesQuery} from 'sentry/views/insights/browser/webVitals/queries/rawWebVitalsQueries/useProjectRawWebVitalsValuesTimeseriesQuery';
  26. import {calculatePerformanceScoreFromStoredTableDataRow} from 'sentry/views/insights/browser/webVitals/queries/storedScoreQueries/calculatePerformanceScoreFromStored';
  27. import {useProjectWebVitalsScoresQuery} from 'sentry/views/insights/browser/webVitals/queries/storedScoreQueries/useProjectWebVitalsScoresQuery';
  28. import {useTransactionWebVitalsScoresQuery} from 'sentry/views/insights/browser/webVitals/queries/storedScoreQueries/useTransactionWebVitalsScoresQuery';
  29. import {MODULE_DOC_LINK} from 'sentry/views/insights/browser/webVitals/settings';
  30. import type {
  31. Row,
  32. RowWithScoreAndOpportunity,
  33. WebVitals,
  34. } from 'sentry/views/insights/browser/webVitals/types';
  35. import decodeBrowserTypes from 'sentry/views/insights/browser/webVitals/utils/queryParameterDecoders/browserType';
  36. import DetailPanel from 'sentry/views/insights/common/components/detailPanel';
  37. import {SpanIndexedField, type SubregionCode} from 'sentry/views/insights/types';
  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 location = useLocation();
  56. const organization = useOrganization();
  57. const browserTypes = decodeBrowserTypes(location.query[SpanIndexedField.BROWSER_NAME]);
  58. const subregions = decodeList(
  59. location.query[SpanIndexedField.USER_GEO_SUBREGION]
  60. ) as SubregionCode[];
  61. const {data: projectData} = useProjectRawWebVitalsQuery({browserTypes, subregions});
  62. const {data: projectScoresData} = useProjectWebVitalsScoresQuery({
  63. weightWebVital: webVital ?? 'total',
  64. browserTypes,
  65. subregions,
  66. });
  67. const projectScore = calculatePerformanceScoreFromStoredTableDataRow(
  68. projectScoresData?.data?.[0]
  69. );
  70. const {data, isPending} = useTransactionWebVitalsScoresQuery({
  71. limit: 100,
  72. webVital: webVital ?? 'total',
  73. ...(webVital
  74. ? {
  75. query: `count_scores(measurements.score.${webVital}):>0`,
  76. defaultSort: {
  77. field: `opportunity_score(measurements.score.${webVital})`,
  78. kind: 'desc',
  79. },
  80. }
  81. : {}),
  82. enabled: webVital !== null,
  83. sortName: 'webVitalsDetailPanelSort',
  84. browserTypes,
  85. subregions,
  86. });
  87. const dataByOpportunity = useMemo(() => {
  88. if (!data) {
  89. return [];
  90. }
  91. const sumWeights = projectScoresData?.data?.[0]?.[
  92. `sum(measurements.score.weight.${webVital})`
  93. ] as number;
  94. return data
  95. .map(row => ({
  96. ...row,
  97. opportunity:
  98. Math.round(
  99. (((row as RowWithScoreAndOpportunity).opportunity ?? 0) * 100 * 100) /
  100. sumWeights
  101. ) / 100,
  102. }))
  103. .sort((a, b) => {
  104. if (a.opportunity === undefined) {
  105. return 1;
  106. }
  107. if (b.opportunity === undefined) {
  108. return -1;
  109. }
  110. return b.opportunity - a.opportunity;
  111. })
  112. .slice(0, MAX_ROWS);
  113. }, [data, projectScoresData?.data, webVital]);
  114. const {data: timeseriesData, isLoading: isTimeseriesLoading} =
  115. useProjectRawWebVitalsValuesTimeseriesQuery({browserTypes, subregions});
  116. const webVitalData: LineChartSeries = {
  117. data:
  118. !isTimeseriesLoading && webVital
  119. ? timeseriesData?.[webVital].map(({name, value}) => ({
  120. name,
  121. value,
  122. }))
  123. : [],
  124. seriesName: webVital ?? '',
  125. };
  126. const detailKey = webVital;
  127. useEffect(() => {
  128. if (webVital !== null) {
  129. trackAnalytics('insight.vital.vital_sidebar_opened', {
  130. organization,
  131. vital: webVital,
  132. });
  133. }
  134. }, [organization, 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={`${MODULE_DOC_LINK}#opportunity`}>
  157. {t('How is this calculated?')}
  158. </ExternalLink>
  159. </span>
  160. }
  161. >
  162. <OpportunityHeader>{col.name}</OpportunityHeader>
  163. </Tooltip>
  164. );
  165. }
  166. if (col.key === 'count') {
  167. if (webVital === 'inp') {
  168. return <AlignRight>{t('Interactions')}</AlignRight>;
  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', '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. pathname: `${location.pathname}overview/`,
  204. query: {
  205. ...location.query,
  206. transaction: row.transaction,
  207. webVital,
  208. project: row['project.id'],
  209. },
  210. }}
  211. >
  212. {row.transaction}
  213. </Link>
  214. </NoOverflow>
  215. );
  216. }
  217. if (key === 'count') {
  218. const count =
  219. webVital === 'inp' ? row['count_scores(measurements.score.inp)'] : row['count()'];
  220. return <AlignRight>{formatAbbreviatedNumber(count)}</AlignRight>;
  221. }
  222. return <AlignRight>{row[key]}</AlignRight>;
  223. };
  224. const webVitalScore = projectScore[`${webVital}Score`];
  225. const webVitalValue = projectData?.data?.[0]?.[mapWebVitalToColumn(webVital)] as
  226. | number
  227. | undefined;
  228. return (
  229. <PageAlertProvider>
  230. <DetailPanel detailKey={detailKey ?? undefined} onClose={onClose}>
  231. {webVital && (
  232. <WebVitalDescription
  233. value={
  234. webVitalValue !== undefined
  235. ? webVital !== 'cls'
  236. ? getDuration(webVitalValue / 1000, 2, true)
  237. : webVitalValue?.toFixed(2)
  238. : undefined
  239. }
  240. webVital={webVital}
  241. score={webVitalScore}
  242. />
  243. )}
  244. <ChartContainer>
  245. {webVital && <WebVitalStatusLineChart webVitalSeries={webVitalData} />}
  246. </ChartContainer>
  247. <TableContainer>
  248. <GridEditable
  249. data={dataByOpportunity}
  250. isLoading={isPending}
  251. columnOrder={columnOrder}
  252. columnSortBy={[sort]}
  253. grid={{
  254. renderHeadCell,
  255. renderBodyCell,
  256. }}
  257. />
  258. </TableContainer>
  259. <PageAlert />
  260. </DetailPanel>
  261. </PageAlertProvider>
  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 'inp':
  275. return 'p75(measurements.inp)';
  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. `;