chart.tsx 11 KB

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