vitalsCards.tsx 13 KB

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