webVitalsDetailPanel.tsx 9.4 KB

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