webVitalsDetailPanel.tsx 10 KB

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