chart.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. import {Component} from 'react';
  2. import {browserHistory, withRouter, WithRouterProps} from 'react-router';
  3. import {withTheme} from '@emotion/react';
  4. import {Client} from 'app/api';
  5. import ChartZoom from 'app/components/charts/chartZoom';
  6. import LineChart from 'app/components/charts/lineChart';
  7. import ReleaseSeries from 'app/components/charts/releaseSeries';
  8. import TransitionChart from 'app/components/charts/transitionChart';
  9. import TransparentLoadingMask from 'app/components/charts/transparentLoadingMask';
  10. import {getParams} from 'app/components/organizations/globalSelectionHeader/getParams';
  11. import {t} from 'app/locale';
  12. import {EventsStatsData, OrganizationSummary, Project} from 'app/types';
  13. import {Series} from 'app/types/echarts';
  14. import {getUtcToLocalDateObject} from 'app/utils/dates';
  15. import {axisLabelFormatter, tooltipFormatter} from 'app/utils/discover/charts';
  16. import EventView from 'app/utils/discover/eventView';
  17. import getDynamicText from 'app/utils/getDynamicText';
  18. import {decodeList} from 'app/utils/queryString';
  19. import {Theme} from 'app/utils/theme';
  20. import withApi from 'app/utils/withApi';
  21. import {YAxis} from 'app/views/releases/detail/overview/chart/releaseChartControls';
  22. import {NormalizedTrendsTransaction, TrendChangeType, TrendsStats} from './types';
  23. import {
  24. generateTrendFunctionAsString,
  25. getCurrentTrendFunction,
  26. getCurrentTrendParameter,
  27. getUnselectedSeries,
  28. transformEventStatsSmoothed,
  29. trendToColor,
  30. } from './utils';
  31. const QUERY_KEYS = [
  32. 'environment',
  33. 'project',
  34. 'query',
  35. 'start',
  36. 'end',
  37. 'statsPeriod',
  38. ] as const;
  39. type ViewProps = Pick<EventView, typeof QUERY_KEYS[number]>;
  40. type Props = WithRouterProps &
  41. ViewProps & {
  42. theme: Theme;
  43. api: Client;
  44. location: Location;
  45. organization: OrganizationSummary;
  46. trendChangeType: TrendChangeType;
  47. transaction?: NormalizedTrendsTransaction;
  48. isLoading: boolean;
  49. statsData: TrendsStats;
  50. projects: Project[];
  51. };
  52. function transformEventStats(data: EventsStatsData, seriesName?: string): Series[] {
  53. return [
  54. {
  55. seriesName: seriesName || 'Current',
  56. data: data.map(([timestamp, countsForTimestamp]) => ({
  57. name: timestamp * 1000,
  58. value: countsForTimestamp.reduce((acc, {count}) => acc + count, 0),
  59. })),
  60. },
  61. ];
  62. }
  63. function getLegend(trendFunction: string) {
  64. return {
  65. right: 10,
  66. top: 0,
  67. itemGap: 12,
  68. align: 'left' as const,
  69. data: [
  70. {
  71. name: 'Baseline',
  72. icon: 'path://M180 1000 l0 -40 200 0 200 0 0 40 0 40 -200 0 -200 0 0 -40z, M810 1000 l0 -40 200 0 200 0 0 40 0 40 -200 0 -200 0 0 -40zm, M1440 1000 l0 -40 200 0 200 0 0 40 0 40 -200 0 -200 0 0 -40z',
  73. },
  74. {
  75. name: 'Releases',
  76. icon: 'line',
  77. },
  78. {
  79. name: trendFunction,
  80. icon: 'line',
  81. },
  82. ],
  83. };
  84. }
  85. function getIntervalLine(
  86. theme: Theme,
  87. series: Series[],
  88. intervalRatio: number,
  89. transaction?: NormalizedTrendsTransaction
  90. ) {
  91. if (!transaction || !series.length || !series[0].data || !series[0].data.length) {
  92. return [];
  93. }
  94. const seriesStart = parseInt(series[0].data[0].name as string, 0);
  95. const seriesEnd = parseInt(series[0].data.slice(-1)[0].name as string, 0);
  96. if (seriesEnd < seriesStart) {
  97. return [];
  98. }
  99. const periodLine = {
  100. data: [] as any[],
  101. color: theme.textColor,
  102. markLine: {
  103. data: [] as any[],
  104. label: {} as any,
  105. lineStyle: {
  106. normal: {
  107. color: theme.textColor,
  108. type: 'dashed',
  109. width: 1,
  110. },
  111. },
  112. symbol: ['none', 'none'],
  113. tooltip: {
  114. show: false,
  115. },
  116. },
  117. seriesName: 'Baseline',
  118. };
  119. const periodLineLabel = {
  120. fontSize: 11,
  121. show: true,
  122. };
  123. const previousPeriod = {
  124. ...periodLine,
  125. markLine: {...periodLine.markLine},
  126. seriesName: 'Baseline',
  127. };
  128. const currentPeriod = {
  129. ...periodLine,
  130. markLine: {...periodLine.markLine},
  131. seriesName: 'Baseline',
  132. };
  133. const periodDividingLine = {
  134. ...periodLine,
  135. markLine: {...periodLine.markLine},
  136. seriesName: 'Period split',
  137. };
  138. const seriesDiff = seriesEnd - seriesStart;
  139. const seriesLine = seriesDiff * intervalRatio + seriesStart;
  140. previousPeriod.markLine.data = [
  141. [
  142. {value: 'Past', coord: [seriesStart, transaction.aggregate_range_1]},
  143. {coord: [seriesLine, transaction.aggregate_range_1]},
  144. ],
  145. ];
  146. previousPeriod.markLine.tooltip = {
  147. formatter: () => {
  148. return [
  149. '<div class="tooltip-series tooltip-series-solo">',
  150. '<div>',
  151. `<span class="tooltip-label"><strong>${t('Past Baseline')}</strong></span>`,
  152. // p50() coerces the axis to be time based
  153. tooltipFormatter(transaction.aggregate_range_1, 'p50()'),
  154. '</div>',
  155. '</div>',
  156. '<div class="tooltip-arrow"></div>',
  157. ].join('');
  158. },
  159. } as any;
  160. currentPeriod.markLine.data = [
  161. [
  162. {value: 'Present', coord: [seriesLine, transaction.aggregate_range_2]},
  163. {coord: [seriesEnd, transaction.aggregate_range_2]},
  164. ],
  165. ];
  166. currentPeriod.markLine.tooltip = {
  167. formatter: () => {
  168. return [
  169. '<div class="tooltip-series tooltip-series-solo">',
  170. '<div>',
  171. `<span class="tooltip-label"><strong>${t('Present Baseline')}</strong></span>`,
  172. // p50() coerces the axis to be time based
  173. tooltipFormatter(transaction.aggregate_range_2, 'p50()'),
  174. '</div>',
  175. '</div>',
  176. '<div class="tooltip-arrow"></div>',
  177. ].join('');
  178. },
  179. } as any;
  180. periodDividingLine.markLine = {
  181. data: [
  182. {
  183. value: 'Previous Period / This Period',
  184. xAxis: seriesLine,
  185. },
  186. ],
  187. label: {show: false},
  188. lineStyle: {
  189. normal: {
  190. color: theme.textColor,
  191. type: 'solid',
  192. width: 2,
  193. },
  194. },
  195. symbol: ['none', 'none'],
  196. tooltip: {
  197. show: false,
  198. },
  199. };
  200. previousPeriod.markLine.label = {
  201. ...periodLineLabel,
  202. formatter: 'Past',
  203. position: 'insideStartBottom',
  204. };
  205. currentPeriod.markLine.label = {
  206. ...periodLineLabel,
  207. formatter: 'Present',
  208. position: 'insideEndBottom',
  209. };
  210. const additionalLineSeries = [previousPeriod, currentPeriod, periodDividingLine];
  211. return additionalLineSeries;
  212. }
  213. class Chart extends Component<Props> {
  214. handleLegendSelectChanged = legendChange => {
  215. const {location, trendChangeType} = this.props;
  216. const {selected} = legendChange;
  217. const unselected = Object.keys(selected).filter(key => !selected[key]);
  218. const query = {
  219. ...location.query,
  220. };
  221. const queryKey = getUnselectedSeries(trendChangeType);
  222. query[queryKey] = unselected;
  223. const to = {
  224. ...location,
  225. query,
  226. };
  227. browserHistory.push(to);
  228. };
  229. render() {
  230. const props = this.props;
  231. const {
  232. theme,
  233. trendChangeType,
  234. router,
  235. statsPeriod,
  236. project,
  237. environment,
  238. transaction,
  239. statsData,
  240. isLoading,
  241. location,
  242. projects,
  243. } = props;
  244. const lineColor = trendToColor[trendChangeType || ''];
  245. const events =
  246. statsData && transaction?.project && transaction?.transaction
  247. ? statsData[[transaction.project, transaction.transaction].join(',')]
  248. : undefined;
  249. const data = events?.data ?? [];
  250. const trendFunction = getCurrentTrendFunction(location);
  251. const trendParameter = getCurrentTrendParameter(location);
  252. const chartLabel = generateTrendFunctionAsString(
  253. trendFunction.field,
  254. trendParameter.column
  255. );
  256. const results = transformEventStats(data, chartLabel);
  257. const {smoothedResults, minValue, maxValue} = transformEventStatsSmoothed(
  258. results,
  259. chartLabel
  260. );
  261. const start = props.start ? getUtcToLocalDateObject(props.start) : null;
  262. const end = props.end ? getUtcToLocalDateObject(props.end) : null;
  263. const {utc} = getParams(location.query);
  264. const seriesSelection = decodeList(
  265. location.query[getUnselectedSeries(trendChangeType)]
  266. ).reduce((selection, metric) => {
  267. selection[metric] = false;
  268. return selection;
  269. }, {});
  270. const legend = {
  271. ...getLegend(chartLabel),
  272. selected: seriesSelection,
  273. };
  274. const loading = isLoading;
  275. const reloading = isLoading;
  276. const transactionProject = parseInt(
  277. projects.find(({slug}) => transaction?.project === slug)?.id || '',
  278. 10
  279. );
  280. const yMax = Math.max(
  281. maxValue,
  282. transaction?.aggregate_range_2 || 0,
  283. transaction?.aggregate_range_1 || 0
  284. );
  285. const yMin = Math.min(
  286. minValue,
  287. transaction?.aggregate_range_1 || Number.MAX_SAFE_INTEGER,
  288. transaction?.aggregate_range_2 || Number.MAX_SAFE_INTEGER
  289. );
  290. const yDiff = yMax - yMin;
  291. const yMargin = yDiff * 0.1;
  292. const queryExtra = {
  293. showTransactions: trendChangeType,
  294. yAxis: YAxis.COUNT_DURATION,
  295. };
  296. const chartOptions = {
  297. tooltip: {
  298. valueFormatter: (value, seriesName) => {
  299. return tooltipFormatter(value, seriesName);
  300. },
  301. },
  302. yAxis: {
  303. min: Math.max(0, yMin - yMargin),
  304. max: yMax + yMargin,
  305. axisLabel: {
  306. color: theme.chartLabel,
  307. // p50() coerces the axis to be time based
  308. formatter: (value: number) => axisLabelFormatter(value, 'p50()'),
  309. },
  310. },
  311. };
  312. return (
  313. <ChartZoom
  314. router={router}
  315. period={statsPeriod}
  316. start={start}
  317. end={end}
  318. utc={utc === 'true'}
  319. >
  320. {zoomRenderProps => {
  321. const smoothedSeries = smoothedResults
  322. ? smoothedResults.map(values => {
  323. return {
  324. ...values,
  325. color: lineColor.default,
  326. lineStyle: {
  327. opacity: 1,
  328. },
  329. };
  330. })
  331. : [];
  332. const intervalSeries = getIntervalLine(
  333. theme,
  334. smoothedResults || [],
  335. 0.5,
  336. transaction
  337. );
  338. return (
  339. <ReleaseSeries
  340. start={start}
  341. end={end}
  342. queryExtra={queryExtra}
  343. period={statsPeriod}
  344. utc={utc === 'true'}
  345. projects={isNaN(transactionProject) ? project : [transactionProject]}
  346. environments={environment}
  347. memoized
  348. >
  349. {({releaseSeries}) => (
  350. <TransitionChart loading={loading} reloading={reloading}>
  351. <TransparentLoadingMask visible={reloading} />
  352. {getDynamicText({
  353. value: (
  354. <LineChart
  355. {...zoomRenderProps}
  356. {...chartOptions}
  357. onLegendSelectChanged={this.handleLegendSelectChanged}
  358. series={[...smoothedSeries, ...releaseSeries, ...intervalSeries]}
  359. seriesOptions={{
  360. showSymbol: false,
  361. }}
  362. legend={legend}
  363. toolBox={{
  364. show: false,
  365. }}
  366. grid={{
  367. left: '10px',
  368. right: '10px',
  369. top: '40px',
  370. bottom: '0px',
  371. }}
  372. />
  373. ),
  374. fixed: 'Duration Chart',
  375. })}
  376. </TransitionChart>
  377. )}
  378. </ReleaseSeries>
  379. );
  380. }}
  381. </ChartZoom>
  382. );
  383. }
  384. }
  385. export default withTheme(withApi(withRouter(Chart)));