webVitalsDetailPanel.tsx 8.8 KB

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