webVitalsDetailPanel.tsx 9.9 KB

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