focusArea.tsx 8.5 KB

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