chart.tsx 10 KB

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