vitalCard.tsx 14 KB

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