vitalsCards.tsx 15 KB

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