chart.tsx 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. import {forwardRef, useCallback, useEffect, useMemo, useRef} from 'react';
  2. import styled from '@emotion/styled';
  3. import * as Sentry from '@sentry/react';
  4. import * as echarts from 'echarts/core';
  5. import {CanvasRenderer} from 'echarts/renderers';
  6. import {updateDateTime} from 'sentry/actionCreators/pageFilters';
  7. import {transformToAreaSeries} from 'sentry/components/charts/areaChart';
  8. import {transformToBarSeries} from 'sentry/components/charts/barChart';
  9. import type {BaseChartProps} from 'sentry/components/charts/baseChart';
  10. import BaseChart from 'sentry/components/charts/baseChart';
  11. import {transformToLineSeries} from 'sentry/components/charts/lineChart';
  12. import ScatterSeries from 'sentry/components/charts/series/scatterSeries';
  13. import type {DateTimeObject} from 'sentry/components/charts/utils';
  14. import type {ReactEchartsRef} from 'sentry/types/echarts';
  15. import mergeRefs from 'sentry/utils/mergeRefs';
  16. import {isCumulativeOp} from 'sentry/utils/metrics';
  17. import {formatMetricsUsingUnitAndOp} from 'sentry/utils/metrics/formatters';
  18. import {MetricDisplayType} from 'sentry/utils/metrics/types';
  19. import useRouter from 'sentry/utils/useRouter';
  20. import {DDM_CHART_GROUP} from 'sentry/views/ddm/constants';
  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 {useChartSamples} from './useChartSamples';
  25. import type {SamplesProps, ScatterSeries as ScatterSeriesType, Series} from './widget';
  26. type ChartProps = {
  27. displayType: MetricDisplayType;
  28. series: Series[];
  29. widgetIndex: number;
  30. focusArea?: FocusAreaProps;
  31. height?: number;
  32. operation?: string;
  33. scatter?: SamplesProps;
  34. };
  35. // We need to enable canvas renderer for echarts before we use it here.
  36. // Once we use it in more places, this should probably move to a more global place
  37. // But for now we keep it here to not invluence the bundle size of the main chunks.
  38. echarts.use(CanvasRenderer);
  39. export const MetricChart = forwardRef<ReactEchartsRef, ChartProps>(
  40. (
  41. {series, displayType, operation, widgetIndex, focusArea, height, scatter},
  42. forwardedRef
  43. ) => {
  44. const router = useRouter();
  45. const chartRef = useRef<ReactEchartsRef>(null);
  46. const handleZoom = useCallback(
  47. (range: DateTimeObject) => {
  48. Sentry.metrics.increment('ddm.enhance.zoom');
  49. updateDateTime(range, router, {save: true});
  50. },
  51. [router]
  52. );
  53. const focusAreaBrush = useFocusArea({
  54. ...focusArea,
  55. chartRef,
  56. opts: {
  57. widgetIndex,
  58. isDisabled: !focusArea?.onAdd || !handleZoom,
  59. useFullYAxis: isCumulativeOp(operation),
  60. },
  61. onZoom: handleZoom,
  62. });
  63. useEffect(() => {
  64. const echartsInstance = chartRef?.current?.getEchartsInstance();
  65. if (echartsInstance && !echartsInstance.group) {
  66. echartsInstance.group = DDM_CHART_GROUP;
  67. }
  68. });
  69. const unit = series[0]?.unit;
  70. const seriesToShow = useMemo(
  71. () =>
  72. series
  73. .filter(s => !s.hidden)
  74. .map(s => ({
  75. ...s,
  76. silent: true,
  77. })),
  78. [series]
  79. );
  80. const valueFormatter = useCallback(
  81. (value: number) => {
  82. return formatMetricsUsingUnitAndOp(value, unit, operation);
  83. },
  84. [unit, operation]
  85. );
  86. const samples = useChartSamples({
  87. chartRef,
  88. correlations: scatter?.data,
  89. onClick: scatter?.onClick,
  90. highlightedSampleId: scatter?.higlightedId,
  91. operation,
  92. timeseries: series,
  93. });
  94. // TODO(ddm): This assumes that all series have the same bucket size
  95. const bucketSize = seriesToShow[0]?.data[1]?.name - seriesToShow[0]?.data[0]?.name;
  96. const isSubMinuteBucket = bucketSize < 60_000;
  97. const seriesLength = seriesToShow[0]?.data.length;
  98. const displayFogOfWar = isCumulativeOp(operation);
  99. const chartProps = useMemo(() => {
  100. const timeseriesFormatters = {
  101. valueFormatter,
  102. isGroupedByDate: true,
  103. bucketSize,
  104. showTimeInTooltip: true,
  105. addSecondsToTimeFormat: isSubMinuteBucket,
  106. limit: 10,
  107. filter: (_, seriesParam) => {
  108. return seriesParam?.axisId === 'xAxis';
  109. },
  110. };
  111. const heightOptions = height ? {height} : {autoHeightResize: true};
  112. return {
  113. ...heightOptions,
  114. ...focusAreaBrush.options,
  115. forwardedRef: mergeRefs([forwardedRef, chartRef]),
  116. series: seriesToShow,
  117. renderer: seriesToShow.length > 20 ? ('canvas' as const) : ('svg' as const),
  118. isGroupedByDate: true,
  119. colors: seriesToShow.map(s => s.color),
  120. grid: {top: 5, bottom: 0, left: 0, right: 0},
  121. onClick: samples.handleClick,
  122. tooltip: {
  123. formatter: (params, asyncTicket) => {
  124. if (focusAreaBrush.isDrawingRef.current) {
  125. return '';
  126. }
  127. const hoveredEchartElement = Array.from(
  128. document.querySelectorAll(':hover')
  129. ).find(element => {
  130. return element.classList.contains('echarts-for-react');
  131. });
  132. const isThisChartHovered = hoveredEchartElement === chartRef?.current?.ele;
  133. if (!isThisChartHovered) {
  134. return '';
  135. }
  136. if (params.seriesType === 'scatter') {
  137. return getFormatter(samples.formatters)(params, asyncTicket);
  138. }
  139. return getFormatter(timeseriesFormatters)(params, asyncTicket);
  140. },
  141. },
  142. yAxes: [
  143. {
  144. // used to find and convert datapoint to pixel position
  145. id: 'yAxis',
  146. axisLabel: {
  147. formatter: (value: number) => {
  148. return valueFormatter(value);
  149. },
  150. },
  151. },
  152. samples.yAxis,
  153. ],
  154. xAxes: [
  155. {
  156. // used to find and convert datapoint to pixel position
  157. id: 'xAxis',
  158. axisPointer: {
  159. snap: true,
  160. },
  161. },
  162. samples.xAxis,
  163. ],
  164. };
  165. }, [
  166. bucketSize,
  167. focusAreaBrush.options,
  168. focusAreaBrush.isDrawingRef,
  169. forwardedRef,
  170. isSubMinuteBucket,
  171. seriesToShow,
  172. height,
  173. samples.handleClick,
  174. samples.xAxis,
  175. samples.yAxis,
  176. samples.formatters,
  177. valueFormatter,
  178. ]);
  179. return (
  180. <ChartWrapper>
  181. {focusAreaBrush.overlay}
  182. <CombinedChart
  183. {...chartProps}
  184. displayType={displayType}
  185. scatterSeries={samples.series}
  186. />
  187. {displayFogOfWar && (
  188. <FogOfWar bucketSize={bucketSize} seriesLength={seriesLength} />
  189. )}
  190. </ChartWrapper>
  191. );
  192. }
  193. );
  194. interface CombinedChartProps extends BaseChartProps {
  195. displayType: MetricDisplayType;
  196. series: Series[];
  197. scatterSeries?: ScatterSeriesType[];
  198. }
  199. function CombinedChart({
  200. displayType,
  201. series,
  202. scatterSeries = [],
  203. ...chartProps
  204. }: CombinedChartProps) {
  205. const combinedSeries = useMemo(() => {
  206. if (displayType === MetricDisplayType.LINE) {
  207. return [
  208. ...transformToLineSeries({series}),
  209. ...transformToScatterSeries({series: scatterSeries, displayType}),
  210. ];
  211. }
  212. if (displayType === MetricDisplayType.BAR) {
  213. return [
  214. ...transformToBarSeries({series, stacked: true, animation: false}),
  215. ...transformToScatterSeries({series: scatterSeries, displayType}),
  216. ];
  217. }
  218. if (displayType === MetricDisplayType.AREA) {
  219. return [
  220. ...transformToAreaSeries({series, stacked: true, colors: chartProps.colors}),
  221. ...transformToScatterSeries({series: scatterSeries, displayType}),
  222. ];
  223. }
  224. return [];
  225. }, [displayType, scatterSeries, series, chartProps.colors]);
  226. return <BaseChart {...chartProps} series={combinedSeries} />;
  227. }
  228. function transformToScatterSeries({
  229. series,
  230. displayType,
  231. }: {
  232. displayType: MetricDisplayType;
  233. series: Series[];
  234. }) {
  235. return series.map(({seriesName, data: seriesData, ...options}) => {
  236. if (displayType === MetricDisplayType.BAR) {
  237. return ScatterSeries({
  238. ...options,
  239. name: seriesName,
  240. data: seriesData?.map(({value, name}) => ({value: [name, value]})),
  241. });
  242. }
  243. return ScatterSeries({
  244. ...options,
  245. name: seriesName,
  246. data: seriesData?.map(({value, name}) => [name, value]),
  247. animation: false,
  248. });
  249. });
  250. }
  251. function FogOfWar({
  252. bucketSize,
  253. seriesLength,
  254. }: {
  255. bucketSize?: number;
  256. seriesLength?: number;
  257. }) {
  258. if (!bucketSize || !seriesLength) {
  259. return null;
  260. }
  261. const widthFactor = getWidthFactor(bucketSize);
  262. const fogOfWarWidth = widthFactor * bucketSize + 30_000;
  263. const seriesWidth = bucketSize * seriesLength;
  264. // If either of these are undefiend, NaN or 0 the result will be invalid
  265. if (!fogOfWarWidth || !seriesWidth) {
  266. return null;
  267. }
  268. const width = (fogOfWarWidth / seriesWidth) * 100;
  269. return <FogOfWarOverlay width={width ?? 0} />;
  270. }
  271. function getWidthFactor(bucketSize: number) {
  272. // In general, fog of war should cover the last bucket
  273. if (bucketSize > 30 * 60_000) {
  274. return 1;
  275. }
  276. // for 10s timeframe we want to show a fog of war that spans last 10 buckets
  277. // because on average, we are missing last 90 seconds of data
  278. if (bucketSize <= 10_000) {
  279. return 10;
  280. }
  281. // For smaller time frames we want to show a wider fog of war
  282. return 2;
  283. }
  284. const ChartWrapper = styled('div')`
  285. position: relative;
  286. height: 100%;
  287. `;
  288. const FogOfWarOverlay = styled('div')<{width?: number}>`
  289. height: calc(100% - 29px);
  290. width: ${p => p.width}%;
  291. position: absolute;
  292. right: 0px;
  293. top: 5px;
  294. pointer-events: none;
  295. background: linear-gradient(
  296. 90deg,
  297. ${p => p.theme.background}00 0%,
  298. ${p => p.theme.background}FF 70%,
  299. ${p => p.theme.background}FF 100%
  300. );
  301. `;