webVitalsDetailPanel.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. import {useMemo} from 'react';
  2. import {Link} from 'react-router';
  3. import {useTheme} from '@emotion/react';
  4. import styled from '@emotion/styled';
  5. import * as qs from 'query-string';
  6. import ChartZoom from 'sentry/components/charts/chartZoom';
  7. import MarkArea from 'sentry/components/charts/components/markArea';
  8. import MarkLine from 'sentry/components/charts/components/markLine';
  9. import {LineChart, LineChartSeries} from 'sentry/components/charts/lineChart';
  10. import GridEditable, {
  11. COL_WIDTH_UNDEFINED,
  12. GridColumnHeader,
  13. GridColumnOrder,
  14. GridColumnSortBy,
  15. } from 'sentry/components/gridEditable';
  16. import {getDuration} from 'sentry/utils/formatters';
  17. import {
  18. PageErrorAlert,
  19. PageErrorProvider,
  20. } from 'sentry/utils/performance/contexts/pageError';
  21. import {useLocation} from 'sentry/utils/useLocation';
  22. import usePageFilters from 'sentry/utils/usePageFilters';
  23. import useProjects from 'sentry/utils/useProjects';
  24. import useRouter from 'sentry/utils/useRouter';
  25. import {PerformanceBadge} from 'sentry/views/performance/browser/webVitals/components/performanceBadge';
  26. import {calculateOpportunity} from 'sentry/views/performance/browser/webVitals/utils/calculateOpportunity';
  27. import {
  28. calculatePerformanceScore,
  29. PERFORMANCE_SCORE_MEDIANS,
  30. PERFORMANCE_SCORE_P90S,
  31. } from 'sentry/views/performance/browser/webVitals/utils/calculatePerformanceScore';
  32. import {
  33. Row,
  34. RowWithScore,
  35. WebVitals,
  36. } from 'sentry/views/performance/browser/webVitals/utils/types';
  37. import {useProjectWebVitalsQuery} from 'sentry/views/performance/browser/webVitals/utils/useProjectWebVitalsQuery';
  38. import {useProjectWebVitalsValuesTimeseriesQuery} from 'sentry/views/performance/browser/webVitals/utils/useProjectWebVitalsValuesTimeseriesQuery';
  39. import {useTransactionWebVitalsQuery} from 'sentry/views/performance/browser/webVitals/utils/useTransactionWebVitalsQuery';
  40. import {WebVitalDescription} from 'sentry/views/performance/browser/webVitals/webVitalsDescriptions/webVitalDescription';
  41. import DetailPanel from 'sentry/views/starfish/components/detailPanel';
  42. type Column = GridColumnHeader;
  43. const columnOrder: GridColumnOrder[] = [
  44. {key: 'transaction', width: COL_WIDTH_UNDEFINED, name: 'Pages'},
  45. {key: 'count()', width: COL_WIDTH_UNDEFINED, name: 'Pageloads'},
  46. {key: 'webVital', width: COL_WIDTH_UNDEFINED, name: 'Web Vital'},
  47. {key: 'score', width: COL_WIDTH_UNDEFINED, name: 'Score'},
  48. {key: 'opportunity', width: COL_WIDTH_UNDEFINED, name: 'Opportunity'},
  49. ];
  50. const sort: GridColumnSortBy<keyof Row> = {key: 'count()', order: 'desc'};
  51. const MAX_ROWS = 10;
  52. export function WebVitalsDetailPanel({
  53. webVital,
  54. onClose,
  55. }: {
  56. onClose: () => void;
  57. webVital: WebVitals | null;
  58. }) {
  59. const location = useLocation();
  60. const {projects} = useProjects();
  61. const theme = useTheme();
  62. const pageFilters = usePageFilters();
  63. const router = useRouter();
  64. const {period, start, end, utc} = pageFilters.selection.datetime;
  65. const project = useMemo(
  66. () => projects.find(p => p.id === String(location.query.project)),
  67. [projects, location.query.project]
  68. );
  69. const {data: projectData} = useProjectWebVitalsQuery();
  70. const projectScore = calculatePerformanceScore({
  71. lcp: projectData?.data[0]['p75(measurements.lcp)'] as number,
  72. fcp: projectData?.data[0]['p75(measurements.fcp)'] as number,
  73. cls: projectData?.data[0]['p75(measurements.cls)'] as number,
  74. ttfb: projectData?.data[0]['p75(measurements.ttfb)'] as number,
  75. fid: projectData?.data[0]['p75(measurements.fid)'] as number,
  76. });
  77. const {data, isLoading} = useTransactionWebVitalsQuery({
  78. orderBy: webVital,
  79. limit: 100,
  80. });
  81. const dataByOpportunity = useMemo(() => {
  82. if (!data) {
  83. return [];
  84. }
  85. const count = projectData?.data[0]['count()'] as number;
  86. return data
  87. .map(row => ({
  88. ...row,
  89. opportunity: calculateOpportunity(
  90. projectScore[`${webVital}Score`],
  91. count,
  92. row[`${webVital}Score`],
  93. row['count()']
  94. ),
  95. }))
  96. .sort((a, b) => b.opportunity - a.opportunity)
  97. .slice(0, MAX_ROWS);
  98. }, [data, projectData?.data, projectScore, webVital]);
  99. const {data: timeseriesData, isLoading: isTimeseriesLoading} =
  100. useProjectWebVitalsValuesTimeseriesQuery();
  101. const webVitalData: LineChartSeries[] = [
  102. {
  103. data:
  104. !isTimeseriesLoading && webVital
  105. ? timeseriesData?.[webVital].map(({name, value}) => ({
  106. name,
  107. value,
  108. }))
  109. : [],
  110. seriesName: webVital ?? '',
  111. },
  112. ];
  113. const goodMarkArea = MarkArea({
  114. silent: true,
  115. itemStyle: {
  116. color: theme.green300,
  117. opacity: 0.1,
  118. },
  119. data: [
  120. [
  121. {
  122. yAxis: PERFORMANCE_SCORE_P90S[webVital ?? ''],
  123. },
  124. {
  125. yAxis: 0,
  126. },
  127. ],
  128. ],
  129. });
  130. const mehMarkArea = MarkArea({
  131. silent: true,
  132. itemStyle: {
  133. color: theme.yellow300,
  134. opacity: 0.1,
  135. },
  136. data: [
  137. [
  138. {
  139. yAxis: PERFORMANCE_SCORE_MEDIANS[webVital ?? ''],
  140. },
  141. {
  142. yAxis: PERFORMANCE_SCORE_P90S[webVital ?? ''],
  143. },
  144. ],
  145. ],
  146. });
  147. const poorMarkArea = MarkArea({
  148. silent: true,
  149. itemStyle: {
  150. color: theme.red300,
  151. opacity: 0.1,
  152. },
  153. data: [
  154. [
  155. {
  156. yAxis: PERFORMANCE_SCORE_MEDIANS[webVital ?? ''],
  157. },
  158. {
  159. yAxis: Infinity,
  160. },
  161. ],
  162. ],
  163. });
  164. const goodMarkLine = MarkLine({
  165. silent: true,
  166. lineStyle: {
  167. color: theme.green300,
  168. },
  169. label: {
  170. formatter: () => 'Good',
  171. position: 'insideEndBottom',
  172. color: theme.green300,
  173. },
  174. data: [
  175. {
  176. yAxis: PERFORMANCE_SCORE_P90S[webVital ?? ''],
  177. },
  178. ],
  179. });
  180. const mehMarkLine = MarkLine({
  181. silent: true,
  182. lineStyle: {
  183. color: theme.yellow300,
  184. },
  185. label: {
  186. formatter: () => 'Meh',
  187. position: 'insideEndBottom',
  188. color: theme.yellow300,
  189. },
  190. data: [
  191. {
  192. yAxis: PERFORMANCE_SCORE_MEDIANS[webVital ?? ''],
  193. },
  194. ],
  195. });
  196. webVitalData.push({
  197. seriesName: '',
  198. type: 'line',
  199. markArea: goodMarkArea,
  200. data: [],
  201. });
  202. webVitalData.push({
  203. seriesName: '',
  204. type: 'line',
  205. markArea: mehMarkArea,
  206. data: [],
  207. });
  208. webVitalData.push({
  209. seriesName: '',
  210. type: 'line',
  211. markArea: poorMarkArea,
  212. data: [],
  213. });
  214. webVitalData.push({
  215. seriesName: '',
  216. type: 'line',
  217. markLine: goodMarkLine,
  218. data: [],
  219. });
  220. webVitalData.push({
  221. seriesName: '',
  222. type: 'line',
  223. markLine: mehMarkLine,
  224. data: [],
  225. });
  226. const detailKey = webVital;
  227. const renderHeadCell = (col: Column) => {
  228. if (col.key === 'transaction') {
  229. return <NoOverflow>{col.name}</NoOverflow>;
  230. }
  231. if (col.key === 'webVital') {
  232. return <AlignRight>{`${webVital} P75`}</AlignRight>;
  233. }
  234. if (col.key === 'score') {
  235. return <AlignCenter>{`${webVital} ${col.name}`}</AlignCenter>;
  236. }
  237. return <AlignRight>{col.name}</AlignRight>;
  238. };
  239. const renderBodyCell = (col: Column, row: RowWithScore) => {
  240. const {key} = col;
  241. if (key === 'score') {
  242. return (
  243. <AlignCenter>
  244. <PerformanceBadge score={row[`${webVital}Score`]} />
  245. </AlignCenter>
  246. );
  247. }
  248. if (col.key === 'webVital') {
  249. let value: string | number = row[mapWebVitalToColumn(webVital)];
  250. if (webVital && ['lcp', 'fcp', 'ttfb', 'fid'].includes(webVital)) {
  251. value = getDuration(value / 1000, 2, true);
  252. } else if (webVital === 'cls') {
  253. value = value?.toFixed(2);
  254. }
  255. return <AlignRight>{value}</AlignRight>;
  256. }
  257. if (key === 'transaction') {
  258. const link = `/performance/summary/?${qs.stringify({
  259. project: project?.id,
  260. transaction: row.transaction,
  261. })}`;
  262. return (
  263. <NoOverflow>
  264. <Link to={link}>{row.transaction}</Link>
  265. </NoOverflow>
  266. );
  267. }
  268. return <AlignRight>{row[key]}</AlignRight>;
  269. };
  270. return (
  271. <PageErrorProvider>
  272. <DetailPanel detailKey={detailKey ?? undefined} onClose={onClose}>
  273. {webVital && (
  274. <WebVitalDescription
  275. value={
  276. webVital !== 'cls'
  277. ? getDuration(
  278. (projectData?.data[0][mapWebVitalToColumn(webVital)] as number) /
  279. 1000,
  280. 2,
  281. true
  282. )
  283. : (projectData?.data[0][mapWebVitalToColumn(webVital)] as number).toFixed(
  284. 2
  285. )
  286. }
  287. webVital={webVital}
  288. score={projectScore[`${webVital}Score`]}
  289. />
  290. )}
  291. <ChartContainer>
  292. {webVital && (
  293. <ChartZoom router={router} period={period} start={start} end={end} utc={utc}>
  294. {zoomRenderProps => (
  295. <LineChart
  296. {...zoomRenderProps}
  297. height={240}
  298. series={webVitalData}
  299. xAxis={{show: false}}
  300. grid={{
  301. left: 0,
  302. right: 15,
  303. top: 10,
  304. bottom: 0,
  305. }}
  306. />
  307. )}
  308. </ChartZoom>
  309. )}
  310. </ChartContainer>
  311. <GridEditable
  312. data={dataByOpportunity}
  313. isLoading={isLoading}
  314. columnOrder={columnOrder}
  315. columnSortBy={[sort]}
  316. grid={{
  317. renderHeadCell,
  318. renderBodyCell,
  319. }}
  320. location={location}
  321. />
  322. <PageErrorAlert />
  323. </DetailPanel>
  324. </PageErrorProvider>
  325. );
  326. }
  327. const mapWebVitalToColumn = (webVital?: WebVitals | null) => {
  328. switch (webVital) {
  329. case 'lcp':
  330. return 'p75(measurements.lcp)';
  331. case 'fcp':
  332. return 'p75(measurements.fcp)';
  333. case 'cls':
  334. return 'p75(measurements.cls)';
  335. case 'ttfb':
  336. return 'p75(measurements.ttfb)';
  337. case 'fid':
  338. return 'p75(measurements.fid)';
  339. default:
  340. return 'count()';
  341. }
  342. };
  343. const NoOverflow = styled('span')`
  344. overflow: hidden;
  345. text-overflow: ellipsis;
  346. `;
  347. const AlignRight = styled('span')<{color?: string}>`
  348. text-align: right;
  349. width: 100%;
  350. ${p => (p.color ? `color: ${p.color};` : '')}
  351. `;
  352. const ChartContainer = styled('div')`
  353. position: relative;
  354. flex: 1;
  355. `;
  356. const AlignCenter = styled('span')`
  357. text-align: center;
  358. width: 100%;
  359. `;