webVitalsDetailPanel.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  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 ChartZoom from 'sentry/components/charts/chartZoom';
  6. import MarkArea from 'sentry/components/charts/components/markArea';
  7. import MarkLine from 'sentry/components/charts/components/markLine';
  8. import {LineChart, LineChartSeries} from 'sentry/components/charts/lineChart';
  9. import GridEditable, {
  10. COL_WIDTH_UNDEFINED,
  11. GridColumnHeader,
  12. GridColumnOrder,
  13. GridColumnSortBy,
  14. } from 'sentry/components/gridEditable';
  15. import {Tooltip} from 'sentry/components/tooltip';
  16. import {t} from 'sentry/locale';
  17. import {getDuration} from 'sentry/utils/formatters';
  18. import {
  19. PageErrorAlert,
  20. PageErrorProvider,
  21. } from 'sentry/utils/performance/contexts/pageError';
  22. import {useLocation} from 'sentry/utils/useLocation';
  23. import useOrganization from 'sentry/utils/useOrganization';
  24. import usePageFilters from 'sentry/utils/usePageFilters';
  25. import useRouter from 'sentry/utils/useRouter';
  26. import {PerformanceBadge} from 'sentry/views/performance/browser/webVitals/components/performanceBadge';
  27. import {WebVitalDescription} from 'sentry/views/performance/browser/webVitals/components/webVitalDescription';
  28. import {calculateOpportunity} from 'sentry/views/performance/browser/webVitals/utils/calculateOpportunity';
  29. import {
  30. calculatePerformanceScore,
  31. PERFORMANCE_SCORE_MEDIANS,
  32. PERFORMANCE_SCORE_P90S,
  33. } from 'sentry/views/performance/browser/webVitals/utils/calculatePerformanceScore';
  34. import {
  35. Row,
  36. RowWithScore,
  37. WebVitals,
  38. } from 'sentry/views/performance/browser/webVitals/utils/types';
  39. import {useProjectWebVitalsQuery} from 'sentry/views/performance/browser/webVitals/utils/useProjectWebVitalsQuery';
  40. import {useProjectWebVitalsValuesTimeseriesQuery} from 'sentry/views/performance/browser/webVitals/utils/useProjectWebVitalsValuesTimeseriesQuery';
  41. import {useTransactionWebVitalsQuery} from 'sentry/views/performance/browser/webVitals/utils/useTransactionWebVitalsQuery';
  42. import DetailPanel from 'sentry/views/starfish/components/detailPanel';
  43. type Column = GridColumnHeader;
  44. const columnOrder: GridColumnOrder[] = [
  45. {key: 'transaction', width: COL_WIDTH_UNDEFINED, name: 'Pages'},
  46. {key: 'count()', width: COL_WIDTH_UNDEFINED, name: 'Pageloads'},
  47. {key: 'webVital', width: COL_WIDTH_UNDEFINED, name: 'Web Vital'},
  48. {key: 'score', width: COL_WIDTH_UNDEFINED, name: 'Score'},
  49. {key: 'opportunity', width: COL_WIDTH_UNDEFINED, name: 'Opportunity'},
  50. ];
  51. const sort: GridColumnSortBy<keyof Row> = {key: 'count()', order: 'desc'};
  52. const MAX_ROWS = 10;
  53. export function WebVitalsDetailPanel({
  54. webVital,
  55. onClose,
  56. }: {
  57. onClose: () => void;
  58. webVital: WebVitals | null;
  59. }) {
  60. const organization = useOrganization();
  61. const location = useLocation();
  62. const theme = useTheme();
  63. const pageFilters = usePageFilters();
  64. const router = useRouter();
  65. const {period, start, end, utc} = pageFilters.selection.datetime;
  66. const transaction = location.query.transaction
  67. ? Array.isArray(location.query.transaction)
  68. ? location.query.transaction[0]
  69. : location.query.transaction
  70. : undefined;
  71. const {data: projectData} = useProjectWebVitalsQuery({transaction});
  72. const projectScore = calculatePerformanceScore({
  73. lcp: projectData?.data[0]['p75(measurements.lcp)'] as number,
  74. fcp: projectData?.data[0]['p75(measurements.fcp)'] as number,
  75. cls: projectData?.data[0]['p75(measurements.cls)'] as number,
  76. ttfb: projectData?.data[0]['p75(measurements.ttfb)'] as number,
  77. fid: projectData?.data[0]['p75(measurements.fid)'] as number,
  78. });
  79. const {data, isLoading} = useTransactionWebVitalsQuery({
  80. transaction,
  81. orderBy: webVital,
  82. limit: 100,
  83. });
  84. const dataByOpportunity = useMemo(() => {
  85. if (!data) {
  86. return [];
  87. }
  88. const count = projectData?.data[0]['count()'] as number;
  89. return data
  90. .map(row => ({
  91. ...row,
  92. opportunity: calculateOpportunity(
  93. projectScore[`${webVital}Score`],
  94. count,
  95. row[`${webVital}Score`],
  96. row['count()']
  97. ),
  98. }))
  99. .sort((a, b) => b.opportunity - a.opportunity)
  100. .slice(0, MAX_ROWS);
  101. }, [data, projectData?.data, projectScore, webVital]);
  102. const {data: timeseriesData, isLoading: isTimeseriesLoading} =
  103. useProjectWebVitalsValuesTimeseriesQuery({transaction});
  104. const webVitalData: LineChartSeries[] = [
  105. {
  106. data:
  107. !isTimeseriesLoading && webVital
  108. ? timeseriesData?.[webVital].map(({name, value}) => ({
  109. name,
  110. value,
  111. }))
  112. : [],
  113. seriesName: webVital ?? '',
  114. },
  115. ];
  116. const showPoorMarkLine = webVitalData[0].data?.some(
  117. ({value}) => value > PERFORMANCE_SCORE_MEDIANS[webVital ?? '']
  118. );
  119. const showMehMarkLine = webVitalData[0].data?.some(
  120. ({value}) => value >= PERFORMANCE_SCORE_P90S[webVital ?? '']
  121. );
  122. const showGoodMarkLine = webVitalData[0].data?.every(
  123. ({value}) => value < PERFORMANCE_SCORE_P90S[webVital ?? '']
  124. );
  125. const goodMarkArea = MarkArea({
  126. silent: true,
  127. itemStyle: {
  128. color: theme.green300,
  129. opacity: 0.1,
  130. },
  131. data: [
  132. [
  133. {
  134. yAxis: PERFORMANCE_SCORE_P90S[webVital ?? ''],
  135. },
  136. {
  137. yAxis: 0,
  138. },
  139. ],
  140. ],
  141. });
  142. const mehMarkArea = MarkArea({
  143. silent: true,
  144. itemStyle: {
  145. color: theme.yellow300,
  146. opacity: 0.1,
  147. },
  148. data: [
  149. [
  150. {
  151. yAxis: PERFORMANCE_SCORE_MEDIANS[webVital ?? ''],
  152. },
  153. {
  154. yAxis: PERFORMANCE_SCORE_P90S[webVital ?? ''],
  155. },
  156. ],
  157. ],
  158. });
  159. const poorMarkArea = MarkArea({
  160. silent: true,
  161. itemStyle: {
  162. color: theme.red300,
  163. opacity: 0.1,
  164. },
  165. data: [
  166. [
  167. {
  168. yAxis: PERFORMANCE_SCORE_MEDIANS[webVital ?? ''],
  169. },
  170. {
  171. yAxis: Infinity,
  172. },
  173. ],
  174. ],
  175. });
  176. const goodMarkLine = MarkLine({
  177. silent: true,
  178. lineStyle: {
  179. color: theme.green300,
  180. },
  181. label: {
  182. formatter: () => 'Good',
  183. position: 'insideEndBottom',
  184. color: theme.green300,
  185. },
  186. data: showGoodMarkLine
  187. ? [
  188. [
  189. {xAxis: 'min', y: 10},
  190. {xAxis: 'max', y: 10},
  191. ],
  192. ]
  193. : [
  194. {
  195. yAxis: PERFORMANCE_SCORE_P90S[webVital ?? ''],
  196. },
  197. ],
  198. });
  199. const mehMarkLine = MarkLine({
  200. silent: true,
  201. lineStyle: {
  202. color: theme.yellow300,
  203. },
  204. label: {
  205. formatter: () => 'Meh',
  206. position: 'insideEndBottom',
  207. color: theme.yellow300,
  208. },
  209. data:
  210. showMehMarkLine && !showPoorMarkLine
  211. ? [
  212. [
  213. {xAxis: 'min', y: 10},
  214. {xAxis: 'max', y: 10},
  215. ],
  216. ]
  217. : [
  218. {
  219. yAxis: PERFORMANCE_SCORE_MEDIANS[webVital ?? ''],
  220. },
  221. ],
  222. });
  223. const poorMarkLine = MarkLine({
  224. silent: true,
  225. lineStyle: {
  226. color: theme.red300,
  227. },
  228. label: {
  229. formatter: () => 'Poor',
  230. position: 'insideEndBottom',
  231. color: theme.red300,
  232. },
  233. data: [
  234. [
  235. {xAxis: 'min', y: 10},
  236. {xAxis: 'max', y: 10},
  237. ],
  238. ],
  239. });
  240. webVitalData.push({
  241. seriesName: '',
  242. type: 'line',
  243. markArea: goodMarkArea,
  244. data: [],
  245. });
  246. webVitalData.push({
  247. seriesName: '',
  248. type: 'line',
  249. markArea: mehMarkArea,
  250. data: [],
  251. });
  252. webVitalData.push({
  253. seriesName: '',
  254. type: 'line',
  255. markArea: poorMarkArea,
  256. data: [],
  257. });
  258. webVitalData.push({
  259. seriesName: '',
  260. type: 'line',
  261. markLine: goodMarkLine,
  262. data: [],
  263. });
  264. webVitalData.push({
  265. seriesName: '',
  266. type: 'line',
  267. markLine: mehMarkLine,
  268. data: [],
  269. });
  270. if (showPoorMarkLine) {
  271. webVitalData.push({
  272. seriesName: '',
  273. type: 'line',
  274. markLine: poorMarkLine,
  275. data: [],
  276. });
  277. }
  278. const detailKey = webVital;
  279. const renderHeadCell = (col: Column) => {
  280. if (col.key === 'transaction') {
  281. return <NoOverflow>{col.name}</NoOverflow>;
  282. }
  283. if (col.key === 'webVital') {
  284. return <AlignRight>{`${webVital} P75`}</AlignRight>;
  285. }
  286. if (col.key === 'score') {
  287. return <AlignCenter>{`${webVital} ${col.name}`}</AlignCenter>;
  288. }
  289. if (col.key === 'opportunity') {
  290. return (
  291. <Tooltip
  292. title={t(
  293. 'The biggest opportunities to improve your cumulative performance score.'
  294. )}
  295. >
  296. <OpportunityHeader>{col.name}</OpportunityHeader>
  297. </Tooltip>
  298. );
  299. }
  300. return <AlignRight>{col.name}</AlignRight>;
  301. };
  302. const getFormattedDuration = (value: number) => {
  303. if (value < 1000) {
  304. return getDuration(value / 1000, 0, true);
  305. }
  306. return getDuration(value / 1000, 2, true);
  307. };
  308. const renderBodyCell = (col: Column, row: RowWithScore) => {
  309. const {key} = col;
  310. if (key === 'score') {
  311. return (
  312. <AlignCenter>
  313. <PerformanceBadge score={row[`${webVital}Score`]} />
  314. </AlignCenter>
  315. );
  316. }
  317. if (col.key === 'webVital') {
  318. let value: string | number = row[mapWebVitalToColumn(webVital)];
  319. if (webVital && ['lcp', 'fcp', 'ttfb', 'fid'].includes(webVital)) {
  320. value = getFormattedDuration(value);
  321. } else if (webVital === 'cls') {
  322. value = value?.toFixed(2);
  323. }
  324. return <AlignRight>{value}</AlignRight>;
  325. }
  326. if (key === 'transaction') {
  327. return (
  328. <NoOverflow>
  329. <Link
  330. to={{
  331. ...location,
  332. ...(organization.features.includes(
  333. 'starfish-browser-webvitals-pageoverview-v2'
  334. )
  335. ? {pathname: `${location.pathname}overview/`}
  336. : {}),
  337. query: {
  338. ...location.query,
  339. transaction: row.transaction,
  340. webVital,
  341. },
  342. }}
  343. onClick={onClose}
  344. >
  345. {row.transaction}
  346. </Link>
  347. </NoOverflow>
  348. );
  349. }
  350. return <AlignRight>{row[key]}</AlignRight>;
  351. };
  352. return (
  353. <PageErrorProvider>
  354. <DetailPanel detailKey={detailKey ?? undefined} onClose={onClose}>
  355. {webVital && (
  356. <WebVitalDescription
  357. value={
  358. webVital !== 'cls'
  359. ? getDuration(
  360. (projectData?.data[0][mapWebVitalToColumn(webVital)] as number) /
  361. 1000,
  362. 2,
  363. true
  364. )
  365. : (projectData?.data[0][mapWebVitalToColumn(webVital)] as number).toFixed(
  366. 2
  367. )
  368. }
  369. webVital={webVital}
  370. score={projectScore[`${webVital}Score`]}
  371. />
  372. )}
  373. <ChartContainer>
  374. {webVital && (
  375. <ChartZoom router={router} period={period} start={start} end={end} utc={utc}>
  376. {zoomRenderProps => (
  377. <LineChart
  378. {...zoomRenderProps}
  379. height={240}
  380. series={webVitalData}
  381. xAxis={{show: false}}
  382. grid={{
  383. left: 0,
  384. right: 15,
  385. top: 10,
  386. bottom: 0,
  387. }}
  388. yAxis={
  389. webVital === 'cls'
  390. ? {}
  391. : {axisLabel: {formatter: getFormattedDuration}}
  392. }
  393. tooltip={
  394. webVital === 'cls' ? {} : {valueFormatter: getFormattedDuration}
  395. }
  396. />
  397. )}
  398. </ChartZoom>
  399. )}
  400. </ChartContainer>
  401. {!transaction && (
  402. <GridEditable
  403. data={dataByOpportunity}
  404. isLoading={isLoading}
  405. columnOrder={columnOrder}
  406. columnSortBy={[sort]}
  407. grid={{
  408. renderHeadCell,
  409. renderBodyCell,
  410. }}
  411. location={location}
  412. />
  413. )}
  414. <PageErrorAlert />
  415. </DetailPanel>
  416. </PageErrorProvider>
  417. );
  418. }
  419. const mapWebVitalToColumn = (webVital?: WebVitals | null) => {
  420. switch (webVital) {
  421. case 'lcp':
  422. return 'p75(measurements.lcp)';
  423. case 'fcp':
  424. return 'p75(measurements.fcp)';
  425. case 'cls':
  426. return 'p75(measurements.cls)';
  427. case 'ttfb':
  428. return 'p75(measurements.ttfb)';
  429. case 'fid':
  430. return 'p75(measurements.fid)';
  431. default:
  432. return 'count()';
  433. }
  434. };
  435. const NoOverflow = styled('span')`
  436. overflow: hidden;
  437. text-overflow: ellipsis;
  438. `;
  439. const AlignRight = styled('span')<{color?: string}>`
  440. text-align: right;
  441. width: 100%;
  442. ${p => (p.color ? `color: ${p.color};` : '')}
  443. `;
  444. const ChartContainer = styled('div')`
  445. position: relative;
  446. flex: 1;
  447. `;
  448. const AlignCenter = styled('span')`
  449. text-align: center;
  450. width: 100%;
  451. `;
  452. const OpportunityHeader = styled('span')`
  453. ${p => p.theme.tooltipUnderline()};
  454. `;