webVitalsDetailPanel.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. import {useEffect, useMemo} from 'react';
  2. import styled from '@emotion/styled';
  3. import type {LineChartSeries} from 'sentry/components/charts/lineChart';
  4. import {DrawerHeader} from 'sentry/components/globalDrawer/components';
  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 Link from 'sentry/components/links/link';
  13. import {Tooltip} from 'sentry/components/tooltip';
  14. import {t, tct} from 'sentry/locale';
  15. import {trackAnalytics} from 'sentry/utils/analytics';
  16. import getDuration from 'sentry/utils/duration/getDuration';
  17. import {formatAbbreviatedNumber} from 'sentry/utils/formatters';
  18. import {PageAlert, PageAlertProvider} from 'sentry/utils/performance/contexts/pageAlert';
  19. import {decodeList} from 'sentry/utils/queryString';
  20. import {useLocation} from 'sentry/utils/useLocation';
  21. import useOrganization from 'sentry/utils/useOrganization';
  22. import {WebVitalStatusLineChart} from 'sentry/views/insights/browser/webVitals/components/charts/webVitalStatusLineChart';
  23. import {PerformanceBadge} from 'sentry/views/insights/browser/webVitals/components/performanceBadge';
  24. import {WebVitalDescription} from 'sentry/views/insights/browser/webVitals/components/webVitalDescription';
  25. import {useProjectRawWebVitalsQuery} from 'sentry/views/insights/browser/webVitals/queries/rawWebVitalsQueries/useProjectRawWebVitalsQuery';
  26. import {useProjectRawWebVitalsValuesTimeseriesQuery} from 'sentry/views/insights/browser/webVitals/queries/rawWebVitalsQueries/useProjectRawWebVitalsValuesTimeseriesQuery';
  27. import {getWebVitalScoresFromTableDataRow} from 'sentry/views/insights/browser/webVitals/queries/storedScoreQueries/getWebVitalScoresFromTableDataRow';
  28. import {useProjectWebVitalsScoresQuery} from 'sentry/views/insights/browser/webVitals/queries/storedScoreQueries/useProjectWebVitalsScoresQuery';
  29. import {useTransactionWebVitalsScoresQuery} from 'sentry/views/insights/browser/webVitals/queries/storedScoreQueries/useTransactionWebVitalsScoresQuery';
  30. import {MODULE_DOC_LINK} from 'sentry/views/insights/browser/webVitals/settings';
  31. import type {
  32. Row,
  33. RowWithScoreAndOpportunity,
  34. WebVitals,
  35. } from 'sentry/views/insights/browser/webVitals/types';
  36. import decodeBrowserTypes from 'sentry/views/insights/browser/webVitals/utils/queryParameterDecoders/browserType';
  37. import {SampleDrawerBody} from 'sentry/views/insights/common/components/sampleDrawerBody';
  38. import {SpanIndexedField, type SubregionCode} from 'sentry/views/insights/types';
  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({webVital}: {webVital: WebVitals | null}) {
  50. const location = useLocation();
  51. const organization = useOrganization();
  52. const browserTypes = decodeBrowserTypes(location.query[SpanIndexedField.BROWSER_NAME]);
  53. const subregions = decodeList(
  54. location.query[SpanIndexedField.USER_GEO_SUBREGION]
  55. ) as SubregionCode[];
  56. const {data: projectData} = useProjectRawWebVitalsQuery({browserTypes, subregions});
  57. const {data: projectScoresData} = useProjectWebVitalsScoresQuery({
  58. weightWebVital: webVital ?? 'total',
  59. browserTypes,
  60. subregions,
  61. });
  62. const projectScore = getWebVitalScoresFromTableDataRow(projectScoresData?.data?.[0]);
  63. const {data, isPending} = useTransactionWebVitalsScoresQuery({
  64. limit: 100,
  65. webVital: webVital ?? 'total',
  66. ...(webVital
  67. ? {
  68. query: `count_scores(measurements.score.${webVital}):>0`,
  69. defaultSort: {
  70. field: `opportunity_score(measurements.score.${webVital})`,
  71. kind: 'desc',
  72. },
  73. }
  74. : {}),
  75. enabled: webVital !== null,
  76. sortName: 'webVitalsDetailPanelSort',
  77. browserTypes,
  78. subregions,
  79. });
  80. const dataByOpportunity = useMemo(() => {
  81. if (!data) {
  82. return [];
  83. }
  84. const sumWeights = projectScoresData?.data?.[0]?.[
  85. `sum(measurements.score.weight.${webVital})`
  86. ] as number;
  87. return data
  88. .map(row => ({
  89. ...row,
  90. opportunity:
  91. Math.round(
  92. (((row as RowWithScoreAndOpportunity).opportunity ?? 0) * 100 * 100) /
  93. sumWeights
  94. ) / 100,
  95. }))
  96. .sort((a, b) => {
  97. if (a.opportunity === undefined) {
  98. return 1;
  99. }
  100. if (b.opportunity === undefined) {
  101. return -1;
  102. }
  103. return b.opportunity - a.opportunity;
  104. })
  105. .slice(0, MAX_ROWS);
  106. }, [data, projectScoresData?.data, webVital]);
  107. const {data: timeseriesData, isLoading: isTimeseriesLoading} =
  108. useProjectRawWebVitalsValuesTimeseriesQuery({browserTypes, subregions});
  109. const webVitalData: LineChartSeries = {
  110. data:
  111. !isTimeseriesLoading && webVital
  112. ? timeseriesData?.[webVital].map(({name, value}) => ({
  113. name,
  114. value,
  115. }))
  116. : [],
  117. seriesName: webVital ?? '',
  118. };
  119. useEffect(() => {
  120. if (webVital !== null) {
  121. trackAnalytics('insight.vital.vital_sidebar_opened', {
  122. organization,
  123. vital: webVital,
  124. });
  125. }
  126. }, [organization, webVital]);
  127. const renderHeadCell = (col: Column) => {
  128. if (col.key === 'transaction') {
  129. return <NoOverflow>{col.name}</NoOverflow>;
  130. }
  131. if (col.key === 'webVital') {
  132. return <AlignRight>{`${webVital} P75`}</AlignRight>;
  133. }
  134. if (col.key === 'score') {
  135. return <AlignCenter>{`${webVital} ${col.name}`}</AlignCenter>;
  136. }
  137. if (col.key === 'opportunity') {
  138. return (
  139. <Tooltip
  140. isHoverable
  141. title={
  142. <span>
  143. {tct(
  144. "A number rating how impactful a performance improvement on this page would be to your application's [webVital] Performance Score.",
  145. {webVital: webVital?.toUpperCase() ?? ''}
  146. )}
  147. <br />
  148. <ExternalLink href={`${MODULE_DOC_LINK}#opportunity`}>
  149. {t('How is this calculated?')}
  150. </ExternalLink>
  151. </span>
  152. }
  153. >
  154. <OpportunityHeader>{col.name}</OpportunityHeader>
  155. </Tooltip>
  156. );
  157. }
  158. if (col.key === 'count') {
  159. if (webVital === 'inp') {
  160. return <AlignRight>{t('Interactions')}</AlignRight>;
  161. }
  162. }
  163. return <AlignRight>{col.name}</AlignRight>;
  164. };
  165. const getFormattedDuration = (value: number) => {
  166. if (value < 1000) {
  167. return getDuration(value / 1000, 0, true);
  168. }
  169. return getDuration(value / 1000, 2, true);
  170. };
  171. const renderBodyCell = (col: Column, row: RowWithScoreAndOpportunity) => {
  172. const {key} = col;
  173. if (key === 'score') {
  174. return (
  175. <AlignCenter>
  176. <PerformanceBadge score={row[`${webVital!}Score`]} />
  177. </AlignCenter>
  178. );
  179. }
  180. if (col.key === 'webVital') {
  181. let value: string | number = row[mapWebVitalToColumn(webVital)];
  182. if (webVital && ['lcp', 'fcp', 'ttfb', 'inp'].includes(webVital)) {
  183. value = getFormattedDuration(value);
  184. } else if (webVital === 'cls') {
  185. value = value?.toFixed(2);
  186. }
  187. return <AlignRight>{value}</AlignRight>;
  188. }
  189. if (key === 'transaction') {
  190. return (
  191. <NoOverflow>
  192. <Link
  193. to={{
  194. ...location,
  195. pathname: `${location.pathname}overview/`,
  196. query: {
  197. ...location.query,
  198. transaction: row.transaction,
  199. webVital,
  200. project: row['project.id'],
  201. },
  202. }}
  203. >
  204. {row.transaction}
  205. </Link>
  206. </NoOverflow>
  207. );
  208. }
  209. if (key === 'count') {
  210. const count =
  211. // @ts-expect-error TS(7053): Element implicitly has an 'any' type because expre... Remove this comment to see the full error message
  212. webVital === 'inp' ? row['count_scores(measurements.score.inp)'] : row['count()'];
  213. return <AlignRight>{formatAbbreviatedNumber(count)}</AlignRight>;
  214. }
  215. // @ts-expect-error TS(7053): Element implicitly has an 'any' type because expre... Remove this comment to see the full error message
  216. return <AlignRight>{row[key]}</AlignRight>;
  217. };
  218. // @ts-expect-error TS(7053): Element implicitly has an 'any' type because expre... Remove this comment to see the full error message
  219. const webVitalScore = projectScore[`${webVital}Score`];
  220. const webVitalValue = projectData?.data?.[0]?.[mapWebVitalToColumn(webVital)] as
  221. | number
  222. | undefined;
  223. return (
  224. <PageAlertProvider>
  225. <DrawerHeader />
  226. <SampleDrawerBody>
  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={isPending}
  247. columnOrder={columnOrder}
  248. columnSortBy={[sort]}
  249. grid={{
  250. renderHeadCell,
  251. renderBodyCell,
  252. }}
  253. />
  254. </TableContainer>
  255. <PageAlert />
  256. </SampleDrawerBody>
  257. </PageAlertProvider>
  258. );
  259. }
  260. const mapWebVitalToColumn = (webVital?: WebVitals | null) => {
  261. switch (webVital) {
  262. case 'lcp':
  263. return 'p75(measurements.lcp)';
  264. case 'fcp':
  265. return 'p75(measurements.fcp)';
  266. case 'cls':
  267. return 'p75(measurements.cls)';
  268. case 'ttfb':
  269. return 'p75(measurements.ttfb)';
  270. case 'inp':
  271. return 'p75(measurements.inp)';
  272. default:
  273. return 'count()';
  274. }
  275. };
  276. const NoOverflow = styled('span')`
  277. overflow: hidden;
  278. text-overflow: ellipsis;
  279. `;
  280. const AlignRight = styled('span')<{color?: string}>`
  281. text-align: right;
  282. width: 100%;
  283. ${p => (p.color ? `color: ${p.color};` : '')}
  284. `;
  285. const ChartContainer = styled('div')`
  286. position: relative;
  287. flex: 1;
  288. `;
  289. const AlignCenter = styled('span')`
  290. text-align: center;
  291. width: 100%;
  292. `;
  293. const OpportunityHeader = styled('span')`
  294. ${p => p.theme.tooltipUnderline()};
  295. `;
  296. const TableContainer = styled('div')`
  297. margin-bottom: 80px;
  298. `;