webVitalsDetailPanel.tsx 8.3 KB

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