vitalCard.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. import {Component} from 'react';
  2. import type {Theme} from '@emotion/react';
  3. import {withTheme} from '@emotion/react';
  4. import styled from '@emotion/styled';
  5. import type {Location} from 'history';
  6. import isEqual from 'lodash/isEqual';
  7. import throttle from 'lodash/throttle';
  8. import {Button} from 'sentry/components/button';
  9. import type {BarChartSeries} from 'sentry/components/charts/barChart';
  10. import {BarChart} from 'sentry/components/charts/barChart';
  11. import BarChartZoom from 'sentry/components/charts/barChartZoom';
  12. import MarkLine from 'sentry/components/charts/components/markLine';
  13. import TransparentLoadingMask from 'sentry/components/charts/transparentLoadingMask';
  14. import Placeholder from 'sentry/components/placeholder';
  15. import {t} from 'sentry/locale';
  16. import {space} from 'sentry/styles/space';
  17. import type {Organization} from 'sentry/types/organization';
  18. import {trackAnalytics} from 'sentry/utils/analytics';
  19. import type EventView from 'sentry/utils/discover/eventView';
  20. import {getAggregateAlias} from 'sentry/utils/discover/fields';
  21. import getDuration from 'sentry/utils/duration/getDuration';
  22. import type {WebVital} from 'sentry/utils/fields';
  23. import {formatAbbreviatedNumber, formatFloat} from 'sentry/utils/formatters';
  24. import getDynamicText from 'sentry/utils/getDynamicText';
  25. import type {DataFilter, HistogramData} from 'sentry/utils/performance/histogram/types';
  26. import {
  27. computeBuckets,
  28. formatHistogramData,
  29. } from 'sentry/utils/performance/histogram/utils';
  30. import type {Vital} from 'sentry/utils/performance/vitals/types';
  31. import type {VitalData} from 'sentry/utils/performance/vitals/vitalsCardsDiscoverQuery';
  32. import {MutableSearch} from 'sentry/utils/tokenizeSearch';
  33. import {EventsDisplayFilterName} from 'sentry/views/performance/transactionSummary/transactionEvents/utils';
  34. import {VitalBar} from '../../landing/vitalsCards';
  35. import {
  36. VitalState,
  37. vitalStateColors,
  38. webVitalMeh,
  39. webVitalPoor,
  40. } from '../../vitalDetail/utils';
  41. import {NUM_BUCKETS, PERCENTILE} from './constants';
  42. import {Card, CardSectionHeading, CardSummary, Description, StatNumber} from './styles';
  43. import type {Rectangle} from './types';
  44. import {asPixelRect, findNearestBucketIndex, getRefRect, mapPoint} from './utils';
  45. type Props = {
  46. chartData: HistogramData;
  47. colors: [string];
  48. error: boolean;
  49. eventView: EventView;
  50. isLoading: boolean;
  51. location: Location;
  52. organization: Organization;
  53. summaryData: VitalData | null;
  54. theme: Theme;
  55. vital: WebVital;
  56. vitalDetails: Vital;
  57. dataFilter?: DataFilter;
  58. max?: number;
  59. min?: number;
  60. precision?: number;
  61. };
  62. type State = {
  63. /**
  64. * This is a pair of reference points on the graph that we can use to map any
  65. * other points to their pixel coordinates on the graph.
  66. *
  67. * The x values here are the index of the cooresponding bucket and the y value
  68. * are the respective counts.
  69. *
  70. * Invariances:
  71. * - refDataRect.point1.x < refDataRect.point2.x
  72. * - refDataRect.point1.y < refDataRect.point2.y
  73. */
  74. refDataRect: Rectangle | null;
  75. /**
  76. * This is the cooresponding pixel coordinate of the references points from refDataRect.
  77. *
  78. * ECharts' pixel coordinates are relative to the top left whereas the axis coordinates
  79. * used here are relative to the bottom right. Because of this and the invariances imposed
  80. * on refDataRect, these points have the difference invariances.
  81. *
  82. * Invariances:
  83. * - refPixelRect.point1.x < refPixelRect.point2.x
  84. * - refPixelRect.point1.y > refPixelRect.point2.y
  85. */
  86. refPixelRect: Rectangle | null;
  87. };
  88. class VitalCard extends Component<Props, State> {
  89. state: State = {
  90. refDataRect: null,
  91. refPixelRect: null,
  92. };
  93. static getDerivedStateFromProps(nextProps: Readonly<Props>, prevState: State) {
  94. const {isLoading, error, chartData} = nextProps;
  95. if (isLoading || error === null) {
  96. return {...prevState};
  97. }
  98. const refDataRect = getRefRect(chartData);
  99. if (
  100. prevState.refDataRect === null ||
  101. (refDataRect !== null && !isEqual(refDataRect, prevState.refDataRect))
  102. ) {
  103. return {
  104. ...prevState,
  105. refDataRect,
  106. };
  107. }
  108. return {...prevState};
  109. }
  110. trackOpenInDiscoverClicked = () => {
  111. const {organization} = this.props;
  112. const {vitalDetails: vital} = this.props;
  113. trackAnalytics('performance_views.vitals.open_in_discover', {
  114. organization,
  115. vital: vital.slug,
  116. });
  117. };
  118. trackOpenAllEventsClicked = () => {
  119. const {organization} = this.props;
  120. const {vitalDetails: vital} = this.props;
  121. trackAnalytics('performance_views.vitals.open_all_events', {
  122. organization,
  123. vital: vital.slug,
  124. });
  125. };
  126. get summary() {
  127. const {summaryData} = this.props;
  128. return summaryData?.p75 ?? null;
  129. }
  130. get failureRate() {
  131. const {summaryData} = this.props;
  132. const numerator = summaryData?.poor ?? 0;
  133. const denominator = summaryData?.total ?? 0;
  134. return denominator <= 0 ? 0 : numerator / denominator;
  135. }
  136. getFormattedStatNumber() {
  137. const {vitalDetails: vital} = this.props;
  138. const summary = this.summary;
  139. const {type} = vital;
  140. return summary === null
  141. ? '\u2014'
  142. : type === 'duration'
  143. ? getDuration(summary / 1000, 2, true)
  144. : formatFloat(summary, 2);
  145. }
  146. renderSummary() {
  147. const {
  148. vitalDetails: vital,
  149. eventView,
  150. organization,
  151. min,
  152. max,
  153. dataFilter,
  154. } = this.props;
  155. const {slug, name, description} = vital;
  156. const column = `measurements.${slug}`;
  157. const newEventView = eventView
  158. .withColumns([
  159. {kind: 'field', field: 'transaction'},
  160. {
  161. kind: 'function',
  162. function: ['percentile', column, PERCENTILE.toString(), undefined],
  163. },
  164. {kind: 'function', function: ['count', '', '', undefined]},
  165. ])
  166. .withSorts([
  167. {
  168. kind: 'desc',
  169. field: getAggregateAlias(`percentile(${column},${PERCENTILE.toString()})`),
  170. },
  171. ]);
  172. const query = new MutableSearch(newEventView.query ?? '');
  173. query.addFilterValues('has', [column]);
  174. // add in any range constraints if any
  175. if (min !== undefined || max !== undefined) {
  176. if (min !== undefined) {
  177. query.addFilterValues(column, [`>=${min}`]);
  178. }
  179. if (max !== undefined) {
  180. query.addFilterValues(column, [`<=${max}`]);
  181. }
  182. }
  183. newEventView.query = query.formatString();
  184. return (
  185. <CardSummary>
  186. <SummaryHeading>
  187. <CardSectionHeading>{`${name} (${slug.toUpperCase()})`}</CardSectionHeading>
  188. </SummaryHeading>
  189. <StatNumber>
  190. {getDynamicText({
  191. value: this.getFormattedStatNumber(),
  192. fixed: '\u2014',
  193. })}
  194. </StatNumber>
  195. <Description>{description}</Description>
  196. <div>
  197. <Button
  198. size="xs"
  199. to={newEventView
  200. .withColumns([{kind: 'field', field: column}])
  201. .withSorts([{kind: 'desc', field: column}])
  202. .getPerformanceTransactionEventsViewUrlTarget(organization.slug, {
  203. showTransactions:
  204. dataFilter === 'all'
  205. ? EventsDisplayFilterName.P100
  206. : EventsDisplayFilterName.P75,
  207. webVital: column as WebVital,
  208. })}
  209. onClick={this.trackOpenAllEventsClicked}
  210. >
  211. {t('View Sampled Events')}
  212. </Button>
  213. </div>
  214. </CardSummary>
  215. );
  216. }
  217. /**
  218. * This callback happens everytime ECharts renders. This is NOT when ECharts
  219. * finishes rendering, so it can be called quite frequently. The calculations
  220. * here can get expensive if done frequently, furthermore, this can trigger a
  221. * state change leading to a re-render. So slow down the updates here as they
  222. * do not need to be updated every single time.
  223. */
  224. handleRendered = throttle(
  225. (_, chartRef) => {
  226. const {chartData} = this.props;
  227. const {refDataRect} = this.state;
  228. if (refDataRect === null || chartData.length < 1) {
  229. return;
  230. }
  231. const refPixelRect =
  232. refDataRect === null ? null : asPixelRect(chartRef, refDataRect!);
  233. if (refPixelRect !== null && !isEqual(refPixelRect, this.state.refPixelRect)) {
  234. this.setState({refPixelRect});
  235. }
  236. },
  237. 200,
  238. {leading: true}
  239. );
  240. handleDataZoomCancelled = () => {};
  241. renderHistogram() {
  242. const {
  243. theme,
  244. location,
  245. isLoading,
  246. chartData,
  247. summaryData,
  248. error,
  249. colors,
  250. vital,
  251. vitalDetails,
  252. precision = 0,
  253. } = this.props;
  254. const {slug} = vitalDetails;
  255. const series = this.getSeries();
  256. const xAxis = {
  257. type: 'category' as const,
  258. truncate: true,
  259. axisTick: {
  260. alignWithLabel: true,
  261. },
  262. };
  263. const values = series.data.map(point => point.value);
  264. const max = values.length ? Math.max(...values) : undefined;
  265. const yAxis = {
  266. type: 'value' as const,
  267. max,
  268. axisLabel: {
  269. color: theme.chartLabel,
  270. formatter: (value: string | number) => formatAbbreviatedNumber(value),
  271. },
  272. };
  273. const allSeries = [series];
  274. if (!isLoading && !error) {
  275. const baselineSeries = this.getBaselineSeries();
  276. if (baselineSeries !== null) {
  277. allSeries.push(baselineSeries);
  278. }
  279. }
  280. const vitalData =
  281. !isLoading && !error && summaryData !== null ? {[vital]: summaryData} : {};
  282. return (
  283. <BarChartZoom
  284. minZoomWidth={10 ** -precision * NUM_BUCKETS}
  285. location={location}
  286. paramStart={`${slug}Start`}
  287. paramEnd={`${slug}End`}
  288. xAxisIndex={[0]}
  289. buckets={computeBuckets(chartData)}
  290. onDataZoomCancelled={this.handleDataZoomCancelled}
  291. >
  292. {zoomRenderProps => (
  293. <Container>
  294. <TransparentLoadingMask visible={isLoading} />
  295. <PercentContainer>
  296. <VitalBar
  297. isLoading={isLoading}
  298. data={vitalData}
  299. vital={vital}
  300. showBar={false}
  301. showStates={false}
  302. showVitalPercentNames={false}
  303. showVitalThresholds={false}
  304. showDurationDetail={false}
  305. />
  306. </PercentContainer>
  307. {getDynamicText({
  308. value: (
  309. <BarChart
  310. series={allSeries}
  311. xAxis={xAxis}
  312. yAxis={yAxis}
  313. colors={colors}
  314. onRendered={this.handleRendered}
  315. grid={{
  316. left: space(3),
  317. right: space(3),
  318. top: space(3),
  319. bottom: space(1.5),
  320. }}
  321. stacked
  322. {...zoomRenderProps}
  323. />
  324. ),
  325. fixed: <Placeholder testId="skeleton-ui" height="200px" />,
  326. })}
  327. </Container>
  328. )}
  329. </BarChartZoom>
  330. );
  331. }
  332. bucketWidth() {
  333. const {chartData} = this.props;
  334. // We can assume that all buckets are of equal width, use the first two
  335. // buckets to get the width. The value of each histogram function indicates
  336. // the beginning of the bucket.
  337. return chartData.length >= 2 ? chartData[1].bin - chartData[0].bin : 0;
  338. }
  339. getSeries() {
  340. const {theme, chartData, precision, vitalDetails, vital} = this.props;
  341. const additionalFieldsFn = bucket => {
  342. return {
  343. itemStyle: {color: theme[this.getVitalsColor(vital, bucket)]},
  344. };
  345. };
  346. const data = formatHistogramData(chartData, {
  347. precision: precision === 0 ? undefined : precision,
  348. type: vitalDetails.type,
  349. additionalFieldsFn,
  350. });
  351. return {
  352. seriesName: t('Count'),
  353. data,
  354. };
  355. }
  356. getVitalsColor(vital: WebVital, value: number) {
  357. const poorThreshold = webVitalPoor[vital];
  358. const mehThreshold = webVitalMeh[vital];
  359. if (value >= poorThreshold) {
  360. return vitalStateColors[VitalState.POOR];
  361. }
  362. if (value >= mehThreshold) {
  363. return vitalStateColors[VitalState.MEH];
  364. }
  365. return vitalStateColors[VitalState.GOOD];
  366. }
  367. getBaselineSeries(): BarChartSeries | null {
  368. const {theme, chartData} = this.props;
  369. const summary = this.summary;
  370. if (summary === null || this.state.refPixelRect === null) {
  371. return null;
  372. }
  373. const summaryBucket = findNearestBucketIndex(chartData, summary);
  374. if (summaryBucket === null || summaryBucket === -1) {
  375. return null;
  376. }
  377. const thresholdPixelBottom = mapPoint(
  378. {
  379. // subtract 0.5 from the x here to ensure that the threshold lies between buckets
  380. x: summaryBucket - 0.5,
  381. y: 0,
  382. },
  383. this.state.refDataRect!,
  384. this.state.refPixelRect!
  385. );
  386. if (thresholdPixelBottom === null) {
  387. return null;
  388. }
  389. const thresholdPixelTop = mapPoint(
  390. {
  391. // subtract 0.5 from the x here to ensure that the threshold lies between buckets
  392. x: summaryBucket - 0.5,
  393. y: Math.max(...chartData.map(data => data.count)) || 1,
  394. },
  395. this.state.refDataRect!,
  396. this.state.refPixelRect!
  397. );
  398. if (thresholdPixelTop === null) {
  399. return null;
  400. }
  401. const markLine = MarkLine({
  402. animationDuration: 200,
  403. data: [[thresholdPixelBottom, thresholdPixelTop] as any],
  404. label: {
  405. show: false,
  406. },
  407. lineStyle: {
  408. color: theme.textColor,
  409. type: 'solid',
  410. },
  411. tooltip: {
  412. formatter: () => {
  413. return [
  414. '<div class="tooltip-series tooltip-series-solo">',
  415. '<span class="tooltip-label">',
  416. `<strong>${t('p75')}</strong>`,
  417. '</span>',
  418. '</div>',
  419. '<div class="tooltip-arrow"></div>',
  420. ].join('');
  421. },
  422. },
  423. });
  424. return {
  425. seriesName: t('p75'),
  426. data: [],
  427. markLine,
  428. };
  429. }
  430. render() {
  431. return (
  432. <Card>
  433. {this.renderSummary()}
  434. {this.renderHistogram()}
  435. </Card>
  436. );
  437. }
  438. }
  439. const SummaryHeading = styled('div')`
  440. display: flex;
  441. justify-content: space-between;
  442. `;
  443. const Container = styled('div')`
  444. position: relative;
  445. `;
  446. const PercentContainer = styled('div')`
  447. position: absolute;
  448. top: ${space(2)};
  449. right: ${space(3)};
  450. z-index: 2;
  451. `;
  452. export default withTheme(VitalCard);