chart.tsx 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. import {browserHistory} from 'react-router';
  2. import {useTheme} from '@emotion/react';
  3. import type {LegendComponentOption, LineSeriesOption} from 'echarts';
  4. import ChartZoom from 'sentry/components/charts/chartZoom';
  5. import {LineChart, LineChartProps} from 'sentry/components/charts/lineChart';
  6. import TransitionChart from 'sentry/components/charts/transitionChart';
  7. import TransparentLoadingMask from 'sentry/components/charts/transparentLoadingMask';
  8. import {normalizeDateTimeParams} from 'sentry/components/organizations/pageFilters/parse';
  9. import {EventsStatsData, OrganizationSummary, Project} from 'sentry/types';
  10. import {Series} from 'sentry/types/echarts';
  11. import {getUtcToLocalDateObject} from 'sentry/utils/dates';
  12. import {
  13. axisLabelFormatter,
  14. getDurationUnit,
  15. tooltipFormatter,
  16. } from 'sentry/utils/discover/charts';
  17. import {aggregateOutputType} from 'sentry/utils/discover/fields';
  18. import getDynamicText from 'sentry/utils/getDynamicText';
  19. import {decodeList} from 'sentry/utils/queryString';
  20. import {useLocation} from 'sentry/utils/useLocation';
  21. import useRouter from 'sentry/utils/useRouter';
  22. import {getIntervalLine} from 'sentry/views/performance/utils';
  23. import {ViewProps} from '../types';
  24. import {
  25. NormalizedTrendsTransaction,
  26. TrendChangeType,
  27. TrendFunctionField,
  28. TrendsStats,
  29. } from './types';
  30. import {
  31. generateTrendFunctionAsString,
  32. getCurrentTrendFunction,
  33. getCurrentTrendParameter,
  34. getUnselectedSeries,
  35. transformEventStatsSmoothed,
  36. trendToColor,
  37. } from './utils';
  38. type Props = ViewProps & {
  39. isLoading: boolean;
  40. organization: OrganizationSummary;
  41. projects: Project[];
  42. statsData: TrendsStats;
  43. trendChangeType: TrendChangeType;
  44. additionalSeries?: LineSeriesOption[];
  45. applyRegressionFormatToInterval?: boolean;
  46. disableLegend?: boolean;
  47. disableXAxis?: boolean;
  48. grid?: LineChartProps['grid'];
  49. height?: number;
  50. neutralColor?: boolean;
  51. transaction?: NormalizedTrendsTransaction;
  52. trendFunctionField?: TrendFunctionField;
  53. };
  54. function transformEventStats(data: EventsStatsData, seriesName?: string): Series[] {
  55. return [
  56. {
  57. seriesName: seriesName || 'Current',
  58. data: data.map(([timestamp, countsForTimestamp]) => ({
  59. name: timestamp * 1000,
  60. value: countsForTimestamp.reduce((acc, {count}) => acc + count, 0),
  61. })),
  62. },
  63. ];
  64. }
  65. function getLegend(trendFunction: string): LegendComponentOption {
  66. return {
  67. right: 10,
  68. top: 0,
  69. itemGap: 12,
  70. align: 'left',
  71. data: [
  72. {
  73. name: 'Baseline',
  74. 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',
  75. },
  76. {
  77. name: 'Releases',
  78. },
  79. {
  80. name: trendFunction,
  81. },
  82. ],
  83. };
  84. }
  85. export function Chart({
  86. trendChangeType,
  87. statsPeriod,
  88. transaction,
  89. statsData,
  90. isLoading,
  91. start: propsStart,
  92. end: propsEnd,
  93. trendFunctionField,
  94. disableXAxis,
  95. disableLegend,
  96. neutralColor,
  97. grid,
  98. height,
  99. projects,
  100. project,
  101. organization,
  102. additionalSeries,
  103. applyRegressionFormatToInterval = false,
  104. }: Props) {
  105. const location = useLocation();
  106. const router = useRouter();
  107. const theme = useTheme();
  108. const handleLegendSelectChanged = legendChange => {
  109. const {selected} = legendChange;
  110. const unselected = Object.keys(selected).filter(key => !selected[key]);
  111. const query = {
  112. ...location.query,
  113. };
  114. const queryKey = getUnselectedSeries(trendChangeType);
  115. query[queryKey] = unselected;
  116. const to = {
  117. ...location,
  118. query,
  119. };
  120. browserHistory.push(to);
  121. };
  122. const derivedTrendChangeType = organization.features.includes('performance-new-trends')
  123. ? transaction?.change
  124. : trendChangeType;
  125. const lineColor =
  126. trendToColor[neutralColor ? 'neutral' : derivedTrendChangeType || trendChangeType];
  127. const events =
  128. statsData && transaction?.project && transaction?.transaction
  129. ? statsData[[transaction.project, transaction.transaction].join(',')]
  130. : undefined;
  131. const data = events?.data ?? [];
  132. const trendFunction = getCurrentTrendFunction(location, trendFunctionField);
  133. const trendParameter = getCurrentTrendParameter(location, projects, project);
  134. const chartLabel = generateTrendFunctionAsString(
  135. trendFunction.field,
  136. trendParameter.column
  137. );
  138. const results = transformEventStats(data, chartLabel);
  139. const {smoothedResults, minValue, maxValue} = transformEventStatsSmoothed(
  140. results,
  141. chartLabel
  142. );
  143. const start = propsStart ? getUtcToLocalDateObject(propsStart) : null;
  144. const end = propsEnd ? getUtcToLocalDateObject(propsEnd) : null;
  145. const {utc} = normalizeDateTimeParams(location.query);
  146. const seriesSelection = decodeList(
  147. location.query[getUnselectedSeries(trendChangeType)]
  148. ).reduce((selection, metric) => {
  149. selection[metric] = false;
  150. return selection;
  151. }, {});
  152. const legend: LegendComponentOption = disableLegend
  153. ? {show: false}
  154. : {
  155. ...getLegend(chartLabel),
  156. selected: seriesSelection,
  157. };
  158. const loading = isLoading;
  159. const reloading = isLoading;
  160. const yMax = Math.max(
  161. maxValue,
  162. transaction?.aggregate_range_2 || 0,
  163. transaction?.aggregate_range_1 || 0
  164. );
  165. const yMin = Math.min(
  166. minValue,
  167. transaction?.aggregate_range_1 || Number.MAX_SAFE_INTEGER,
  168. transaction?.aggregate_range_2 || Number.MAX_SAFE_INTEGER
  169. );
  170. const smoothedSeries = smoothedResults
  171. ? smoothedResults.map(values => {
  172. return {
  173. ...values,
  174. color: lineColor.default,
  175. lineStyle: {
  176. opacity: 1,
  177. },
  178. };
  179. })
  180. : [];
  181. const needsLabel = true;
  182. const intervalSeries = getIntervalLine(
  183. theme,
  184. smoothedResults || [],
  185. 0.5,
  186. needsLabel,
  187. transaction,
  188. applyRegressionFormatToInterval
  189. );
  190. const yDiff = yMax - yMin;
  191. const yMargin = yDiff * 0.1;
  192. const series = [...smoothedSeries, ...intervalSeries];
  193. const durationUnit = getDurationUnit(series);
  194. const chartOptions: Omit<LineChartProps, 'series'> = {
  195. tooltip: {
  196. valueFormatter: (value, seriesName) => {
  197. return tooltipFormatter(value, aggregateOutputType(seriesName));
  198. },
  199. },
  200. yAxis: {
  201. min: Math.max(0, yMin - yMargin),
  202. max: yMax + yMargin,
  203. minInterval: durationUnit,
  204. axisLabel: {
  205. color: theme.chartLabel,
  206. formatter: (value: number) =>
  207. axisLabelFormatter(value, 'duration', undefined, durationUnit),
  208. },
  209. },
  210. };
  211. return (
  212. <ChartZoom
  213. router={router}
  214. period={statsPeriod}
  215. start={start}
  216. end={end}
  217. utc={utc === 'true'}
  218. >
  219. {zoomRenderProps => {
  220. return (
  221. <TransitionChart loading={loading} reloading={reloading}>
  222. <TransparentLoadingMask visible={reloading} />
  223. {getDynamicText({
  224. value: (
  225. <LineChart
  226. height={height}
  227. {...zoomRenderProps}
  228. {...chartOptions}
  229. additionalSeries={additionalSeries}
  230. onLegendSelectChanged={handleLegendSelectChanged}
  231. series={series}
  232. seriesOptions={{
  233. showSymbol: false,
  234. }}
  235. legend={legend}
  236. toolBox={{
  237. show: false,
  238. }}
  239. grid={
  240. grid ?? {
  241. left: '10px',
  242. right: '10px',
  243. top: '40px',
  244. bottom: '0px',
  245. }
  246. }
  247. xAxis={disableXAxis ? {show: false} : undefined}
  248. />
  249. ),
  250. fixed: 'Duration Chart',
  251. })}
  252. </TransitionChart>
  253. );
  254. }}
  255. </ChartZoom>
  256. );
  257. }
  258. export default Chart;