chart.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  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 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): LegendComponentOption {
  67. return {
  68. right: 10,
  69. top: 0,
  70. itemGap: 12,
  71. align: 'left',
  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. },
  80. {
  81. name: trendFunction,
  82. },
  83. ],
  84. };
  85. }
  86. function getIntervalLine(
  87. theme: Theme,
  88. series: Series[],
  89. intervalRatio: number,
  90. transaction?: NormalizedTrendsTransaction
  91. ): LineChartSeries[] {
  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, 10);
  96. const seriesEnd = parseInt(series[0].data.slice(-1)[0].name as string, 10);
  97. if (seriesEnd < seriesStart) {
  98. return [];
  99. }
  100. const periodLine: LineChartSeries = {
  101. data: [],
  102. color: theme.textColor,
  103. markLine: {
  104. data: [],
  105. label: {},
  106. lineStyle: {
  107. color: theme.textColor,
  108. type: 'dashed',
  109. width: 1,
  110. },
  111. symbol: ['none', 'none'],
  112. tooltip: {
  113. show: false,
  114. },
  115. },
  116. seriesName: 'Baseline',
  117. };
  118. const periodLineLabel = {
  119. fontSize: 11,
  120. show: true,
  121. color: theme.textColor,
  122. silent: 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. previousPeriod.markLine.tooltip = {
  148. formatter: () => {
  149. return [
  150. '<div class="tooltip-series tooltip-series-solo">',
  151. '<div>',
  152. `<span class="tooltip-label"><strong>${t('Past Baseline')}</strong></span>`,
  153. // p50() coerces the axis to be time based
  154. tooltipFormatter(transaction.aggregate_range_1, 'duration'),
  155. '</div>',
  156. '</div>',
  157. '<div class="tooltip-arrow"></div>',
  158. ].join('');
  159. },
  160. };
  161. currentPeriod.markLine.data = [
  162. [
  163. {value: 'Present', coord: [seriesLine, transaction.aggregate_range_2]},
  164. {coord: [seriesEnd, transaction.aggregate_range_2]},
  165. ],
  166. ];
  167. currentPeriod.markLine.tooltip = {
  168. formatter: () => {
  169. return [
  170. '<div class="tooltip-series tooltip-series-solo">',
  171. '<div>',
  172. `<span class="tooltip-label"><strong>${t('Present Baseline')}</strong></span>`,
  173. // p50() coerces the axis to be time based
  174. tooltipFormatter(transaction.aggregate_range_2, 'duration'),
  175. '</div>',
  176. '</div>',
  177. '<div class="tooltip-arrow"></div>',
  178. ].join('');
  179. },
  180. };
  181. periodDividingLine.markLine = {
  182. data: [
  183. {
  184. xAxis: seriesLine,
  185. },
  186. ],
  187. label: {show: false},
  188. lineStyle: {
  189. color: theme.textColor,
  190. type: 'solid',
  191. width: 2,
  192. },
  193. symbol: ['none', 'none'],
  194. tooltip: {
  195. show: false,
  196. },
  197. silent: true,
  198. };
  199. previousPeriod.markLine.label = {
  200. ...periodLineLabel,
  201. formatter: 'Past',
  202. position: 'insideStartBottom',
  203. };
  204. currentPeriod.markLine.label = {
  205. ...periodLineLabel,
  206. formatter: 'Present',
  207. position: 'insideEndBottom',
  208. };
  209. const additionalLineSeries = [previousPeriod, currentPeriod, periodDividingLine];
  210. return additionalLineSeries;
  211. }
  212. export function Chart({
  213. trendChangeType,
  214. statsPeriod,
  215. transaction,
  216. statsData,
  217. isLoading,
  218. start: propsStart,
  219. end: propsEnd,
  220. trendFunctionField,
  221. disableXAxis,
  222. disableLegend,
  223. grid,
  224. height,
  225. projects,
  226. project,
  227. }: Props) {
  228. const location = useLocation();
  229. const router = useRouter();
  230. const theme = useTheme();
  231. const handleLegendSelectChanged = legendChange => {
  232. const {selected} = legendChange;
  233. const unselected = Object.keys(selected).filter(key => !selected[key]);
  234. const query = {
  235. ...location.query,
  236. };
  237. const queryKey = getUnselectedSeries(trendChangeType);
  238. query[queryKey] = unselected;
  239. const to = {
  240. ...location,
  241. query,
  242. };
  243. browserHistory.push(to);
  244. };
  245. const lineColor = trendToColor[trendChangeType || ''];
  246. const events =
  247. statsData && transaction?.project && transaction?.transaction
  248. ? statsData[[transaction.project, transaction.transaction].join(',')]
  249. : undefined;
  250. const data = events?.data ?? [];
  251. const trendFunction = getCurrentTrendFunction(location, trendFunctionField);
  252. const trendParameter = getCurrentTrendParameter(location, projects, project);
  253. const chartLabel = generateTrendFunctionAsString(
  254. trendFunction.field,
  255. trendParameter.column
  256. );
  257. const results = transformEventStats(data, chartLabel);
  258. const {smoothedResults, minValue, maxValue} = transformEventStatsSmoothed(
  259. results,
  260. chartLabel
  261. );
  262. const start = propsStart ? getUtcToLocalDateObject(propsStart) : null;
  263. const end = propsEnd ? getUtcToLocalDateObject(propsEnd) : null;
  264. const {utc} = normalizeDateTimeParams(location.query);
  265. const seriesSelection = decodeList(
  266. location.query[getUnselectedSeries(trendChangeType)]
  267. ).reduce((selection, metric) => {
  268. selection[metric] = false;
  269. return selection;
  270. }, {});
  271. const legend: LegendComponentOption = disableLegend
  272. ? {show: false}
  273. : {
  274. ...getLegend(chartLabel),
  275. selected: seriesSelection,
  276. };
  277. const loading = isLoading;
  278. const reloading = isLoading;
  279. const yMax = Math.max(
  280. maxValue,
  281. transaction?.aggregate_range_2 || 0,
  282. transaction?.aggregate_range_1 || 0
  283. );
  284. const yMin = Math.min(
  285. minValue,
  286. transaction?.aggregate_range_1 || Number.MAX_SAFE_INTEGER,
  287. transaction?.aggregate_range_2 || Number.MAX_SAFE_INTEGER
  288. );
  289. const smoothedSeries = smoothedResults
  290. ? smoothedResults.map(values => {
  291. return {
  292. ...values,
  293. color: lineColor.default,
  294. lineStyle: {
  295. opacity: 1,
  296. },
  297. };
  298. })
  299. : [];
  300. const intervalSeries = getIntervalLine(theme, smoothedResults || [], 0.5, transaction);
  301. const yDiff = yMax - yMin;
  302. const yMargin = yDiff * 0.1;
  303. const series = [...smoothedSeries, ...intervalSeries];
  304. const durationUnit = getDurationUnit(series);
  305. const chartOptions: Omit<LineChartProps, 'series'> = {
  306. tooltip: {
  307. valueFormatter: (value, seriesName) => {
  308. return tooltipFormatter(value, aggregateOutputType(seriesName));
  309. },
  310. },
  311. yAxis: {
  312. min: Math.max(0, yMin - yMargin),
  313. max: yMax + yMargin,
  314. minInterval: durationUnit,
  315. axisLabel: {
  316. color: theme.chartLabel,
  317. formatter: (value: number) =>
  318. axisLabelFormatter(value, 'duration', undefined, durationUnit),
  319. },
  320. },
  321. };
  322. return (
  323. <ChartZoom
  324. router={router}
  325. period={statsPeriod}
  326. start={start}
  327. end={end}
  328. utc={utc === 'true'}
  329. >
  330. {zoomRenderProps => {
  331. return (
  332. <TransitionChart loading={loading} reloading={reloading}>
  333. <TransparentLoadingMask visible={reloading} />
  334. {getDynamicText({
  335. value: (
  336. <LineChart
  337. height={height}
  338. {...zoomRenderProps}
  339. {...chartOptions}
  340. onLegendSelectChanged={handleLegendSelectChanged}
  341. series={series}
  342. seriesOptions={{
  343. showSymbol: false,
  344. }}
  345. legend={legend}
  346. toolBox={{
  347. show: false,
  348. }}
  349. grid={
  350. grid ?? {
  351. left: '10px',
  352. right: '10px',
  353. top: '40px',
  354. bottom: '0px',
  355. }
  356. }
  357. xAxis={disableXAxis ? {show: false} : undefined}
  358. />
  359. ),
  360. fixed: 'Duration Chart',
  361. })}
  362. </TransitionChart>
  363. );
  364. }}
  365. </ChartZoom>
  366. );
  367. }
  368. export default Chart;