vitalsCards.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  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. return (
  138. <DiscoverQuery
  139. location={location}
  140. eventView={eventView}
  141. orgSlug={organization.slug}
  142. limit={1}
  143. referrer="api.performance.vitals-cards"
  144. >
  145. {({isLoading: isSummaryLoading, tableData}) => (
  146. <EventsRequest
  147. api={api}
  148. organization={organization}
  149. period={globalSelection.datetime.period}
  150. project={globalSelection.projects}
  151. environment={globalSelection.environments}
  152. start={start}
  153. end={end}
  154. interval={getInterval({
  155. start: start || null,
  156. end: end || null,
  157. period: globalSelection.datetime.period,
  158. })}
  159. query={eventView.getEventsAPIPayload(location).query}
  160. includePrevious={false}
  161. yAxis={eventView.getFields()}
  162. partial
  163. >
  164. {({results}) => {
  165. const series = results?.reduce((allSeries, oneSeries) => {
  166. allSeries[oneSeries.seriesName] = oneSeries.data.map(item => item.value);
  167. return allSeries;
  168. }, {});
  169. const fields = eventView
  170. .getFields()
  171. .map((fn, i) => [functionNames[i], fn, series?.[fn]]);
  172. return (
  173. <VitalsContainer>
  174. {fields.map(([name, fn, data]) => {
  175. const {title, tooltip, formatter} = backendCardDetails(organization)[
  176. name
  177. ];
  178. const alias = getAggregateAlias(fn);
  179. const rawValue = tableData?.data?.[0]?.[alias];
  180. const value =
  181. isSummaryLoading || rawValue === undefined
  182. ? '\u2014'
  183. : formatter(rawValue);
  184. const chart = <SparklineChart data={data} />;
  185. return (
  186. <VitalCard
  187. key={name}
  188. title={title}
  189. tooltip={tooltip}
  190. value={value}
  191. chart={chart}
  192. horizontal
  193. minHeight={96}
  194. isNotInteractive
  195. />
  196. );
  197. })}
  198. </VitalsContainer>
  199. );
  200. }}
  201. </EventsRequest>
  202. )}
  203. </DiscoverQuery>
  204. );
  205. }
  206. export const BackendCards = withApi(_BackendCards);
  207. type SparklineChartProps = {
  208. data: number[];
  209. };
  210. function SparklineChart(props: SparklineChartProps) {
  211. const {data} = props;
  212. const width = 150;
  213. const height = 24;
  214. const lineColor = theme.charts.getColorPalette(1)[0];
  215. return (
  216. <SparklineContainer data-test-id="sparkline" width={width} height={height}>
  217. <Sparklines data={data} width={width} height={height}>
  218. <SparklinesLine style={{stroke: lineColor, fill: 'none', strokeWidth: 3}} />
  219. </Sparklines>
  220. </SparklineContainer>
  221. );
  222. }
  223. type SparklineContainerProps = {
  224. width: number;
  225. height: number;
  226. };
  227. const SparklineContainer = styled('div')<SparklineContainerProps>`
  228. flex-grow: 4;
  229. max-height: ${p => p.height}px;
  230. max-width: ${p => p.width}px;
  231. margin: ${space(1)} ${space(0)} ${space(0.5)} ${space(3)};
  232. `;
  233. const VitalsContainer = styled('div')`
  234. display: grid;
  235. grid-template-columns: 1fr;
  236. grid-column-gap: ${space(2)};
  237. @media (min-width: ${p => p.theme.breakpoints[0]}) {
  238. grid-template-columns: repeat(2, 1fr);
  239. }
  240. @media (min-width: ${p => p.theme.breakpoints[2]}) {
  241. grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  242. }
  243. `;
  244. type VitalBarProps = {
  245. isLoading: boolean;
  246. data: VitalsData | null;
  247. vital: WebVital | WebVital[];
  248. value?: string;
  249. showBar?: boolean;
  250. showStates?: boolean;
  251. showDurationDetail?: boolean;
  252. showVitalPercentNames?: boolean;
  253. };
  254. export function VitalBar(props: VitalBarProps) {
  255. const {
  256. isLoading,
  257. data,
  258. vital,
  259. value,
  260. showBar = true,
  261. showStates = false,
  262. showDurationDetail = false,
  263. showVitalPercentNames = false,
  264. } = props;
  265. if (isLoading) {
  266. return showStates ? <Placeholder height="48px" /> : null;
  267. }
  268. const emptyState = showStates ? (
  269. <EmptyVitalBar small>{t('No vitals found')}</EmptyVitalBar>
  270. ) : null;
  271. if (!data) {
  272. return emptyState;
  273. }
  274. const counts: Pick<VitalData, 'poor' | 'meh' | 'good' | 'total'> = {
  275. poor: 0,
  276. meh: 0,
  277. good: 0,
  278. total: 0,
  279. };
  280. const vitals = Array.isArray(vital) ? vital : [vital];
  281. vitals.forEach(vitalName => {
  282. const c = data?.[vitalName] ?? {};
  283. Object.keys(counts).forEach(countKey => (counts[countKey] += c[countKey]));
  284. });
  285. if (!counts.total) {
  286. return emptyState;
  287. }
  288. const p75: React.ReactNode = Array.isArray(vital)
  289. ? null
  290. : value ?? getP75(data?.[vital] ?? null, vital);
  291. const percents = getPercentsFromCounts(counts);
  292. const colorStops = getColorStopsFromPercents(percents);
  293. return (
  294. <React.Fragment>
  295. {showBar && <ColorBar colorStops={colorStops} />}
  296. <BarDetail>
  297. {showDurationDetail && p75 && (
  298. <div data-test-id="vital-bar-p75">
  299. {t('The p75 for all transactions is ')}
  300. <strong>{p75}</strong>
  301. </div>
  302. )}
  303. <VitalPercents
  304. vital={vital}
  305. percents={percents}
  306. showVitalPercentNames={showVitalPercentNames}
  307. />
  308. </BarDetail>
  309. </React.Fragment>
  310. );
  311. }
  312. const EmptyVitalBar = styled(EmptyStateWarning)`
  313. height: 48px;
  314. padding: ${space(1.5)} 15%;
  315. `;
  316. type VitalCardProps = {
  317. title: string;
  318. tooltip: string;
  319. value: string;
  320. chart: React.ReactNode;
  321. minHeight?: number;
  322. horizontal?: boolean;
  323. isNotInteractive?: boolean;
  324. };
  325. function VitalCard(props: VitalCardProps) {
  326. const {chart, minHeight, horizontal, title, tooltip, value, isNotInteractive} = props;
  327. return (
  328. <StyledCard interactive={!isNotInteractive} minHeight={minHeight}>
  329. <HeaderTitle>
  330. <OverflowEllipsis>{t(title)}</OverflowEllipsis>
  331. <QuestionTooltip size="sm" position="top" title={tooltip} />
  332. </HeaderTitle>
  333. <CardContent horizontal={horizontal}>
  334. <CardValue>{value}</CardValue>
  335. {chart}
  336. </CardContent>
  337. </StyledCard>
  338. );
  339. }
  340. const CardContent = styled('div')<{horizontal?: boolean}>`
  341. width: 100%;
  342. display: flex;
  343. flex-direction: ${p => (p.horizontal ? 'row' : 'column')};
  344. justify-content: space-between;
  345. `;
  346. const StyledCard = styled(Card)<{minHeight?: number}>`
  347. color: ${p => p.theme.textColor};
  348. padding: ${space(2)} ${space(3)};
  349. align-items: flex-start;
  350. margin-bottom: ${space(2)};
  351. ${p => p.minHeight && `min-height: ${p.minHeight}px`};
  352. `;
  353. function getP75(data: VitalData | null, vitalName: WebVital): string {
  354. const p75 = data?.p75 ?? null;
  355. if (p75 === null) {
  356. return '\u2014';
  357. } else {
  358. return vitalName === WebVital.CLS ? p75.toFixed(2) : `${p75.toFixed(0)}ms`;
  359. }
  360. }
  361. type Percent = {
  362. vitalState: VitalState;
  363. percent: number;
  364. };
  365. function getPercentsFromCounts({poor, meh, good, total}) {
  366. const poorPercent = poor / total;
  367. const mehPercent = meh / total;
  368. const goodPercent = good / total;
  369. const percents: Percent[] = [
  370. {
  371. vitalState: VitalState.GOOD,
  372. percent: goodPercent,
  373. },
  374. {
  375. vitalState: VitalState.MEH,
  376. percent: mehPercent,
  377. },
  378. {
  379. vitalState: VitalState.POOR,
  380. percent: poorPercent,
  381. },
  382. ];
  383. return percents;
  384. }
  385. function getColorStopsFromPercents(percents: Percent[]) {
  386. return percents.map(({percent, vitalState}) => ({
  387. percent,
  388. color: vitalStateColors[vitalState],
  389. }));
  390. }
  391. const BarDetail = styled('div')`
  392. font-size: ${p => p.theme.fontSizeMedium};
  393. @media (min-width: ${p => p.theme.breakpoints[0]}) {
  394. display: flex;
  395. justify-content: space-between;
  396. }
  397. `;
  398. const CardValue = styled('div')`
  399. font-size: 32px;
  400. margin-top: ${space(1)};
  401. `;
  402. const OverflowEllipsis = styled('div')`
  403. ${overflowEllipsis};
  404. `;