chart.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. import React from 'react';
  2. import {browserHistory, withRouter} from 'react-router';
  3. import {WithRouterProps} from 'react-router/lib/withRouter';
  4. import {withTheme} from '@emotion/react';
  5. import {Client} from 'app/api';
  6. import ChartZoom from 'app/components/charts/chartZoom';
  7. import LineChart from 'app/components/charts/lineChart';
  8. import ReleaseSeries from 'app/components/charts/releaseSeries';
  9. import TransitionChart from 'app/components/charts/transitionChart';
  10. import TransparentLoadingMask from 'app/components/charts/transparentLoadingMask';
  11. import {getParams} from 'app/components/organizations/globalSelectionHeader/getParams';
  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:
  73. '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',
  74. },
  75. {
  76. name: 'Releases',
  77. icon: 'line',
  78. },
  79. {
  80. name: trendFunction,
  81. icon: 'line',
  82. },
  83. ],
  84. };
  85. }
  86. function getIntervalLine(
  87. theme: Theme,
  88. series: Series[],
  89. intervalRatio: number,
  90. transaction?: NormalizedTrendsTransaction
  91. ) {
  92. if (!transaction || !series.length || !series[0].data || !series[0].data.length) {
  93. return [];
  94. }
  95. const seriesStart = parseInt(series[0].data[0].name as string, 0);
  96. const seriesEnd = parseInt(series[0].data.slice(-1)[0].name as string, 0);
  97. if (seriesEnd < seriesStart) {
  98. return [];
  99. }
  100. const periodLine = {
  101. data: [] as any[],
  102. color: theme.textColor,
  103. markLine: {
  104. data: [] as any[],
  105. label: {} as any,
  106. lineStyle: {
  107. normal: {
  108. color: theme.textColor,
  109. type: 'dashed',
  110. width: 1,
  111. },
  112. },
  113. symbol: ['none', 'none'],
  114. tooltip: {
  115. show: false,
  116. },
  117. },
  118. seriesName: 'Baseline',
  119. };
  120. const periodLineLabel = {
  121. fontSize: 11,
  122. show: true,
  123. };
  124. const previousPeriod = {
  125. ...periodLine,
  126. markLine: {...periodLine.markLine},
  127. seriesName: 'Baseline',
  128. };
  129. const currentPeriod = {
  130. ...periodLine,
  131. markLine: {...periodLine.markLine},
  132. seriesName: 'Baseline',
  133. };
  134. const periodDividingLine = {
  135. ...periodLine,
  136. markLine: {...periodLine.markLine},
  137. seriesName: 'Period split',
  138. };
  139. const seriesDiff = seriesEnd - seriesStart;
  140. const seriesLine = seriesDiff * intervalRatio + seriesStart;
  141. previousPeriod.markLine.data = [
  142. [
  143. {value: 'Past', coord: [seriesStart, transaction.aggregate_range_1]},
  144. {coord: [seriesLine, transaction.aggregate_range_1]},
  145. ],
  146. ];
  147. currentPeriod.markLine.data = [
  148. [
  149. {value: 'Present', coord: [seriesLine, transaction.aggregate_range_2]},
  150. {coord: [seriesEnd, transaction.aggregate_range_2]},
  151. ],
  152. ];
  153. periodDividingLine.markLine = {
  154. data: [
  155. {
  156. value: 'Previous Period / This Period',
  157. xAxis: seriesLine,
  158. },
  159. ],
  160. label: {show: false},
  161. lineStyle: {
  162. normal: {
  163. color: theme.textColor,
  164. type: 'solid',
  165. width: 2,
  166. },
  167. },
  168. symbol: ['none', 'none'],
  169. tooltip: {
  170. show: false,
  171. },
  172. };
  173. previousPeriod.markLine.label = {
  174. ...periodLineLabel,
  175. formatter: 'Past',
  176. position: 'insideStartBottom',
  177. };
  178. currentPeriod.markLine.label = {
  179. ...periodLineLabel,
  180. formatter: 'Present',
  181. position: 'insideEndBottom',
  182. };
  183. const additionalLineSeries = [previousPeriod, currentPeriod, periodDividingLine];
  184. return additionalLineSeries;
  185. }
  186. class Chart extends React.Component<Props> {
  187. handleLegendSelectChanged = legendChange => {
  188. const {location, trendChangeType} = this.props;
  189. const {selected} = legendChange;
  190. const unselected = Object.keys(selected).filter(key => !selected[key]);
  191. const query = {
  192. ...location.query,
  193. };
  194. const queryKey = getUnselectedSeries(trendChangeType);
  195. query[queryKey] = unselected;
  196. const to = {
  197. ...location,
  198. query,
  199. };
  200. browserHistory.push(to);
  201. };
  202. render() {
  203. const props = this.props;
  204. const {
  205. theme,
  206. trendChangeType,
  207. router,
  208. statsPeriod,
  209. project,
  210. environment,
  211. transaction,
  212. statsData,
  213. isLoading,
  214. location,
  215. projects,
  216. } = props;
  217. const lineColor = trendToColor[trendChangeType || ''];
  218. const events =
  219. statsData && transaction?.project && transaction?.transaction
  220. ? statsData[[transaction.project, transaction.transaction].join(',')]
  221. : undefined;
  222. const data = events?.data ?? [];
  223. const trendFunction = getCurrentTrendFunction(location);
  224. const trendParameter = getCurrentTrendParameter(location);
  225. const chartLabel = generateTrendFunctionAsString(
  226. trendFunction.field,
  227. trendParameter.column
  228. );
  229. const results = transformEventStats(data, chartLabel);
  230. const {smoothedResults, minValue, maxValue} = transformEventStatsSmoothed(
  231. results,
  232. chartLabel
  233. );
  234. const start = props.start ? getUtcToLocalDateObject(props.start) : null;
  235. const end = props.end ? getUtcToLocalDateObject(props.end) : null;
  236. const {utc} = getParams(location.query);
  237. const seriesSelection = decodeList(
  238. location.query[getUnselectedSeries(trendChangeType)]
  239. ).reduce((selection, metric) => {
  240. selection[metric] = false;
  241. return selection;
  242. }, {});
  243. const legend = {
  244. ...getLegend(chartLabel),
  245. selected: seriesSelection,
  246. };
  247. const loading = isLoading;
  248. const reloading = isLoading;
  249. const transactionProject = parseInt(
  250. projects.find(({slug}) => transaction?.project === slug)?.id || '',
  251. 10
  252. );
  253. const yMax = Math.max(
  254. maxValue,
  255. transaction?.aggregate_range_2 || 0,
  256. transaction?.aggregate_range_1 || 0
  257. );
  258. const yMin = Math.min(
  259. minValue,
  260. transaction?.aggregate_range_1 || Number.MAX_SAFE_INTEGER,
  261. transaction?.aggregate_range_2 || Number.MAX_SAFE_INTEGER
  262. );
  263. const yDiff = yMax - yMin;
  264. const yMargin = yDiff * 0.1;
  265. const queryExtra = {
  266. showTransactions: trendChangeType,
  267. yAxis: YAxis.COUNT_DURATION,
  268. };
  269. const chartOptions = {
  270. tooltip: {
  271. valueFormatter: (value, seriesName) => {
  272. return tooltipFormatter(value, seriesName);
  273. },
  274. },
  275. yAxis: {
  276. min: Math.max(0, yMin - yMargin),
  277. max: yMax + yMargin,
  278. axisLabel: {
  279. color: theme.chartLabel,
  280. // p50() coerces the axis to be time based
  281. formatter: (value: number) => axisLabelFormatter(value, 'p50()'),
  282. },
  283. },
  284. };
  285. return (
  286. <ChartZoom
  287. router={router}
  288. period={statsPeriod}
  289. start={start}
  290. end={end}
  291. utc={utc === 'true'}
  292. >
  293. {zoomRenderProps => {
  294. const smoothedSeries = smoothedResults
  295. ? smoothedResults.map(values => {
  296. return {
  297. ...values,
  298. color: lineColor.default,
  299. lineStyle: {
  300. opacity: 1,
  301. },
  302. };
  303. })
  304. : [];
  305. const intervalSeries = getIntervalLine(
  306. theme,
  307. smoothedResults || [],
  308. 0.5,
  309. transaction
  310. );
  311. return (
  312. <ReleaseSeries
  313. start={start}
  314. end={end}
  315. queryExtra={queryExtra}
  316. period={statsPeriod}
  317. utc={utc === 'true'}
  318. projects={isNaN(transactionProject) ? project : [transactionProject]}
  319. environments={environment}
  320. memoized
  321. >
  322. {({releaseSeries}) => (
  323. <TransitionChart loading={loading} reloading={reloading}>
  324. <TransparentLoadingMask visible={reloading} />
  325. {getDynamicText({
  326. value: (
  327. <LineChart
  328. {...zoomRenderProps}
  329. {...chartOptions}
  330. onLegendSelectChanged={this.handleLegendSelectChanged}
  331. series={[...smoothedSeries, ...releaseSeries, ...intervalSeries]}
  332. seriesOptions={{
  333. showSymbol: false,
  334. }}
  335. legend={legend}
  336. toolBox={{
  337. show: false,
  338. }}
  339. grid={{
  340. left: '10px',
  341. right: '10px',
  342. top: '40px',
  343. bottom: '0px',
  344. }}
  345. />
  346. ),
  347. fixed: 'Duration Chart',
  348. })}
  349. </TransitionChart>
  350. )}
  351. </ReleaseSeries>
  352. );
  353. }}
  354. </ChartZoom>
  355. );
  356. }
  357. }
  358. export default withTheme(withApi(withRouter(Chart)));