chart.tsx 10 KB

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