chart.tsx 11 KB

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