focusArea.tsx 8.9 KB

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