chart.tsx 11 KB

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