vitalsCards.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  1. import {Fragment} from 'react';
  2. import styled from '@emotion/styled';
  3. import * as Sentry from '@sentry/react';
  4. import type {Location} from 'history';
  5. import Card from 'sentry/components/card';
  6. import EventsRequest from 'sentry/components/charts/eventsRequest';
  7. import {HeaderTitle} from 'sentry/components/charts/styles';
  8. import {getInterval} from 'sentry/components/charts/utils';
  9. import EmptyStateWarning from 'sentry/components/emptyStateWarning';
  10. import Link from 'sentry/components/links/link';
  11. import Placeholder from 'sentry/components/placeholder';
  12. import QuestionTooltip from 'sentry/components/questionTooltip';
  13. import {Sparklines} from 'sentry/components/sparklines';
  14. import SparklinesLine from 'sentry/components/sparklines/line';
  15. import {Tooltip} from 'sentry/components/tooltip';
  16. import {t} from 'sentry/locale';
  17. import {space} from 'sentry/styles/space';
  18. import type {Organization, Project} from 'sentry/types';
  19. import {defined} from 'sentry/utils';
  20. import {getUtcToLocalDateObject} from 'sentry/utils/dates';
  21. import DiscoverQuery from 'sentry/utils/discover/discoverQuery';
  22. import type EventView from 'sentry/utils/discover/eventView';
  23. import type {Column} from 'sentry/utils/discover/fields';
  24. import {generateFieldAsString, getAggregateAlias} from 'sentry/utils/discover/fields';
  25. import {WebVital} from 'sentry/utils/fields';
  26. import {WEB_VITAL_DETAILS} from 'sentry/utils/performance/vitals/constants';
  27. import type {
  28. VitalData,
  29. VitalsData,
  30. } from 'sentry/utils/performance/vitals/vitalsCardsDiscoverQuery';
  31. import VitalsCardsDiscoverQuery from 'sentry/utils/performance/vitals/vitalsCardsDiscoverQuery';
  32. import {decodeList} from 'sentry/utils/queryString';
  33. import theme from 'sentry/utils/theme';
  34. import toArray from 'sentry/utils/toArray';
  35. import useApi from 'sentry/utils/useApi';
  36. import ColorBar from '../vitalDetail/colorBar';
  37. import {
  38. vitalAbbreviations,
  39. vitalDetailRouteWithQuery,
  40. vitalMap,
  41. VitalState,
  42. vitalStateColors,
  43. } from '../vitalDetail/utils';
  44. import VitalPercents from '../vitalDetail/vitalPercents';
  45. import {
  46. getDefaultDisplayFieldForPlatform,
  47. LandingDisplayField,
  48. vitalCardDetails,
  49. } from './utils';
  50. type FrontendCardsProps = {
  51. eventView: EventView;
  52. location: Location;
  53. organization: Organization;
  54. projects: Project[];
  55. frontendOnly?: boolean;
  56. };
  57. export function FrontendCards(props: FrontendCardsProps) {
  58. const {eventView, location, organization, projects, frontendOnly = false} = props;
  59. if (frontendOnly) {
  60. const defaultDisplay = getDefaultDisplayFieldForPlatform(projects, eventView);
  61. const isFrontend = defaultDisplay === LandingDisplayField.FRONTEND_PAGELOAD;
  62. if (!isFrontend) {
  63. return null;
  64. }
  65. }
  66. const vitals = [WebVital.FCP, WebVital.LCP, WebVital.FID, WebVital.CLS];
  67. return (
  68. <VitalsCardsDiscoverQuery
  69. eventView={eventView}
  70. location={location}
  71. orgSlug={organization.slug}
  72. vitals={vitals}
  73. >
  74. {({isLoading, vitalsData}) => {
  75. return (
  76. <VitalsContainer>
  77. {vitals.map(vital => {
  78. const target = vitalDetailRouteWithQuery({
  79. orgSlug: organization.slug,
  80. query: eventView.generateQueryStringObject(),
  81. vitalName: vital,
  82. projectID: decodeList(location.query.project),
  83. });
  84. const value = isLoading
  85. ? '\u2014'
  86. : getP75(vitalsData?.[vital] ?? null, vital);
  87. const chart = (
  88. <VitalBarContainer>
  89. <VitalBar isLoading={isLoading} vital={vital} data={vitalsData} />
  90. </VitalBarContainer>
  91. );
  92. return (
  93. <Link
  94. key={vital}
  95. to={target}
  96. data-test-id={`vitals-linked-card-${vitalAbbreviations[vital]}`}
  97. >
  98. <VitalCard
  99. title={vitalMap[vital] ?? ''}
  100. tooltip={WEB_VITAL_DETAILS[vital].description ?? ''}
  101. value={isLoading ? '\u2014' : value}
  102. chart={chart}
  103. minHeight={150}
  104. />
  105. </Link>
  106. );
  107. })}
  108. </VitalsContainer>
  109. );
  110. }}
  111. </VitalsCardsDiscoverQuery>
  112. );
  113. }
  114. const VitalBarContainer = styled('div')`
  115. margin-top: ${space(1.5)};
  116. `;
  117. type BaseCardsProps = {
  118. eventView: EventView;
  119. location: Location;
  120. organization: Organization;
  121. };
  122. type GenericCardsProps = BaseCardsProps & {
  123. functions: Column[];
  124. };
  125. function GenericCards(props: GenericCardsProps) {
  126. const api = useApi();
  127. const {eventView: baseEventView, location, organization, functions} = props;
  128. const {query} = location;
  129. const eventView = baseEventView.withColumns(functions);
  130. // construct request parameters for fetching chart data
  131. const globalSelection = eventView.getPageFilters();
  132. const start = globalSelection.datetime.start
  133. ? getUtcToLocalDateObject(globalSelection.datetime.start)
  134. : undefined;
  135. const end = globalSelection.datetime.end
  136. ? getUtcToLocalDateObject(globalSelection.datetime.end)
  137. : undefined;
  138. const interval =
  139. typeof query.sparkInterval === 'string'
  140. ? query.sparkInterval
  141. : getInterval(
  142. {
  143. start: start || null,
  144. end: end || null,
  145. period: globalSelection.datetime.period,
  146. },
  147. 'low'
  148. );
  149. const apiPayload = eventView.getEventsAPIPayload(location);
  150. return (
  151. <DiscoverQuery
  152. location={location}
  153. eventView={eventView}
  154. orgSlug={organization.slug}
  155. limit={1}
  156. referrer="api.performance.vitals-cards"
  157. >
  158. {({isLoading: isSummaryLoading, tableData}) => (
  159. <EventsRequest
  160. api={api}
  161. organization={organization}
  162. period={globalSelection.datetime.period}
  163. project={globalSelection.projects}
  164. environment={globalSelection.environments}
  165. team={apiPayload.team}
  166. start={start}
  167. end={end}
  168. interval={interval}
  169. query={apiPayload.query}
  170. includePrevious={false}
  171. yAxis={eventView.getFields()}
  172. partial
  173. >
  174. {({results}) => {
  175. const series = results?.reduce((allSeries, oneSeries) => {
  176. allSeries[oneSeries.seriesName] = oneSeries.data.map(item => item.value);
  177. return allSeries;
  178. }, {});
  179. const details = vitalCardDetails(organization);
  180. return (
  181. <VitalsContainer>
  182. {functions.map(func => {
  183. let fieldName = generateFieldAsString(func);
  184. if (fieldName.includes('apdex')) {
  185. // Replace apdex with explicit thresholds with a generic one for lookup
  186. fieldName = 'apdex()';
  187. }
  188. const cardDetail = details[fieldName];
  189. if (!cardDetail) {
  190. Sentry.captureMessage(`Missing field '${fieldName}' in vital cards.`);
  191. return null;
  192. }
  193. const {title, tooltip, formatter} = cardDetail;
  194. const alias = getAggregateAlias(fieldName);
  195. const rawValue = tableData?.data?.[0]?.[alias] as number;
  196. const data = series?.[fieldName];
  197. const value =
  198. isSummaryLoading || !defined(rawValue)
  199. ? '\u2014'
  200. : formatter(rawValue);
  201. const chart = <SparklineChart data={data} />;
  202. return (
  203. <VitalCard
  204. key={fieldName}
  205. title={title}
  206. tooltip={tooltip}
  207. value={value}
  208. chart={chart}
  209. horizontal
  210. minHeight={96}
  211. isNotInteractive
  212. />
  213. );
  214. })}
  215. </VitalsContainer>
  216. );
  217. }}
  218. </EventsRequest>
  219. )}
  220. </DiscoverQuery>
  221. );
  222. }
  223. function _BackendCards(props: BaseCardsProps) {
  224. const functions: Column[] = [
  225. {
  226. kind: 'function',
  227. function: ['p75', 'transaction.duration', undefined, undefined],
  228. },
  229. {kind: 'function', function: ['tpm', '', undefined, undefined]},
  230. {kind: 'function', function: ['failure_rate', '', undefined, undefined]},
  231. {
  232. kind: 'function',
  233. function: ['apdex', '', undefined, undefined],
  234. },
  235. ];
  236. return <GenericCards {...props} functions={functions} />;
  237. }
  238. export const BackendCards = _BackendCards;
  239. type MobileCardsProps = BaseCardsProps & {
  240. showStallPercentage: boolean;
  241. };
  242. function _MobileCards(props: MobileCardsProps) {
  243. const functions: Column[] = [
  244. {
  245. kind: 'function',
  246. function: ['p75', 'measurements.app_start_cold', undefined, undefined],
  247. },
  248. {
  249. kind: 'function',
  250. function: ['p75', 'measurements.app_start_warm', undefined, undefined],
  251. },
  252. {
  253. kind: 'function',
  254. function: ['p75', 'measurements.frames_slow_rate', undefined, undefined],
  255. },
  256. {
  257. kind: 'function',
  258. function: ['p75', 'measurements.frames_frozen_rate', undefined, undefined],
  259. },
  260. ];
  261. if (props.showStallPercentage) {
  262. functions.push({
  263. kind: 'function',
  264. function: ['p75', 'measurements.stall_percentage', undefined, undefined],
  265. });
  266. }
  267. return <GenericCards {...props} functions={functions} />;
  268. }
  269. export const MobileCards = _MobileCards;
  270. type SparklineChartProps = {
  271. data: number[];
  272. };
  273. function SparklineChart(props: SparklineChartProps) {
  274. const {data} = props;
  275. const width = 150;
  276. const height = 24;
  277. const lineColor = theme.charts.getColorPalette(1)[0];
  278. return (
  279. <SparklineContainer data-test-id="sparkline" width={width} height={height}>
  280. <Sparklines data={data} width={width} height={height}>
  281. <SparklinesLine style={{stroke: lineColor, fill: 'none', strokeWidth: 3}} />
  282. </Sparklines>
  283. </SparklineContainer>
  284. );
  285. }
  286. type SparklineContainerProps = {
  287. height: number;
  288. width: number;
  289. };
  290. const SparklineContainer = styled('div')<SparklineContainerProps>`
  291. flex-grow: 4;
  292. max-height: ${p => p.height}px;
  293. max-width: ${p => p.width}px;
  294. margin: ${space(1)} ${space(0)} ${space(0.5)} ${space(3)};
  295. `;
  296. const VitalsContainer = styled('div')`
  297. display: grid;
  298. grid-template-columns: 1fr;
  299. grid-column-gap: ${space(2)};
  300. @media (min-width: ${p => p.theme.breakpoints.small}) {
  301. grid-template-columns: repeat(2, 1fr);
  302. }
  303. @media (min-width: ${p => p.theme.breakpoints.large}) {
  304. grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  305. }
  306. `;
  307. type VitalBarProps = {
  308. data: VitalsData | null;
  309. isLoading: boolean;
  310. vital: WebVital | WebVital[];
  311. barHeight?: number;
  312. showBar?: boolean;
  313. showDetail?: boolean;
  314. showDurationDetail?: boolean;
  315. showStates?: boolean;
  316. showTooltip?: boolean;
  317. showVitalPercentNames?: boolean;
  318. showVitalThresholds?: boolean;
  319. value?: string;
  320. };
  321. export function VitalBar(props: VitalBarProps) {
  322. const {
  323. isLoading,
  324. data,
  325. vital,
  326. value,
  327. showBar = true,
  328. showStates = false,
  329. showDurationDetail = false,
  330. showVitalPercentNames = true,
  331. showVitalThresholds = false,
  332. showDetail = true,
  333. showTooltip = false,
  334. barHeight,
  335. } = props;
  336. if (isLoading) {
  337. return showStates ? <Placeholder height="48px" /> : null;
  338. }
  339. const emptyState = showStates ? (
  340. <EmptyVitalBar small>{t('No vitals found')}</EmptyVitalBar>
  341. ) : null;
  342. if (!data) {
  343. return emptyState;
  344. }
  345. const counts: Pick<VitalData, 'poor' | 'meh' | 'good' | 'total'> = {
  346. poor: 0,
  347. meh: 0,
  348. good: 0,
  349. total: 0,
  350. };
  351. const vitals = toArray(vital);
  352. vitals.forEach(vitalName => {
  353. const c = data?.[vitalName] ?? {};
  354. Object.keys(counts).forEach(countKey => (counts[countKey] += c[countKey]));
  355. });
  356. if (!counts.total) {
  357. return emptyState;
  358. }
  359. const p75: React.ReactNode = Array.isArray(vital)
  360. ? null
  361. : value ?? getP75(data?.[vital] ?? null, vital);
  362. const percents = getPercentsFromCounts(counts);
  363. const colorStops = getColorStopsFromPercents(percents);
  364. return (
  365. <Fragment>
  366. {showBar && (
  367. <StyledTooltip
  368. title={
  369. <VitalPercents
  370. vital={vital}
  371. percents={percents}
  372. showVitalPercentNames={false}
  373. showVitalThresholds={false}
  374. hideTooltips={showTooltip}
  375. />
  376. }
  377. disabled={!showTooltip}
  378. position="bottom"
  379. >
  380. <ColorBar barHeight={barHeight} colorStops={colorStops} />
  381. </StyledTooltip>
  382. )}
  383. {showDetail && (
  384. <BarDetail>
  385. {showDurationDetail && p75 && (
  386. <div>
  387. {t('The p75 for all transactions is ')}
  388. <strong>{p75}</strong>
  389. </div>
  390. )}
  391. <VitalPercents
  392. vital={vital}
  393. percents={percents}
  394. showVitalPercentNames={showVitalPercentNames}
  395. showVitalThresholds={showVitalThresholds}
  396. />
  397. </BarDetail>
  398. )}
  399. </Fragment>
  400. );
  401. }
  402. const EmptyVitalBar = styled(EmptyStateWarning)`
  403. height: 48px;
  404. padding: ${space(1.5)} 15%;
  405. `;
  406. type VitalCardProps = {
  407. chart: React.ReactNode;
  408. title: string;
  409. tooltip: string;
  410. value: string | number;
  411. horizontal?: boolean;
  412. isNotInteractive?: boolean;
  413. minHeight?: number;
  414. };
  415. function VitalCard(props: VitalCardProps) {
  416. const {chart, minHeight, horizontal, title, tooltip, value, isNotInteractive} = props;
  417. return (
  418. <StyledCard interactive={!isNotInteractive} minHeight={minHeight}>
  419. <HeaderTitle>
  420. <OverflowEllipsis>{title}</OverflowEllipsis>
  421. <QuestionTooltip size="sm" position="top" title={tooltip} />
  422. </HeaderTitle>
  423. <CardContent horizontal={horizontal}>
  424. <CardValue>{value}</CardValue>
  425. {chart}
  426. </CardContent>
  427. </StyledCard>
  428. );
  429. }
  430. const CardContent = styled('div')<{horizontal?: boolean}>`
  431. width: 100%;
  432. display: flex;
  433. flex-direction: ${p => (p.horizontal ? 'row' : 'column')};
  434. justify-content: space-between;
  435. `;
  436. const StyledCard = styled(Card)<{minHeight?: number}>`
  437. color: ${p => p.theme.textColor};
  438. padding: ${space(2)} ${space(3)};
  439. align-items: flex-start;
  440. margin-bottom: ${space(2)};
  441. ${p => p.minHeight && `min-height: ${p.minHeight}px`};
  442. `;
  443. const StyledTooltip = styled(Tooltip)`
  444. width: 100%;
  445. `;
  446. function getP75(data: VitalData | null, vitalName: WebVital): string {
  447. const p75 = data?.p75 ?? null;
  448. if (p75 === null) {
  449. return '\u2014';
  450. }
  451. return vitalName === WebVital.CLS ? p75.toFixed(2) : `${p75.toFixed(0)}ms`;
  452. }
  453. type Percent = {
  454. percent: number;
  455. vitalState: VitalState;
  456. };
  457. function getPercentsFromCounts({poor, meh, good, total}) {
  458. const poorPercent = poor / total;
  459. const mehPercent = meh / total;
  460. const goodPercent = good / total;
  461. const percents: Percent[] = [
  462. {
  463. vitalState: VitalState.GOOD,
  464. percent: goodPercent,
  465. },
  466. {
  467. vitalState: VitalState.MEH,
  468. percent: mehPercent,
  469. },
  470. {
  471. vitalState: VitalState.POOR,
  472. percent: poorPercent,
  473. },
  474. ];
  475. return percents;
  476. }
  477. function getColorStopsFromPercents(percents: Percent[]) {
  478. return percents.map(({percent, vitalState}) => ({
  479. percent,
  480. color: vitalStateColors[vitalState],
  481. }));
  482. }
  483. const BarDetail = styled('div')`
  484. font-size: ${p => p.theme.fontSizeMedium};
  485. @media (min-width: ${p => p.theme.breakpoints.small}) {
  486. display: flex;
  487. justify-content: space-between;
  488. }
  489. `;
  490. const CardValue = styled('div')`
  491. font-size: 32px;
  492. margin-top: ${space(1)};
  493. `;
  494. const OverflowEllipsis = styled('div')`
  495. ${p => p.theme.overflowEllipsis};
  496. `;