vitalsCards.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  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 Card from 'app/components/card';
  6. import EventsRequest from 'app/components/charts/eventsRequest';
  7. import {HeaderTitle} from 'app/components/charts/styles';
  8. import {getInterval} from 'app/components/charts/utils';
  9. import EmptyStateWarning from 'app/components/emptyStateWarning';
  10. import Link from 'app/components/links/link';
  11. import Placeholder from 'app/components/placeholder';
  12. import QuestionTooltip from 'app/components/questionTooltip';
  13. import Sparklines from 'app/components/sparklines';
  14. import SparklinesLine from 'app/components/sparklines/line';
  15. import {t} from 'app/locale';
  16. import overflowEllipsis from 'app/styles/overflowEllipsis';
  17. import space from 'app/styles/space';
  18. import {Organization, Project} from 'app/types';
  19. import {defined} from 'app/utils';
  20. import {getUtcToLocalDateObject} from 'app/utils/dates';
  21. import DiscoverQuery from 'app/utils/discover/discoverQuery';
  22. import EventView from 'app/utils/discover/eventView';
  23. import {
  24. Column,
  25. generateFieldAsString,
  26. getAggregateAlias,
  27. WebVital,
  28. } from 'app/utils/discover/fields';
  29. import {WEB_VITAL_DETAILS} from 'app/utils/performance/vitals/constants';
  30. import VitalsCardsDiscoverQuery, {
  31. VitalData,
  32. VitalsData,
  33. } from 'app/utils/performance/vitals/vitalsCardsDiscoverQuery';
  34. import {decodeList} from 'app/utils/queryString';
  35. import theme from 'app/utils/theme';
  36. import useApi from 'app/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.getGlobalSelection();
  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];
  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. if (props.showStallPercentage) {
  255. functions.push({
  256. kind: 'function',
  257. function: ['p75', 'measurements.stall_percentage', undefined, undefined],
  258. });
  259. } else {
  260. // TODO(tonyx): add these by default once the SDKs are ready
  261. functions.push({
  262. kind: 'function',
  263. function: ['p75', 'measurements.frames_slow_rate', undefined, undefined],
  264. });
  265. functions.push({
  266. kind: 'function',
  267. function: ['p75', 'measurements.frames_frozen_rate', undefined, undefined],
  268. });
  269. }
  270. return <GenericCards {...props} functions={functions} />;
  271. }
  272. export const MobileCards = _MobileCards;
  273. type SparklineChartProps = {
  274. data: number[];
  275. };
  276. function SparklineChart(props: SparklineChartProps) {
  277. const {data} = props;
  278. const width = 150;
  279. const height = 24;
  280. const lineColor = theme.charts.getColorPalette(1)[0];
  281. return (
  282. <SparklineContainer data-test-id="sparkline" width={width} height={height}>
  283. <Sparklines data={data} width={width} height={height}>
  284. <SparklinesLine style={{stroke: lineColor, fill: 'none', strokeWidth: 3}} />
  285. </Sparklines>
  286. </SparklineContainer>
  287. );
  288. }
  289. type SparklineContainerProps = {
  290. width: number;
  291. height: number;
  292. };
  293. const SparklineContainer = styled('div')<SparklineContainerProps>`
  294. flex-grow: 4;
  295. max-height: ${p => p.height}px;
  296. max-width: ${p => p.width}px;
  297. margin: ${space(1)} ${space(0)} ${space(0.5)} ${space(3)};
  298. `;
  299. const VitalsContainer = styled('div')`
  300. display: grid;
  301. grid-template-columns: 1fr;
  302. grid-column-gap: ${space(2)};
  303. @media (min-width: ${p => p.theme.breakpoints[0]}) {
  304. grid-template-columns: repeat(2, 1fr);
  305. }
  306. @media (min-width: ${p => p.theme.breakpoints[2]}) {
  307. grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  308. }
  309. `;
  310. type VitalBarProps = {
  311. isLoading: boolean;
  312. data: VitalsData | null;
  313. vital: WebVital | WebVital[];
  314. value?: string;
  315. showBar?: boolean;
  316. showStates?: boolean;
  317. showDurationDetail?: boolean;
  318. showVitalPercentNames?: boolean;
  319. showDetail?: boolean;
  320. barHeight?: number;
  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 = false,
  332. showDetail = true,
  333. barHeight,
  334. } = props;
  335. if (isLoading) {
  336. return showStates ? <Placeholder height="48px" /> : null;
  337. }
  338. const emptyState = showStates ? (
  339. <EmptyVitalBar small>{t('No vitals found')}</EmptyVitalBar>
  340. ) : null;
  341. if (!data) {
  342. return emptyState;
  343. }
  344. const counts: Pick<VitalData, 'poor' | 'meh' | 'good' | 'total'> = {
  345. poor: 0,
  346. meh: 0,
  347. good: 0,
  348. total: 0,
  349. };
  350. const vitals = Array.isArray(vital) ? vital : [vital];
  351. vitals.forEach(vitalName => {
  352. const c = data?.[vitalName] ?? {};
  353. Object.keys(counts).forEach(countKey => (counts[countKey] += c[countKey]));
  354. });
  355. if (!counts.total) {
  356. return emptyState;
  357. }
  358. const p75: React.ReactNode = Array.isArray(vital)
  359. ? null
  360. : value ?? getP75(data?.[vital] ?? null, vital);
  361. const percents = getPercentsFromCounts(counts);
  362. const colorStops = getColorStopsFromPercents(percents);
  363. return (
  364. <React.Fragment>
  365. {showBar && <ColorBar barHeight={barHeight} colorStops={colorStops} />}
  366. {showDetail && (
  367. <BarDetail>
  368. {showDurationDetail && p75 && (
  369. <div data-test-id="vital-bar-p75">
  370. {t('The p75 for all transactions is ')}
  371. <strong>{p75}</strong>
  372. </div>
  373. )}
  374. <VitalPercents
  375. vital={vital}
  376. percents={percents}
  377. showVitalPercentNames={showVitalPercentNames}
  378. />
  379. </BarDetail>
  380. )}
  381. </React.Fragment>
  382. );
  383. }
  384. const EmptyVitalBar = styled(EmptyStateWarning)`
  385. height: 48px;
  386. padding: ${space(1.5)} 15%;
  387. `;
  388. type VitalCardProps = {
  389. title: string;
  390. tooltip: string;
  391. value: string | number;
  392. chart: React.ReactNode;
  393. minHeight?: number;
  394. horizontal?: boolean;
  395. isNotInteractive?: boolean;
  396. };
  397. function VitalCard(props: VitalCardProps) {
  398. const {chart, minHeight, horizontal, title, tooltip, value, isNotInteractive} = props;
  399. return (
  400. <StyledCard interactive={!isNotInteractive} minHeight={minHeight}>
  401. <HeaderTitle>
  402. <OverflowEllipsis>{t(title)}</OverflowEllipsis>
  403. <QuestionTooltip size="sm" position="top" title={tooltip} />
  404. </HeaderTitle>
  405. <CardContent horizontal={horizontal}>
  406. <CardValue>{value}</CardValue>
  407. {chart}
  408. </CardContent>
  409. </StyledCard>
  410. );
  411. }
  412. const CardContent = styled('div')<{horizontal?: boolean}>`
  413. width: 100%;
  414. display: flex;
  415. flex-direction: ${p => (p.horizontal ? 'row' : 'column')};
  416. justify-content: space-between;
  417. `;
  418. const StyledCard = styled(Card)<{minHeight?: number}>`
  419. color: ${p => p.theme.textColor};
  420. padding: ${space(2)} ${space(3)};
  421. align-items: flex-start;
  422. margin-bottom: ${space(2)};
  423. ${p => p.minHeight && `min-height: ${p.minHeight}px`};
  424. `;
  425. function getP75(data: VitalData | null, vitalName: WebVital): string {
  426. const p75 = data?.p75 ?? null;
  427. if (p75 === null) {
  428. return '\u2014';
  429. } else {
  430. return vitalName === WebVital.CLS ? p75.toFixed(2) : `${p75.toFixed(0)}ms`;
  431. }
  432. }
  433. type Percent = {
  434. vitalState: VitalState;
  435. percent: number;
  436. };
  437. function getPercentsFromCounts({poor, meh, good, total}) {
  438. const poorPercent = poor / total;
  439. const mehPercent = meh / total;
  440. const goodPercent = good / total;
  441. const percents: Percent[] = [
  442. {
  443. vitalState: VitalState.GOOD,
  444. percent: goodPercent,
  445. },
  446. {
  447. vitalState: VitalState.MEH,
  448. percent: mehPercent,
  449. },
  450. {
  451. vitalState: VitalState.POOR,
  452. percent: poorPercent,
  453. },
  454. ];
  455. return percents;
  456. }
  457. function getColorStopsFromPercents(percents: Percent[]) {
  458. return percents.map(({percent, vitalState}) => ({
  459. percent,
  460. color: vitalStateColors[vitalState],
  461. }));
  462. }
  463. const BarDetail = styled('div')`
  464. font-size: ${p => p.theme.fontSizeMedium};
  465. @media (min-width: ${p => p.theme.breakpoints[0]}) {
  466. display: flex;
  467. justify-content: space-between;
  468. }
  469. `;
  470. const CardValue = styled('div')`
  471. font-size: 32px;
  472. margin-top: ${space(1)};
  473. `;
  474. const OverflowEllipsis = styled('div')`
  475. ${overflowEllipsis};
  476. `;