chart.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. // eslint-disable-next-line no-restricted-imports
  2. import {browserHistory, withRouter, WithRouterProps} from 'react-router';
  3. import {useTheme} from '@emotion/react';
  4. import type {LegendComponentOption} from 'echarts';
  5. import ChartZoom from 'sentry/components/charts/chartZoom';
  6. import {
  7. LineChart,
  8. LineChartProps,
  9. LineChartSeries,
  10. } from 'sentry/components/charts/lineChart';
  11. import TransitionChart from 'sentry/components/charts/transitionChart';
  12. import TransparentLoadingMask from 'sentry/components/charts/transparentLoadingMask';
  13. import {normalizeDateTimeParams} from 'sentry/components/organizations/pageFilters/parse';
  14. import {t} from 'sentry/locale';
  15. import {EventsStatsData, OrganizationSummary, Project} from 'sentry/types';
  16. import {Series} from 'sentry/types/echarts';
  17. import {getUtcToLocalDateObject} from 'sentry/utils/dates';
  18. import {
  19. axisLabelFormatter,
  20. getDurationUnit,
  21. tooltipFormatter,
  22. } from 'sentry/utils/discover/charts';
  23. import {aggregateOutputType} from 'sentry/utils/discover/fields';
  24. import getDynamicText from 'sentry/utils/getDynamicText';
  25. import {decodeList} from 'sentry/utils/queryString';
  26. import {Theme} from 'sentry/utils/theme';
  27. import {ViewProps} from '../types';
  28. import {
  29. NormalizedTrendsTransaction,
  30. TrendChangeType,
  31. TrendFunctionField,
  32. TrendsStats,
  33. } from './types';
  34. import {
  35. generateTrendFunctionAsString,
  36. getCurrentTrendFunction,
  37. getCurrentTrendParameter,
  38. getUnselectedSeries,
  39. transformEventStatsSmoothed,
  40. trendToColor,
  41. } from './utils';
  42. type Props = WithRouterProps &
  43. ViewProps & {
  44. isLoading: boolean;
  45. location: Location;
  46. organization: OrganizationSummary;
  47. projects: Project[];
  48. statsData: TrendsStats;
  49. trendChangeType: TrendChangeType;
  50. disableLegend?: boolean;
  51. disableXAxis?: boolean;
  52. grid?: LineChartProps['grid'];
  53. height?: number;
  54. transaction?: NormalizedTrendsTransaction;
  55. trendFunctionField?: TrendFunctionField;
  56. };
  57. function transformEventStats(data: EventsStatsData, seriesName?: string): Series[] {
  58. return [
  59. {
  60. seriesName: seriesName || 'Current',
  61. data: data.map(([timestamp, countsForTimestamp]) => ({
  62. name: timestamp * 1000,
  63. value: countsForTimestamp.reduce((acc, {count}) => acc + count, 0),
  64. })),
  65. },
  66. ];
  67. }
  68. function getLegend(trendFunction: string): LegendComponentOption {
  69. return {
  70. right: 10,
  71. top: 0,
  72. itemGap: 12,
  73. align: 'left',
  74. data: [
  75. {
  76. name: 'Baseline',
  77. 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',
  78. },
  79. {
  80. name: 'Releases',
  81. },
  82. {
  83. name: trendFunction,
  84. },
  85. ],
  86. };
  87. }
  88. function getIntervalLine(
  89. theme: Theme,
  90. series: Series[],
  91. intervalRatio: number,
  92. transaction?: NormalizedTrendsTransaction
  93. ): LineChartSeries[] {
  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, 10);
  98. const seriesEnd = parseInt(series[0].data.slice(-1)[0].name as string, 10);
  99. if (seriesEnd < seriesStart) {
  100. return [];
  101. }
  102. const periodLine: LineChartSeries = {
  103. data: [],
  104. color: theme.textColor,
  105. markLine: {
  106. data: [],
  107. label: {},
  108. lineStyle: {
  109. color: theme.textColor,
  110. type: 'dashed',
  111. width: 1,
  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. color: theme.textColor,
  124. silent: 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, 'duration'),
  157. '</div>',
  158. '</div>',
  159. '<div class="tooltip-arrow"></div>',
  160. ].join('');
  161. },
  162. };
  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, 'duration'),
  177. '</div>',
  178. '</div>',
  179. '<div class="tooltip-arrow"></div>',
  180. ].join('');
  181. },
  182. };
  183. periodDividingLine.markLine = {
  184. data: [
  185. {
  186. xAxis: seriesLine,
  187. },
  188. ],
  189. label: {show: false},
  190. lineStyle: {
  191. color: theme.textColor,
  192. type: 'solid',
  193. width: 2,
  194. },
  195. symbol: ['none', 'none'],
  196. tooltip: {
  197. show: false,
  198. },
  199. silent: true,
  200. };
  201. previousPeriod.markLine.label = {
  202. ...periodLineLabel,
  203. formatter: 'Past',
  204. position: 'insideStartBottom',
  205. };
  206. currentPeriod.markLine.label = {
  207. ...periodLineLabel,
  208. formatter: 'Present',
  209. position: 'insideEndBottom',
  210. };
  211. const additionalLineSeries = [previousPeriod, currentPeriod, periodDividingLine];
  212. return additionalLineSeries;
  213. }
  214. export function Chart({
  215. trendChangeType,
  216. router,
  217. statsPeriod,
  218. transaction,
  219. statsData,
  220. isLoading,
  221. location,
  222. start: propsStart,
  223. end: propsEnd,
  224. trendFunctionField,
  225. disableXAxis,
  226. disableLegend,
  227. grid,
  228. height,
  229. projects,
  230. project,
  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, projects, project);
  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} = normalizeDateTimeParams(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: LegendComponentOption = 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 smoothedSeries = smoothedResults
  292. ? smoothedResults.map(values => {
  293. return {
  294. ...values,
  295. color: lineColor.default,
  296. lineStyle: {
  297. opacity: 1,
  298. },
  299. };
  300. })
  301. : [];
  302. const intervalSeries = getIntervalLine(theme, smoothedResults || [], 0.5, transaction);
  303. const yDiff = yMax - yMin;
  304. const yMargin = yDiff * 0.1;
  305. const series = [...smoothedSeries, ...intervalSeries];
  306. const durationUnit = getDurationUnit(series);
  307. const chartOptions: Omit<LineChartProps, 'series'> = {
  308. tooltip: {
  309. valueFormatter: (value, seriesName) => {
  310. return tooltipFormatter(value, aggregateOutputType(seriesName));
  311. },
  312. },
  313. yAxis: {
  314. min: Math.max(0, yMin - yMargin),
  315. max: yMax + yMargin,
  316. minInterval: durationUnit,
  317. axisLabel: {
  318. color: theme.chartLabel,
  319. formatter: (value: number) =>
  320. axisLabelFormatter(value, 'duration', undefined, durationUnit),
  321. },
  322. },
  323. };
  324. return (
  325. <ChartZoom
  326. router={router}
  327. period={statsPeriod}
  328. start={start}
  329. end={end}
  330. utc={utc === 'true'}
  331. >
  332. {zoomRenderProps => {
  333. return (
  334. <TransitionChart loading={loading} reloading={reloading}>
  335. <TransparentLoadingMask visible={reloading} />
  336. {getDynamicText({
  337. value: (
  338. <LineChart
  339. height={height}
  340. {...zoomRenderProps}
  341. {...chartOptions}
  342. onLegendSelectChanged={handleLegendSelectChanged}
  343. series={series}
  344. seriesOptions={{
  345. showSymbol: false,
  346. }}
  347. legend={legend}
  348. toolBox={{
  349. show: false,
  350. }}
  351. grid={
  352. grid ?? {
  353. left: '10px',
  354. right: '10px',
  355. top: '40px',
  356. bottom: '0px',
  357. }
  358. }
  359. xAxis={disableXAxis ? {show: false} : undefined}
  360. />
  361. ),
  362. fixed: 'Duration Chart',
  363. })}
  364. </TransitionChart>
  365. );
  366. }}
  367. </ChartZoom>
  368. );
  369. }
  370. export default withRouter(Chart);