vitalsCards.tsx 16 KB

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