chart.tsx 7.1 KB

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