chart.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. import {browserHistory, withRouter, WithRouterProps} 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 LineChart, {LineChartSeries} from 'sentry/components/charts/lineChart';
  6. import TransitionChart from 'sentry/components/charts/transitionChart';
  7. import TransparentLoadingMask from 'sentry/components/charts/transparentLoadingMask';
  8. import {getTooltipArrow} from 'sentry/components/charts/utils';
  9. import {normalizeDateTimeParams} from 'sentry/components/organizations/pageFilters/parse';
  10. import {t} from 'sentry/locale';
  11. import {EventsStatsData, OrganizationSummary, Project} from 'sentry/types';
  12. import {Series} from 'sentry/types/echarts';
  13. import {getUtcToLocalDateObject} from 'sentry/utils/dates';
  14. import {axisLabelFormatter, tooltipFormatter} from 'sentry/utils/discover/charts';
  15. import EventView from 'sentry/utils/discover/eventView';
  16. import getDynamicText from 'sentry/utils/getDynamicText';
  17. import {decodeList} from 'sentry/utils/queryString';
  18. import {Theme} from 'sentry/utils/theme';
  19. import {
  20. NormalizedTrendsTransaction,
  21. TrendChangeType,
  22. TrendFunctionField,
  23. TrendsStats,
  24. } from './types';
  25. import {
  26. generateTrendFunctionAsString,
  27. getCurrentTrendFunction,
  28. getCurrentTrendParameter,
  29. getUnselectedSeries,
  30. transformEventStatsSmoothed,
  31. trendToColor,
  32. } from './utils';
  33. const QUERY_KEYS = [
  34. 'environment',
  35. 'project',
  36. 'query',
  37. 'start',
  38. 'end',
  39. 'statsPeriod',
  40. ] as const;
  41. type ViewProps = Pick<EventView, typeof QUERY_KEYS[number]>;
  42. type Props = WithRouterProps &
  43. ViewProps & {
  44. location: Location;
  45. organization: OrganizationSummary;
  46. trendChangeType: TrendChangeType;
  47. trendFunctionField?: TrendFunctionField;
  48. isLoading: boolean;
  49. statsData: TrendsStats;
  50. projects: Project[];
  51. transaction?: NormalizedTrendsTransaction;
  52. height?: number;
  53. grid?: React.ComponentProps<typeof LineChart>['grid'];
  54. disableXAxis?: boolean;
  55. disableLegend?: boolean;
  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, 0);
  98. const seriesEnd = parseInt(series[0].data.slice(-1)[0].name as string, 0);
  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, 'p50()'),
  157. '</div>',
  158. '</div>',
  159. getTooltipArrow(),
  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, 'p50()'),
  177. '</div>',
  178. '</div>',
  179. getTooltipArrow(),
  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. }: Props) {
  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);
  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 yDiff = yMax - yMin;
  290. const yMargin = yDiff * 0.1;
  291. const chartOptions = {
  292. tooltip: {
  293. valueFormatter: (value, seriesName) => {
  294. return tooltipFormatter(value, seriesName);
  295. },
  296. },
  297. yAxis: {
  298. min: Math.max(0, yMin - yMargin),
  299. max: yMax + yMargin,
  300. axisLabel: {
  301. color: theme.chartLabel,
  302. // p50() coerces the axis to be time based
  303. formatter: (value: number) => axisLabelFormatter(value, 'p50()'),
  304. },
  305. },
  306. };
  307. return (
  308. <ChartZoom
  309. router={router}
  310. period={statsPeriod}
  311. start={start}
  312. end={end}
  313. utc={utc === 'true'}
  314. >
  315. {zoomRenderProps => {
  316. const smoothedSeries = smoothedResults
  317. ? smoothedResults.map(values => {
  318. return {
  319. ...values,
  320. color: lineColor.default,
  321. lineStyle: {
  322. opacity: 1,
  323. },
  324. };
  325. })
  326. : [];
  327. const intervalSeries = getIntervalLine(
  328. theme,
  329. smoothedResults || [],
  330. 0.5,
  331. transaction
  332. );
  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={[...smoothedSeries, ...intervalSeries]}
  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);