focusArea.tsx 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. import type {RefObject} from 'react';
  2. import {Fragment, useCallback, useEffect, useMemo, useRef, useState} from 'react';
  3. import {useTheme} from '@emotion/react';
  4. import styled from '@emotion/styled';
  5. import {useResizeObserver} from '@react-aria/utils';
  6. import color from 'color';
  7. import type {EChartsOption} from 'echarts';
  8. import moment from 'moment';
  9. import {Button} from 'sentry/components/button';
  10. import {IconClose, IconZoom} from 'sentry/icons';
  11. import {space} from 'sentry/styles/space';
  12. import type {EChartBrushEndHandler, ReactEchartsRef} from 'sentry/types/echarts';
  13. import type {MetricRange} from 'sentry/utils/metrics/types';
  14. import {isInRect} from 'sentry/views/ddm/rect';
  15. import type {DateTimeObject} from '../../components/charts/utils';
  16. interface AbsolutePosition {
  17. height: string;
  18. left: string;
  19. top: string;
  20. width: string;
  21. }
  22. export interface FocusArea {
  23. range: MetricRange;
  24. widgetIndex: number;
  25. }
  26. interface UseFocusAreaOptions {
  27. widgetIndex: number;
  28. isDisabled?: boolean;
  29. useFullYAxis?: boolean;
  30. }
  31. type BrushEndResult = Parameters<EChartBrushEndHandler>[0];
  32. type UseFocusAreaProps = {
  33. chartRef: RefObject<ReactEchartsRef>;
  34. focusArea: FocusArea | null;
  35. opts: UseFocusAreaOptions;
  36. onAdd?: (area: FocusArea) => void;
  37. onDraw?: () => void;
  38. onRemove?: () => void;
  39. onZoom?: (range: DateTimeObject) => void;
  40. };
  41. export function useFocusArea({
  42. chartRef,
  43. focusArea,
  44. opts: {widgetIndex, isDisabled, useFullYAxis},
  45. onAdd,
  46. onDraw,
  47. onRemove,
  48. onZoom,
  49. }: UseFocusAreaProps) {
  50. const hasFocusArea = useMemo(
  51. () => focusArea && focusArea.widgetIndex === widgetIndex,
  52. [focusArea, widgetIndex]
  53. );
  54. const isDrawingRef = useRef(false);
  55. const theme = useTheme();
  56. const startBrush = useCallback(() => {
  57. if (hasFocusArea || isDisabled) {
  58. return;
  59. }
  60. onDraw?.();
  61. chartRef.current?.getEchartsInstance().dispatchAction({
  62. type: 'takeGlobalCursor',
  63. key: 'brush',
  64. brushOption: {
  65. brushType: 'rect',
  66. },
  67. });
  68. isDrawingRef.current = true;
  69. }, [chartRef, hasFocusArea, isDisabled, onDraw]);
  70. useEffect(() => {
  71. const handleMouseDown = event => {
  72. const rect = chartRef.current?.ele.getBoundingClientRect();
  73. if (isInRect(event.clientX, event.clientY, rect)) {
  74. startBrush();
  75. }
  76. };
  77. window.addEventListener('mousedown', handleMouseDown, {capture: true});
  78. return () => {
  79. window.removeEventListener('mousedown', handleMouseDown, {capture: true});
  80. };
  81. }, [chartRef, startBrush]);
  82. const onBrushEnd = useCallback(
  83. (brushEnd: BrushEndResult) => {
  84. if (isDisabled || !isDrawingRef.current) {
  85. return;
  86. }
  87. const rect = brushEnd.areas[0];
  88. if (!rect) {
  89. return;
  90. }
  91. onAdd?.({
  92. widgetIndex,
  93. range: getMetricRange(brushEnd, !!useFullYAxis),
  94. });
  95. // Remove brush from echarts immediately after adding the focus area
  96. // since brushes get added to all charts in the group by default and then randomly
  97. // render in the wrong place
  98. chartRef.current?.getEchartsInstance().dispatchAction({
  99. type: 'brush',
  100. brushType: 'clear',
  101. areas: [],
  102. });
  103. isDrawingRef.current = false;
  104. },
  105. [chartRef, isDisabled, onAdd, widgetIndex, useFullYAxis]
  106. );
  107. const handleRemove = useCallback(() => {
  108. onRemove?.();
  109. }, [onRemove]);
  110. const handleZoomIn = useCallback(() => {
  111. onZoom?.({
  112. period: null,
  113. ...focusArea?.range,
  114. });
  115. handleRemove();
  116. }, [focusArea, handleRemove, onZoom]);
  117. const brushOptions = useMemo(() => {
  118. return {
  119. onBrushEnd,
  120. toolBox: {
  121. show: false,
  122. },
  123. brush: {
  124. toolbox: ['rect'],
  125. xAxisIndex: 0,
  126. brushStyle: {
  127. borderWidth: 2,
  128. borderColor: theme.gray500,
  129. color: 'transparent',
  130. },
  131. inBrush: {
  132. opacity: 1,
  133. },
  134. outOfBrush: {
  135. opacity: 1,
  136. },
  137. z: 10,
  138. } as EChartsOption['brush'],
  139. };
  140. }, [onBrushEnd, theme.gray500]);
  141. if (hasFocusArea) {
  142. return {
  143. overlay: (
  144. <BrushRectOverlay
  145. rect={focusArea}
  146. onRemove={handleRemove}
  147. onZoom={handleZoomIn}
  148. chartRef={chartRef}
  149. useFullYAxis={!!useFullYAxis}
  150. />
  151. ),
  152. isDrawingRef,
  153. options: {},
  154. };
  155. }
  156. return {
  157. overlay: null,
  158. isDrawingRef,
  159. options: brushOptions,
  160. };
  161. }
  162. type BrushRectOverlayProps = {
  163. chartRef: RefObject<ReactEchartsRef>;
  164. onRemove: () => void;
  165. onZoom: () => void;
  166. rect: FocusArea | null;
  167. useFullYAxis: boolean;
  168. };
  169. function BrushRectOverlay({
  170. rect,
  171. onZoom,
  172. onRemove,
  173. useFullYAxis,
  174. chartRef,
  175. }: BrushRectOverlayProps) {
  176. const chartInstance = chartRef.current?.getEchartsInstance();
  177. const [position, setPosition] = useState<AbsolutePosition | null>(null);
  178. const wrapperRef = useRef<HTMLDivElement>(null);
  179. useResizeObserver({
  180. ref: wrapperRef,
  181. onResize: () => {
  182. chartInstance?.resize();
  183. updatePosition();
  184. },
  185. });
  186. const updatePosition = useCallback(() => {
  187. if (!rect || !chartInstance) {
  188. return;
  189. }
  190. const finder = {xAxisId: 'xAxis', yAxisId: 'yAxis'};
  191. const topLeft = chartInstance.convertToPixel(finder, [
  192. getTimestamp(rect.range.start),
  193. rect.range.max,
  194. ] as number[]);
  195. const bottomRight = chartInstance.convertToPixel(finder, [
  196. getTimestamp(rect.range.end),
  197. rect.range.min,
  198. ] as number[]);
  199. if (!topLeft || !bottomRight) {
  200. return;
  201. }
  202. const widthPx = bottomRight[0] - topLeft[0];
  203. const heightPx = bottomRight[1] - topLeft[1];
  204. const resultTop = useFullYAxis ? '0px' : `${topLeft[1].toPrecision(5)}px`;
  205. const resultHeight = useFullYAxis
  206. ? `${CHART_HEIGHT}px`
  207. : `${heightPx.toPrecision(5)}px`;
  208. // Ensure the focus area rect is always within the chart bounds
  209. const left = Math.max(topLeft[0], 0);
  210. const width = Math.min(widthPx, chartInstance.getWidth() - left);
  211. setPosition({
  212. left: `${left.toPrecision(5)}px`,
  213. top: resultTop,
  214. width: `${width.toPrecision(5)}px`,
  215. height: resultHeight,
  216. });
  217. }, [rect, chartInstance, useFullYAxis]);
  218. useEffect(() => {
  219. updatePosition();
  220. }, [rect, updatePosition]);
  221. if (!position) {
  222. return null;
  223. }
  224. const {left, top, width, height} = position;
  225. return (
  226. <Fragment>
  227. <FocusAreaWrapper ref={wrapperRef}>
  228. <FocusAreaRect top={top} left={left} width={width} height={height} />
  229. </FocusAreaWrapper>
  230. <FocusAreaRectActions top={top} rectHeight={height} left={left}>
  231. <Button
  232. size="xs"
  233. onClick={onZoom}
  234. icon={<IconZoom isZoomIn />}
  235. aria-label="zoom"
  236. />
  237. <Button size="xs" onClick={onRemove} icon={<IconClose />} aria-label="remove" />
  238. </FocusAreaRectActions>
  239. </Fragment>
  240. );
  241. }
  242. const getDate = date =>
  243. date ? moment.utc(date).format(moment.HTML5_FMT.DATETIME_LOCAL_SECONDS) : null;
  244. const getTimestamp = date => (date ? moment.utc(date).valueOf() : null);
  245. const getMetricRange = (params: BrushEndResult, useFullYAxis: boolean): MetricRange => {
  246. const rect = params.areas[0];
  247. const startTimestamp = Math.min(...rect.coordRange[0]);
  248. const endTimestamp = Math.max(...rect.coordRange[0]);
  249. const startDate = getDate(startTimestamp);
  250. const endDate = getDate(endTimestamp);
  251. const min = useFullYAxis ? NaN : Math.min(...rect.coordRange[1]);
  252. const max = useFullYAxis ? NaN : Math.max(...rect.coordRange[1]);
  253. return {
  254. start: startDate,
  255. end: endDate,
  256. min,
  257. max,
  258. };
  259. };
  260. const CHART_HEIGHT = 275;
  261. const FocusAreaRectActions = styled('div')<{
  262. left: string;
  263. rectHeight: string;
  264. top: string;
  265. }>`
  266. position: absolute;
  267. top: calc(${p => p.top} + ${p => p.rectHeight});
  268. left: ${p => p.left};
  269. display: flex;
  270. gap: ${space(0.5)};
  271. padding: ${space(0.5)};
  272. z-index: 2;
  273. pointer-events: auto;
  274. `;
  275. const FocusAreaWrapper = styled('div')`
  276. position: absolute;
  277. top: 0px;
  278. left: 0;
  279. height: 100%;
  280. width: 100%;
  281. overflow: hidden;
  282. `;
  283. const FocusAreaRect = styled('div')<{
  284. height: string;
  285. left: string;
  286. top: string;
  287. width: string;
  288. }>`
  289. position: absolute;
  290. top: ${p => p.top};
  291. left: ${p => p.left};
  292. width: ${p => p.width};
  293. height: ${p => p.height};
  294. padding: ${space(1)};
  295. pointer-events: none;
  296. z-index: 1;
  297. border: 2px solid ${p => p.theme.gray500};
  298. border-radius: ${p => p.theme.borderRadius};
  299. /* requires overflow: hidden on FocusAreaWrapper */
  300. box-shadow: 0px 0px 0px 9999px ${p => color(p.theme.surface400).alpha(0.75).toString()};
  301. `;