vitalsCards.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  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 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((allSeries, oneSeries) => {
  177. allSeries[oneSeries.seriesName] = oneSeries.data.map(item => item.value);
  178. return allSeries;
  179. }, {});
  180. const details = vitalCardDetails(organization);
  181. return (
  182. <VitalsContainer>
  183. {functions.map(func => {
  184. let fieldName = generateFieldAsString(func);
  185. if (fieldName.includes('apdex')) {
  186. // Replace apdex with explicit thresholds with a generic one for lookup
  187. fieldName = 'apdex()';
  188. }
  189. const cardDetail = details[fieldName];
  190. if (!cardDetail) {
  191. Sentry.captureMessage(`Missing field '${fieldName}' in vital cards.`);
  192. return null;
  193. }
  194. const {title, tooltip, formatter} = cardDetail;
  195. const alias = getAggregateAlias(fieldName);
  196. const rawValue = tableData?.data?.[0]?.[alias] as number;
  197. const data = series?.[fieldName];
  198. const value =
  199. isSummaryLoading || !defined(rawValue)
  200. ? '\u2014'
  201. : formatter(rawValue);
  202. const chart = <SparklineChart data={data} />;
  203. return (
  204. <VitalCard
  205. key={fieldName}
  206. title={title}
  207. tooltip={tooltip}
  208. value={value}
  209. chart={chart}
  210. horizontal
  211. minHeight={96}
  212. isNotInteractive
  213. />
  214. );
  215. })}
  216. </VitalsContainer>
  217. );
  218. }}
  219. </EventsRequest>
  220. )}
  221. </DiscoverQuery>
  222. );
  223. }
  224. function _BackendCards(props: BaseCardsProps) {
  225. const functions: Column[] = [
  226. {
  227. kind: 'function',
  228. function: ['p75', 'transaction.duration', undefined, undefined],
  229. },
  230. {kind: 'function', function: ['tpm', '', undefined, undefined]},
  231. {kind: 'function', function: ['failure_rate', '', undefined, undefined]},
  232. {
  233. kind: 'function',
  234. function: ['apdex', '', undefined, undefined],
  235. },
  236. ];
  237. return <GenericCards {...props} functions={functions} />;
  238. }
  239. export const BackendCards = _BackendCards;
  240. type MobileCardsProps = BaseCardsProps & {
  241. showStallPercentage: boolean;
  242. };
  243. function _MobileCards(props: MobileCardsProps) {
  244. const functions: Column[] = [
  245. {
  246. kind: 'function',
  247. function: ['p75', 'measurements.app_start_cold', undefined, undefined],
  248. },
  249. {
  250. kind: 'function',
  251. function: ['p75', 'measurements.app_start_warm', undefined, undefined],
  252. },
  253. {
  254. kind: 'function',
  255. function: ['p75', 'measurements.frames_slow_rate', undefined, undefined],
  256. },
  257. {
  258. kind: 'function',
  259. function: ['p75', 'measurements.frames_frozen_rate', undefined, undefined],
  260. },
  261. ];
  262. if (props.showStallPercentage) {
  263. functions.push({
  264. kind: 'function',
  265. function: ['p75', 'measurements.stall_percentage', undefined, undefined],
  266. });
  267. }
  268. return <GenericCards {...props} functions={functions} />;
  269. }
  270. export const MobileCards = _MobileCards;
  271. type SparklineChartProps = {
  272. data: number[];
  273. };
  274. function SparklineChart(props: SparklineChartProps) {
  275. const {data} = props;
  276. const width = 150;
  277. const height = 24;
  278. const lineColor = theme.charts.getColorPalette(1)[0];
  279. return (
  280. <SparklineContainer data-test-id="sparkline" width={width} height={height}>
  281. <Sparklines data={data} width={width} height={height}>
  282. <SparklinesLine style={{stroke: lineColor, fill: 'none', strokeWidth: 3}} />
  283. </Sparklines>
  284. </SparklineContainer>
  285. );
  286. }
  287. type SparklineContainerProps = {
  288. height: number;
  289. width: number;
  290. };
  291. const SparklineContainer = styled('div')<SparklineContainerProps>`
  292. flex-grow: 4;
  293. max-height: ${p => p.height}px;
  294. max-width: ${p => p.width}px;
  295. margin: ${space(1)} ${space(0)} ${space(0.5)} ${space(3)};
  296. `;
  297. const VitalsContainer = styled('div')`
  298. display: grid;
  299. grid-template-columns: 1fr;
  300. grid-column-gap: ${space(2)};
  301. @media (min-width: ${p => p.theme.breakpoints.small}) {
  302. grid-template-columns: repeat(2, 1fr);
  303. }
  304. @media (min-width: ${p => p.theme.breakpoints.large}) {
  305. grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  306. }
  307. `;
  308. type VitalBarProps = {
  309. data: VitalsData | null;
  310. isLoading: boolean;
  311. vital: WebVital | WebVital[];
  312. barHeight?: number;
  313. showBar?: boolean;
  314. showDetail?: boolean;
  315. showDurationDetail?: boolean;
  316. showStates?: boolean;
  317. showTooltip?: boolean;
  318. showVitalPercentNames?: boolean;
  319. showVitalThresholds?: boolean;
  320. value?: string;
  321. };
  322. export function VitalBar(props: VitalBarProps) {
  323. const {
  324. isLoading,
  325. data,
  326. vital,
  327. value,
  328. showBar = true,
  329. showStates = false,
  330. showDurationDetail = false,
  331. showVitalPercentNames = true,
  332. showVitalThresholds = false,
  333. showDetail = true,
  334. showTooltip = false,
  335. barHeight,
  336. } = props;
  337. if (isLoading) {
  338. return showStates ? <Placeholder height="48px" /> : null;
  339. }
  340. const emptyState = showStates ? (
  341. <EmptyVitalBar small>{t('No vitals found')}</EmptyVitalBar>
  342. ) : null;
  343. if (!data) {
  344. return emptyState;
  345. }
  346. const counts: Pick<VitalData, 'poor' | 'meh' | 'good' | 'total'> = {
  347. poor: 0,
  348. meh: 0,
  349. good: 0,
  350. total: 0,
  351. };
  352. const vitals = Array.isArray(vital) ? vital : [vital];
  353. vitals.forEach(vitalName => {
  354. const c = data?.[vitalName] ?? {};
  355. Object.keys(counts).forEach(countKey => (counts[countKey] += c[countKey]));
  356. });
  357. if (!counts.total) {
  358. return emptyState;
  359. }
  360. const p75: React.ReactNode = Array.isArray(vital)
  361. ? null
  362. : value ?? getP75(data?.[vital] ?? null, vital);
  363. const percents = getPercentsFromCounts(counts);
  364. const colorStops = getColorStopsFromPercents(percents);
  365. return (
  366. <Fragment>
  367. {showBar && (
  368. <StyledTooltip
  369. title={
  370. <VitalPercents
  371. vital={vital}
  372. percents={percents}
  373. showVitalPercentNames={false}
  374. showVitalThresholds={false}
  375. hideTooltips={showTooltip}
  376. />
  377. }
  378. disabled={!showTooltip}
  379. position="bottom"
  380. >
  381. <ColorBar barHeight={barHeight} colorStops={colorStops} />
  382. </StyledTooltip>
  383. )}
  384. {showDetail && (
  385. <BarDetail>
  386. {showDurationDetail && p75 && (
  387. <div>
  388. {t('The p75 for all transactions is ')}
  389. <strong>{p75}</strong>
  390. </div>
  391. )}
  392. <VitalPercents
  393. vital={vital}
  394. percents={percents}
  395. showVitalPercentNames={showVitalPercentNames}
  396. showVitalThresholds={showVitalThresholds}
  397. />
  398. </BarDetail>
  399. )}
  400. </Fragment>
  401. );
  402. }
  403. const EmptyVitalBar = styled(EmptyStateWarning)`
  404. height: 48px;
  405. padding: ${space(1.5)} 15%;
  406. `;
  407. type VitalCardProps = {
  408. chart: React.ReactNode;
  409. title: string;
  410. tooltip: string;
  411. value: string | number;
  412. horizontal?: boolean;
  413. isNotInteractive?: boolean;
  414. minHeight?: number;
  415. };
  416. function VitalCard(props: VitalCardProps) {
  417. const {chart, minHeight, horizontal, title, tooltip, value, isNotInteractive} = props;
  418. return (
  419. <StyledCard interactive={!isNotInteractive} minHeight={minHeight}>
  420. <HeaderTitle>
  421. <OverflowEllipsis>{t(title)}</OverflowEllipsis>
  422. <QuestionTooltip size="sm" position="top" title={tooltip} />
  423. </HeaderTitle>
  424. <CardContent horizontal={horizontal}>
  425. <CardValue>{value}</CardValue>
  426. {chart}
  427. </CardContent>
  428. </StyledCard>
  429. );
  430. }
  431. const CardContent = styled('div')<{horizontal?: boolean}>`
  432. width: 100%;
  433. display: flex;
  434. flex-direction: ${p => (p.horizontal ? 'row' : 'column')};
  435. justify-content: space-between;
  436. `;
  437. const StyledCard = styled(Card)<{minHeight?: number}>`
  438. color: ${p => p.theme.textColor};
  439. padding: ${space(2)} ${space(3)};
  440. align-items: flex-start;
  441. margin-bottom: ${space(2)};
  442. ${p => p.minHeight && `min-height: ${p.minHeight}px`};
  443. `;
  444. const StyledTooltip = styled(Tooltip)`
  445. width: 100%;
  446. `;
  447. function getP75(data: VitalData | null, vitalName: WebVital): string {
  448. const p75 = data?.p75 ?? null;
  449. if (p75 === null) {
  450. return '\u2014';
  451. }
  452. return vitalName === WebVital.CLS ? p75.toFixed(2) : `${p75.toFixed(0)}ms`;
  453. }
  454. type Percent = {
  455. percent: number;
  456. vitalState: VitalState;
  457. };
  458. function getPercentsFromCounts({poor, meh, good, total}) {
  459. const poorPercent = poor / total;
  460. const mehPercent = meh / total;
  461. const goodPercent = good / total;
  462. const percents: Percent[] = [
  463. {
  464. vitalState: VitalState.GOOD,
  465. percent: goodPercent,
  466. },
  467. {
  468. vitalState: VitalState.MEH,
  469. percent: mehPercent,
  470. },
  471. {
  472. vitalState: VitalState.POOR,
  473. percent: poorPercent,
  474. },
  475. ];
  476. return percents;
  477. }
  478. function getColorStopsFromPercents(percents: Percent[]) {
  479. return percents.map(({percent, vitalState}) => ({
  480. percent,
  481. color: vitalStateColors[vitalState],
  482. }));
  483. }
  484. const BarDetail = styled('div')`
  485. font-size: ${p => p.theme.fontSizeMedium};
  486. @media (min-width: ${p => p.theme.breakpoints.small}) {
  487. display: flex;
  488. justify-content: space-between;
  489. }
  490. `;
  491. const CardValue = styled('div')`
  492. font-size: 32px;
  493. margin-top: ${space(1)};
  494. `;
  495. const OverflowEllipsis = styled('div')`
  496. ${p => p.theme.overflowEllipsis};
  497. `;