chart.tsx 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. import {forwardRef, useCallback, useEffect, useMemo, useRef} from 'react';
  2. import styled from '@emotion/styled';
  3. import {useHover} from '@react-aria/interactions';
  4. import * as Sentry from '@sentry/react';
  5. import * as echarts from 'echarts/core';
  6. import {CanvasRenderer} from 'echarts/renderers';
  7. import {updateDateTime} from 'sentry/actionCreators/pageFilters';
  8. import {AreaChart} from 'sentry/components/charts/areaChart';
  9. import {BarChart} from 'sentry/components/charts/barChart';
  10. import {LineChart} from 'sentry/components/charts/lineChart';
  11. import {DateTimeObject} from 'sentry/components/charts/utils';
  12. import {ReactEchartsRef} from 'sentry/types/echarts';
  13. import mergeRefs from 'sentry/utils/mergeRefs';
  14. import {
  15. formatMetricsUsingUnitAndOp,
  16. isCumulativeOp,
  17. MetricDisplayType,
  18. } from 'sentry/utils/metrics';
  19. import useRouter from 'sentry/utils/useRouter';
  20. import {FocusArea, useFocusAreaBrush} from 'sentry/views/ddm/chartBrush';
  21. import {DDM_CHART_GROUP} from 'sentry/views/ddm/constants';
  22. import {getFormatter} from '../../components/charts/components/tooltip';
  23. import {Series} from './widget';
  24. type ChartProps = {
  25. displayType: MetricDisplayType;
  26. focusArea: FocusArea | null;
  27. series: Series[];
  28. widgetIndex: number;
  29. addFocusArea?: (area: FocusArea) => void;
  30. height?: number;
  31. operation?: string;
  32. removeFocusArea?: () => void;
  33. };
  34. // We need to enable canvas renderer for echarts before we use it here.
  35. // Once we use it in more places, this should probably move to a more global place
  36. // But for now we keep it here to not invluence the bundle size of the main chunks.
  37. echarts.use(CanvasRenderer);
  38. export const MetricChart = forwardRef<ReactEchartsRef, ChartProps>(
  39. (
  40. {
  41. series,
  42. displayType,
  43. operation,
  44. widgetIndex,
  45. addFocusArea,
  46. focusArea,
  47. removeFocusArea,
  48. height,
  49. },
  50. forwardedRef
  51. ) => {
  52. const router = useRouter();
  53. const chartRef = useRef<ReactEchartsRef>(null);
  54. const {hoverProps, isHovered} = useHover({
  55. isDisabled: false,
  56. });
  57. const handleZoom = useCallback(
  58. (range: DateTimeObject) => {
  59. Sentry.metrics.increment('ddm.enhance.zoom');
  60. updateDateTime(range, router, {save: true});
  61. },
  62. [router]
  63. );
  64. const focusAreaBrush = useFocusAreaBrush(
  65. chartRef,
  66. focusArea,
  67. {
  68. widgetIndex,
  69. isDisabled: !isHovered || !addFocusArea || !removeFocusArea || !handleZoom,
  70. useFullYAxis: isCumulativeOp(operation),
  71. },
  72. addFocusArea,
  73. removeFocusArea,
  74. handleZoom
  75. );
  76. // TODO(ddm): Try to do this in a more elegant way
  77. useEffect(() => {
  78. const echartsInstance = chartRef?.current?.getEchartsInstance();
  79. if (echartsInstance && !echartsInstance.group) {
  80. echartsInstance.group = DDM_CHART_GROUP;
  81. }
  82. });
  83. const unit = series[0]?.unit;
  84. const seriesToShow = useMemo(
  85. () =>
  86. series
  87. .filter(s => !s.hidden)
  88. .map(s => ({...s, silent: displayType === MetricDisplayType.BAR})),
  89. [series, displayType]
  90. );
  91. // TODO(ddm): This assumes that all series have the same bucket size
  92. const bucketSize = seriesToShow[0]?.data[1]?.name - seriesToShow[0]?.data[0]?.name;
  93. const isSubMinuteBucket = bucketSize < 60_000;
  94. const seriesLength = seriesToShow[0]?.data.length;
  95. const displayFogOfWar = isCumulativeOp(operation);
  96. const chartProps = useMemo(() => {
  97. const formatters = {
  98. valueFormatter: (value: number) =>
  99. formatMetricsUsingUnitAndOp(value, unit, operation),
  100. isGroupedByDate: true,
  101. bucketSize,
  102. showTimeInTooltip: true,
  103. addSecondsToTimeFormat: isSubMinuteBucket,
  104. limit: 10,
  105. };
  106. const heightOptions = height ? {height} : {autoHeightResize: true};
  107. return {
  108. ...heightOptions,
  109. ...focusAreaBrush.options,
  110. forwardedRef: mergeRefs([forwardedRef, chartRef]),
  111. series: seriesToShow,
  112. renderer: seriesToShow.length > 20 ? ('canvas' as const) : ('svg' as const),
  113. isGroupedByDate: true,
  114. height,
  115. colors: seriesToShow.map(s => s.color),
  116. grid: {top: 20, bottom: 20, left: 15, right: 25},
  117. tooltip: {
  118. formatter: (params, asyncTicket) => {
  119. if (focusAreaBrush.isDrawingRef.current) {
  120. return '';
  121. }
  122. const hoveredEchartElement = Array.from(
  123. document.querySelectorAll(':hover')
  124. ).find(element => {
  125. return element.classList.contains('echarts-for-react');
  126. });
  127. if (hoveredEchartElement === chartRef?.current?.ele) {
  128. return getFormatter(formatters)(params, asyncTicket);
  129. }
  130. return '';
  131. },
  132. },
  133. yAxis: {
  134. // used to find and convert datapoint to pixel position
  135. id: 'yAxis',
  136. axisLabel: {
  137. formatter: (value: number) => {
  138. return formatMetricsUsingUnitAndOp(value, unit, operation);
  139. },
  140. },
  141. },
  142. xAxis: {
  143. // used to find and convert datapoint to pixel position
  144. id: 'xAxis',
  145. axisPointer: {
  146. snap: true,
  147. },
  148. },
  149. };
  150. }, [
  151. bucketSize,
  152. focusAreaBrush.options,
  153. focusAreaBrush.isDrawingRef,
  154. forwardedRef,
  155. isSubMinuteBucket,
  156. operation,
  157. seriesToShow,
  158. unit,
  159. height,
  160. ]);
  161. return (
  162. <ChartWrapper {...hoverProps} onMouseDownCapture={focusAreaBrush.startBrush}>
  163. {focusAreaBrush.overlay}
  164. {displayType === MetricDisplayType.LINE ? (
  165. <LineChart {...chartProps} />
  166. ) : displayType === MetricDisplayType.AREA ? (
  167. <AreaChart stacked {...chartProps} />
  168. ) : (
  169. <BarChart stacked animation={false} {...chartProps} />
  170. )}
  171. {displayFogOfWar && (
  172. <FogOfWar bucketSize={bucketSize} seriesLength={seriesLength} />
  173. )}
  174. </ChartWrapper>
  175. );
  176. }
  177. );
  178. function FogOfWar({
  179. bucketSize,
  180. seriesLength,
  181. }: {
  182. bucketSize?: number;
  183. seriesLength?: number;
  184. }) {
  185. if (!bucketSize || !seriesLength) {
  186. return null;
  187. }
  188. const widthFactor = getWidthFactor(bucketSize);
  189. const fogOfWarWidth = widthFactor * bucketSize + 30_000;
  190. const seriesWidth = bucketSize * seriesLength;
  191. // If either of these are undefiend, NaN or 0 the result will be invalid
  192. if (!fogOfWarWidth || !seriesWidth) {
  193. return null;
  194. }
  195. const width = (fogOfWarWidth / seriesWidth) * 100;
  196. return <FogOfWarOverlay width={width ?? 0} />;
  197. }
  198. function getWidthFactor(bucketSize: number) {
  199. // In general, fog of war should cover the last bucket
  200. if (bucketSize > 30 * 60_000) {
  201. return 1;
  202. }
  203. // for 10s timeframe we want to show a fog of war that spans last 10 buckets
  204. // because on average, we are missing last 90 seconds of data
  205. if (bucketSize <= 10_000) {
  206. return 10;
  207. }
  208. // For smaller time frames we want to show a wider fog of war
  209. return 2;
  210. }
  211. const ChartWrapper = styled('div')`
  212. position: relative;
  213. `;
  214. const FogOfWarOverlay = styled('div')<{width?: number}>`
  215. height: calc(100% - 56px);
  216. width: ${p => p.width}%;
  217. position: absolute;
  218. right: 21px;
  219. top: 18px;
  220. pointer-events: none;
  221. background: linear-gradient(
  222. 90deg,
  223. ${p => p.theme.background}00 0%,
  224. ${p => p.theme.background}FF 70%,
  225. ${p => p.theme.background}FF 100%
  226. );
  227. `;