vitalsCards.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  1. import * as React from 'react';
  2. import styled from '@emotion/styled';
  3. import * as Sentry from '@sentry/react';
  4. import {Location} from 'history';
  5. import Tooltip from 'app/components/tooltip';
  6. import Card from 'sentry/components/card';
  7. import EventsRequest from 'sentry/components/charts/eventsRequest';
  8. import {HeaderTitle} from 'sentry/components/charts/styles';
  9. import {getInterval} from 'sentry/components/charts/utils';
  10. import EmptyStateWarning from 'sentry/components/emptyStateWarning';
  11. import Link from 'sentry/components/links/link';
  12. import Placeholder from 'sentry/components/placeholder';
  13. import QuestionTooltip from 'sentry/components/questionTooltip';
  14. import Sparklines from 'sentry/components/sparklines';
  15. import SparklinesLine from 'sentry/components/sparklines/line';
  16. import {t} from 'sentry/locale';
  17. import overflowEllipsis from 'sentry/styles/overflowEllipsis';
  18. import space from 'sentry/styles/space';
  19. import {Organization, Project} from 'sentry/types';
  20. import {defined} from 'sentry/utils';
  21. import {getUtcToLocalDateObject} from 'sentry/utils/dates';
  22. import DiscoverQuery from 'sentry/utils/discover/discoverQuery';
  23. import EventView from 'sentry/utils/discover/eventView';
  24. import {
  25. Column,
  26. generateFieldAsString,
  27. getAggregateAlias,
  28. WebVital,
  29. } from 'sentry/utils/discover/fields';
  30. import {WEB_VITAL_DETAILS} from 'sentry/utils/performance/vitals/constants';
  31. import VitalsCardsDiscoverQuery, {
  32. VitalData,
  33. VitalsData,
  34. } from 'sentry/utils/performance/vitals/vitalsCardsDiscoverQuery';
  35. import {decodeList} from 'sentry/utils/queryString';
  36. import theme from 'sentry/utils/theme';
  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.getGlobalSelection();
  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];
  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. if (props.showStallPercentage) {
  256. functions.push({
  257. kind: 'function',
  258. function: ['p75', 'measurements.stall_percentage', undefined, undefined],
  259. });
  260. } else {
  261. // TODO(tonyx): add these by default once the SDKs are ready
  262. functions.push({
  263. kind: 'function',
  264. function: ['p75', 'measurements.frames_slow_rate', undefined, undefined],
  265. });
  266. functions.push({
  267. kind: 'function',
  268. function: ['p75', 'measurements.frames_frozen_rate', 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. width: number;
  292. height: 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)} ${space(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[0]}) {
  305. grid-template-columns: repeat(2, 1fr);
  306. }
  307. @media (min-width: ${p => p.theme.breakpoints[2]}) {
  308. grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  309. }
  310. `;
  311. type VitalBarProps = {
  312. isLoading: boolean;
  313. data: VitalsData | null;
  314. vital: WebVital | WebVital[];
  315. value?: string;
  316. showBar?: boolean;
  317. showStates?: boolean;
  318. showDurationDetail?: boolean;
  319. showVitalPercentNames?: boolean;
  320. showDetail?: boolean;
  321. showTooltip?: boolean;
  322. barHeight?: number;
  323. };
  324. export function VitalBar(props: VitalBarProps) {
  325. const {
  326. isLoading,
  327. data,
  328. vital,
  329. value,
  330. showBar = true,
  331. showStates = false,
  332. showDurationDetail = false,
  333. showVitalPercentNames = 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 = Array.isArray(vital) ? vital : [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. <React.Fragment>
  368. {showBar && (
  369. <StyledTooltip
  370. title={
  371. <VitalPercents
  372. vital={vital}
  373. percents={percents}
  374. showVitalPercentNames
  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 data-test-id="vital-bar-p75">
  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. />
  397. </BarDetail>
  398. )}
  399. </React.Fragment>
  400. );
  401. }
  402. const EmptyVitalBar = styled(EmptyStateWarning)`
  403. height: 48px;
  404. padding: ${space(1.5)} 15%;
  405. `;
  406. type VitalCardProps = {
  407. title: string;
  408. tooltip: string;
  409. value: string | number;
  410. chart: React.ReactNode;
  411. minHeight?: number;
  412. horizontal?: boolean;
  413. isNotInteractive?: boolean;
  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>{t(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. vitalState: VitalState;
  455. percent: number;
  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[0]}) {
  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. ${overflowEllipsis};
  496. `;