chart.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. import {forwardRef, useCallback, useEffect, useMemo, useRef} from 'react';
  2. import styled from '@emotion/styled';
  3. import * as Sentry from '@sentry/react';
  4. import Color from 'color';
  5. import * as echarts from 'echarts/core';
  6. import {CanvasRenderer} from 'echarts/renderers';
  7. import {updateDateTime} from 'sentry/actionCreators/pageFilters';
  8. import {transformToAreaSeries} from 'sentry/components/charts/areaChart';
  9. import {transformToBarSeries} from 'sentry/components/charts/barChart';
  10. import type {BaseChartProps} from 'sentry/components/charts/baseChart';
  11. import BaseChart from 'sentry/components/charts/baseChart';
  12. import {transformToLineSeries} from 'sentry/components/charts/lineChart';
  13. import ScatterSeries from 'sentry/components/charts/series/scatterSeries';
  14. import type {DateTimeObject} from 'sentry/components/charts/utils';
  15. import type {ReactEchartsRef} from 'sentry/types/echarts';
  16. import mergeRefs from 'sentry/utils/mergeRefs';
  17. import {isCumulativeOp} from 'sentry/utils/metrics';
  18. import {formatMetricsUsingUnitAndOp} from 'sentry/utils/metrics/formatters';
  19. import {MetricDisplayType} from 'sentry/utils/metrics/types';
  20. import useRouter from 'sentry/utils/useRouter';
  21. import type {FocusAreaProps} from 'sentry/views/ddm/context';
  22. import {useFocusArea} from 'sentry/views/ddm/focusArea';
  23. import {getFormatter} from '../../components/charts/components/tooltip';
  24. import {isChartHovered} from '../../components/charts/utils';
  25. import {useChartSamples} from './useChartSamples';
  26. import type {SamplesProps, ScatterSeries as ScatterSeriesType, Series} from './widget';
  27. type ChartProps = {
  28. displayType: MetricDisplayType;
  29. series: Series[];
  30. widgetIndex: number;
  31. focusArea?: FocusAreaProps;
  32. group?: string;
  33. height?: number;
  34. operation?: string;
  35. scatter?: SamplesProps;
  36. };
  37. // We need to enable canvas renderer for echarts before we use it here.
  38. // Once we use it in more places, this should probably move to a more global place
  39. // But for now we keep it here to not invluence the bundle size of the main chunks.
  40. echarts.use(CanvasRenderer);
  41. export const MetricChart = forwardRef<ReactEchartsRef, ChartProps>(
  42. (
  43. {series, displayType, operation, widgetIndex, focusArea, height, scatter, group},
  44. forwardedRef
  45. ) => {
  46. const router = useRouter();
  47. const chartRef = useRef<ReactEchartsRef>(null);
  48. const handleZoom = useCallback(
  49. (range: DateTimeObject) => {
  50. Sentry.metrics.increment('ddm.enhance.zoom');
  51. updateDateTime(range, router, {save: true});
  52. },
  53. [router]
  54. );
  55. const focusAreaBrush = useFocusArea({
  56. ...focusArea,
  57. chartRef,
  58. opts: {
  59. widgetIndex,
  60. isDisabled: !focusArea?.onAdd || !handleZoom,
  61. useFullYAxis: isCumulativeOp(operation),
  62. },
  63. onZoom: handleZoom,
  64. });
  65. useEffect(() => {
  66. if (!group) {
  67. return;
  68. }
  69. const echartsInstance = chartRef?.current?.getEchartsInstance();
  70. if (echartsInstance && !echartsInstance.group) {
  71. echartsInstance.group = group;
  72. }
  73. });
  74. // TODO(ddm): This assumes that all series have the same bucket size
  75. const bucketSize = series[0]?.data[1]?.name - series[0]?.data[0]?.name;
  76. const isSubMinuteBucket = bucketSize < 60_000;
  77. const unit = series[0]?.unit;
  78. const fogOfWarBuckets = getWidthFactor(bucketSize);
  79. const seriesToShow = useMemo(
  80. () =>
  81. series
  82. .filter(s => !s.hidden)
  83. // Split series in two parts, one for the main chart and one for the fog of war
  84. // The order is important as the tooltip will show the first series first (for overlaps)
  85. .flatMap(s => [
  86. {
  87. ...s,
  88. silent: true,
  89. data: s.data.slice(0, -fogOfWarBuckets),
  90. },
  91. displayType === MetricDisplayType.BAR
  92. ? createFogOfWarBarSeries(s, fogOfWarBuckets)
  93. : displayType === MetricDisplayType.LINE
  94. ? createFogOfWarLineSeries(s, fogOfWarBuckets)
  95. : createFogOfWarAreaSeries(s, fogOfWarBuckets),
  96. ]),
  97. [series, fogOfWarBuckets, displayType]
  98. );
  99. const valueFormatter = useCallback(
  100. (value: number) => {
  101. return formatMetricsUsingUnitAndOp(value, unit, operation);
  102. },
  103. [unit, operation]
  104. );
  105. const samples = useChartSamples({
  106. chartRef,
  107. correlations: scatter?.data,
  108. onClick: scatter?.onClick,
  109. highlightedSampleId: scatter?.higlightedId,
  110. operation,
  111. timeseries: series,
  112. valueFormatter,
  113. });
  114. const chartProps = useMemo(() => {
  115. const timeseriesFormatters = {
  116. valueFormatter,
  117. isGroupedByDate: true,
  118. bucketSize,
  119. showTimeInTooltip: true,
  120. addSecondsToTimeFormat: isSubMinuteBucket,
  121. limit: 10,
  122. filter: (_, seriesParam) => {
  123. return seriesParam?.axisId === 'xAxis';
  124. },
  125. };
  126. const heightOptions = height ? {height} : {autoHeightResize: true};
  127. return {
  128. ...heightOptions,
  129. ...focusAreaBrush.options,
  130. forwardedRef: mergeRefs([forwardedRef, chartRef]),
  131. series: seriesToShow,
  132. devicePixelRatio: 2,
  133. renderer: 'canvas' as const,
  134. isGroupedByDate: true,
  135. colors: seriesToShow.map(s => s.color),
  136. grid: {top: 5, bottom: 0, left: 0, right: 0},
  137. onClick: samples.handleClick,
  138. tooltip: {
  139. formatter: (params, asyncTicket) => {
  140. if (focusAreaBrush.isDrawingRef.current) {
  141. return '';
  142. }
  143. if (!isChartHovered(chartRef?.current)) {
  144. return '';
  145. }
  146. // Hovering a single correlated sample datapoint
  147. if (params.seriesType === 'scatter') {
  148. return getFormatter(samples.formatters)(params, asyncTicket);
  149. }
  150. // The mechanism by which we add the fog of war series to the chart, duplicates the series in the chart data
  151. // so we need to deduplicate the series before showing the tooltip
  152. // this assumes that the first series is the main series and the second is the fog of war series
  153. if (Array.isArray(params)) {
  154. const uniqueSeries = new Set<string>();
  155. const deDupedParams = params.filter(param => {
  156. if (uniqueSeries.has(param.seriesName)) {
  157. return false;
  158. }
  159. uniqueSeries.add(param.seriesName);
  160. return true;
  161. });
  162. return getFormatter(timeseriesFormatters)(deDupedParams, asyncTicket);
  163. }
  164. return getFormatter(timeseriesFormatters)(params, asyncTicket);
  165. },
  166. },
  167. yAxes: [
  168. {
  169. // used to find and convert datapoint to pixel position
  170. id: 'yAxis',
  171. axisLabel: {
  172. formatter: (value: number) => {
  173. return valueFormatter(value);
  174. },
  175. },
  176. },
  177. samples.yAxis,
  178. ],
  179. xAxes: [
  180. {
  181. // used to find and convert datapoint to pixel position
  182. id: 'xAxis',
  183. axisPointer: {
  184. snap: true,
  185. },
  186. },
  187. samples.xAxis,
  188. ],
  189. };
  190. }, [
  191. bucketSize,
  192. focusAreaBrush.options,
  193. focusAreaBrush.isDrawingRef,
  194. forwardedRef,
  195. isSubMinuteBucket,
  196. seriesToShow,
  197. height,
  198. samples.handleClick,
  199. samples.xAxis,
  200. samples.yAxis,
  201. samples.formatters,
  202. valueFormatter,
  203. ]);
  204. return (
  205. <ChartWrapper>
  206. {focusAreaBrush.overlay}
  207. <CombinedChart
  208. {...chartProps}
  209. displayType={displayType}
  210. scatterSeries={samples.series}
  211. />
  212. </ChartWrapper>
  213. );
  214. }
  215. );
  216. interface CombinedChartProps extends BaseChartProps {
  217. displayType: MetricDisplayType;
  218. series: Series[];
  219. scatterSeries?: ScatterSeriesType[];
  220. }
  221. function CombinedChart({
  222. displayType,
  223. series,
  224. scatterSeries = [],
  225. ...chartProps
  226. }: CombinedChartProps) {
  227. const combinedSeries = useMemo(() => {
  228. if (displayType === MetricDisplayType.LINE) {
  229. return [
  230. ...transformToLineSeries({series}),
  231. ...transformToScatterSeries({series: scatterSeries, displayType}),
  232. ];
  233. }
  234. if (displayType === MetricDisplayType.BAR) {
  235. return [
  236. ...transformToBarSeries({series, stacked: true, animation: false}),
  237. ...transformToScatterSeries({series: scatterSeries, displayType}),
  238. ];
  239. }
  240. if (displayType === MetricDisplayType.AREA) {
  241. return [
  242. ...transformToAreaSeries({series, stacked: true, colors: chartProps.colors}),
  243. ...transformToScatterSeries({series: scatterSeries, displayType}),
  244. ];
  245. }
  246. return [];
  247. }, [displayType, scatterSeries, series, chartProps.colors]);
  248. return <BaseChart {...chartProps} series={combinedSeries} />;
  249. }
  250. function transformToScatterSeries({
  251. series,
  252. displayType,
  253. }: {
  254. displayType: MetricDisplayType;
  255. series: Series[];
  256. }) {
  257. return series.map(({seriesName, data: seriesData, ...options}) => {
  258. if (displayType === MetricDisplayType.BAR) {
  259. return ScatterSeries({
  260. ...options,
  261. name: seriesName,
  262. data: seriesData?.map(({value, name}) => ({value: [name, value]})),
  263. });
  264. }
  265. return ScatterSeries({
  266. ...options,
  267. name: seriesName,
  268. data: seriesData?.map(({value, name}) => [name, value]),
  269. animation: false,
  270. });
  271. });
  272. }
  273. const EXTRAPOLATED_AREA_STRIPE_IMG =
  274. 'image://data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAABkCAYAAAC/zKGXAAAAMUlEQVR4Ae3KoREAIAwEsMKgrMeYj8BzyIpEZyTZda16mPVJFEVRFEVRFEVRFMWO8QB4uATKpuU51gAAAABJRU5ErkJggg==';
  275. const createFogOfWarBarSeries = (series: Series, fogBucketCnt = 0) => ({
  276. ...series,
  277. silent: true,
  278. data: series.data.map((data, index) => ({
  279. ...data,
  280. // W need to set a value for the non-fog of war buckets so that the stacking still works in echarts
  281. value: index < series.data.length - fogBucketCnt ? 0 : data.value,
  282. })),
  283. itemStyle: {
  284. opacity: 1,
  285. decal: {
  286. symbol: EXTRAPOLATED_AREA_STRIPE_IMG,
  287. dashArrayX: [6, 0],
  288. dashArrayY: [6, 0],
  289. rotation: Math.PI / 4,
  290. },
  291. },
  292. });
  293. const createFogOfWarLineSeries = (series: Series, fogBucketCnt = 0) => ({
  294. ...series,
  295. silent: true,
  296. // We include the last non-fog of war bucket so that the line is connected
  297. data: series.data.slice(-fogBucketCnt - 1),
  298. lineStyle: {
  299. type: 'dotted',
  300. },
  301. });
  302. const createFogOfWarAreaSeries = (series: Series, fogBucketCnt = 0) => ({
  303. ...series,
  304. silent: true,
  305. stack: 'fogOfWar',
  306. // We include the last non-fog of war bucket so that the line is connected
  307. data: series.data.slice(-fogBucketCnt - 1),
  308. lineStyle: {
  309. type: 'dotted',
  310. color: Color(series.color).lighten(0.3).string(),
  311. },
  312. });
  313. function getWidthFactor(bucketSize: number) {
  314. // If the bucket size is >= 5 minutes the fog of war should only cover the last bucket
  315. if (bucketSize >= 5 * 60_000) {
  316. return 1;
  317. }
  318. // for buckets <= 10s we want to show a fog of war that spans last 10 buckets
  319. // because on average, we are missing last 90 seconds of data
  320. if (bucketSize <= 10_000) {
  321. return 10;
  322. }
  323. // For smaller time frames we want to show a wider fog of war
  324. return 2;
  325. }
  326. const ChartWrapper = styled('div')`
  327. position: relative;
  328. height: 100%;
  329. `;